demo_3D_effect.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from PIL import Image
  2. import torch
  3. import torch.nn.functional as F
  4. import numpy as np
  5. from romatch.utils.utils import tensor_to_pil
  6. from romatch import roma_outdoor
  7. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  8. if torch.backends.mps.is_available():
  9. device = torch.device('mps')
  10. if __name__ == "__main__":
  11. from argparse import ArgumentParser
  12. parser = ArgumentParser()
  13. parser.add_argument("--im_A_path", default="assets/toronto_A.jpg", type=str)
  14. parser.add_argument("--im_B_path", default="assets/toronto_B.jpg", type=str)
  15. parser.add_argument("--save_path", default="demo/gif/roma_warp_toronto", type=str)
  16. args, _ = parser.parse_known_args()
  17. im1_path = args.im_A_path
  18. im2_path = args.im_B_path
  19. save_path = args.save_path
  20. # Create model
  21. roma_model = roma_outdoor(device=device, coarse_res=560, upsample_res=(864, 1152))
  22. roma_model.symmetric = False
  23. H, W = roma_model.get_output_resolution()
  24. im1 = Image.open(im1_path).resize((W, H))
  25. im2 = Image.open(im2_path).resize((W, H))
  26. # Match
  27. warp, certainty = roma_model.match(im1_path, im2_path, device=device)
  28. # Sampling not needed, but can be done with model.sample(warp, certainty)
  29. x1 = (torch.tensor(np.array(im1)) / 255).to(device).permute(2, 0, 1)
  30. x2 = (torch.tensor(np.array(im2)) / 255).to(device).permute(2, 0, 1)
  31. coords_A, coords_B = warp[...,:2], warp[...,2:]
  32. for i, x in enumerate(np.linspace(0,2*np.pi,200)):
  33. t = (1 + np.cos(x))/2
  34. interp_warp = (1-t)*coords_A + t*coords_B
  35. im2_transfer_rgb = F.grid_sample(
  36. x2[None], interp_warp[None], mode="bilinear", align_corners=False
  37. )[0]
  38. tensor_to_pil(im2_transfer_rgb, unnormalize=False).save(f"{save_path}_{i:03d}.jpg")