|
| 1 | +{ |
| 2 | + "cells": [ |
| 3 | + { |
| 4 | + "cell_type": "code", |
| 5 | + "execution_count": null, |
| 6 | + "id": "3306ccce-4b17-41a9-831d-add6cccddc0e", |
| 7 | + "metadata": {}, |
| 8 | + "outputs": [], |
| 9 | + "source": [ |
| 10 | + "import torch\n", |
| 11 | + "import torch.nn as nn\n", |
| 12 | + "import matplotlib.pyplot as plt\n", |
| 13 | + "import numpy as np\n", |
| 14 | + "import gc\n", |
| 15 | + "import imageio\n", |
| 16 | + "from PIL import Image\n", |
| 17 | + "from torchvision.transforms import PILToTensor\n", |
| 18 | + "import os\n", |
| 19 | + "import json\n", |
| 20 | + "from PIL import Image, ImageDraw\n", |
| 21 | + "import torch.nn.functional as F\n", |
| 22 | + "import cv2\n", |
| 23 | + "import glob\n", |
| 24 | + "from torchvision.transforms import PILToTensor\n", |
| 25 | + "from src.models.dift_sd import SDFeaturizer4Eval" |
| 26 | + ] |
| 27 | + }, |
| 28 | + { |
| 29 | + "cell_type": "code", |
| 30 | + "execution_count": null, |
| 31 | + "id": "081cd585-9d9d-4ffe-8c9b-6c6360d2e4ad", |
| 32 | + "metadata": {}, |
| 33 | + "outputs": [], |
| 34 | + "source": [ |
| 35 | + "def gen_grid(h, w, device, normalize=False, homogeneous=False):\n", |
| 36 | + " if normalize:\n", |
| 37 | + " lin_y = torch.linspace(-1., 1., steps=h, device=device)\n", |
| 38 | + " lin_x = torch.linspace(-1., 1., steps=w, device=device)\n", |
| 39 | + " else:\n", |
| 40 | + " lin_y = torch.arange(0, h, device=device)\n", |
| 41 | + " lin_x = torch.arange(0, w, device=device)\n", |
| 42 | + " grid_y, grid_x = torch.meshgrid((lin_y, lin_x))\n", |
| 43 | + " grid = torch.stack((grid_x, grid_y), -1)\n", |
| 44 | + " if homogeneous:\n", |
| 45 | + " grid = torch.cat([grid, torch.ones_like(grid[..., :1])], dim=-1)\n", |
| 46 | + " return grid # [h, w, 2 or 3]\n", |
| 47 | + "\n", |
| 48 | + "\n", |
| 49 | + "def normalize_coords(coords, h, w, no_shift=False):\n", |
| 50 | + " assert coords.shape[-1] == 2\n", |
| 51 | + " if no_shift:\n", |
| 52 | + " return coords / torch.tensor([w-1., h-1.], device=coords.device) * 2\n", |
| 53 | + " else:\n", |
| 54 | + " return coords / torch.tensor([w-1., h-1.], device=coords.device) * 2 - 1." |
| 55 | + ] |
| 56 | + }, |
| 57 | + { |
| 58 | + "cell_type": "code", |
| 59 | + "execution_count": null, |
| 60 | + "id": "2a13b459-4698-4a9c-803f-d7ba8adb6962", |
| 61 | + "metadata": {}, |
| 62 | + "outputs": [], |
| 63 | + "source": [ |
| 64 | + "cat = 'cat'\n", |
| 65 | + "dift = SDFeaturizer4Eval(cat_list=['cat'])" |
| 66 | + ] |
| 67 | + }, |
| 68 | + { |
| 69 | + "cell_type": "code", |
| 70 | + "execution_count": null, |
| 71 | + "id": "0606e9dd-9e51-49ec-bf37-1f2bc9f78a84", |
| 72 | + "metadata": {}, |
| 73 | + "outputs": [], |
| 74 | + "source": [ |
| 75 | + "src_img = Image.open('./assets/guitar_cat.jpg').convert('RGB')\n", |
| 76 | + "trg_img = Image.open('./assets/painting_cat.jpg').convert('RGB')\n", |
| 77 | + "sticker = imageio.imread('./assets/cartoon.png')\n", |
| 78 | + "sticker_color, sticker_mask = sticker[..., :3], sticker[..., 3]\n", |
| 79 | + "\n", |
| 80 | + "assert np.array(src_img).shape[:2] == sticker.shape[:2]\n", |
| 81 | + "h_src, w_src = sticker.shape[:2]\n", |
| 82 | + "h_trg, w_trg = np.array(trg_img).shape[:2]\n", |
| 83 | + "\n", |
| 84 | + "sd_feat_src = dift.forward(src_img, cat)\n", |
| 85 | + "sd_feat_trg = dift.forward(trg_img, cat)\n", |
| 86 | + "\n", |
| 87 | + "sd_feat_src = F.normalize(sd_feat_src.squeeze(), p=2, dim=0)\n", |
| 88 | + "sd_feat_trg = F.normalize(sd_feat_trg.squeeze(), p=2, dim=0)\n", |
| 89 | + "feat_dim = sd_feat_src.shape[0]\n", |
| 90 | + "\n", |
| 91 | + "grid_src = gen_grid(h_src, w_src, device='cuda')\n", |
| 92 | + "grid_trg = gen_grid(h_trg, w_trg, device='cuda')\n", |
| 93 | + "\n", |
| 94 | + "coord_src = grid_src[sticker_mask > 0]\n", |
| 95 | + "coord_src = coord_src[torch.randperm(len(coord_src))][:1000]\n", |
| 96 | + "coord_src_normed = normalize_coords(coord_src, h_src, w_src)\n", |
| 97 | + "grid_trg_normed = normalize_coords(grid_trg, h_trg, w_trg)\n", |
| 98 | + "\n", |
| 99 | + "feat_src = F.grid_sample(sd_feat_src[None], coord_src_normed[None, None], align_corners=True).squeeze().T\n", |
| 100 | + "feat_trg = F.grid_sample(sd_feat_trg[None], grid_trg_normed[None], align_corners=True).squeeze()\n", |
| 101 | + "feat_trg_flattened = feat_trg.permute(1, 2, 0).reshape(-1, feat_dim)\n", |
| 102 | + "\n", |
| 103 | + "distances = torch.cdist(feat_src, feat_trg_flattened)\n", |
| 104 | + "_, indices = torch.min(distances, dim=1)\n", |
| 105 | + "\n", |
| 106 | + "src_pts = coord_src.reshape(-1, 2).cpu().numpy()\n", |
| 107 | + "trg_pts = grid_trg.reshape(-1, 2)[indices].cpu().numpy()\n", |
| 108 | + "\n", |
| 109 | + "M, mask = cv2.findHomography(src_pts, trg_pts, cv2.RANSAC, 5.0)\n", |
| 110 | + "sticker_out = cv2.warpPerspective(sticker, M, (w_trg, h_trg))\n", |
| 111 | + "\n", |
| 112 | + "sticker_out_alpha = sticker_out[..., 3:] / 255\n", |
| 113 | + "sticker_alpha = sticker[..., 3:] / 255\n", |
| 114 | + "\n", |
| 115 | + "trg_img_with_sticker = sticker_out_alpha * sticker_out[..., :3] + (1 - sticker_out_alpha) * trg_img\n", |
| 116 | + "src_img_with_sticker = sticker_alpha * sticker[..., :3] + (1 - sticker_alpha) * src_img" |
| 117 | + ] |
| 118 | + }, |
| 119 | + { |
| 120 | + "cell_type": "code", |
| 121 | + "execution_count": null, |
| 122 | + "id": "88723600-c18f-4eb1-aec7-feb4112e2610", |
| 123 | + "metadata": {}, |
| 124 | + "outputs": [], |
| 125 | + "source": [ |
| 126 | + "fig, axs = plt.subplots(2, 2, figsize=(10, 10))\n", |
| 127 | + "\n", |
| 128 | + "axs[0, 0].imshow(src_img)\n", |
| 129 | + "axs[0, 0].set_title(\"Source Image\")\n", |
| 130 | + "axs[0, 0].axis('off')\n", |
| 131 | + "\n", |
| 132 | + "axs[0, 1].imshow(src_img_with_sticker.astype(np.uint8))\n", |
| 133 | + "axs[0, 1].set_title(\"Source Image with Edits\")\n", |
| 134 | + "axs[0, 1].axis('off')\n", |
| 135 | + "\n", |
| 136 | + "axs[1, 0].imshow(trg_img)\n", |
| 137 | + "axs[1, 0].set_title(\"Target Image\")\n", |
| 138 | + "axs[1, 0].axis('off')\n", |
| 139 | + "\n", |
| 140 | + "axs[1, 1].imshow(trg_img_with_sticker.astype(np.uint8))\n", |
| 141 | + "axs[1, 1].set_title(\"Target Image with Propagated Edits\")\n", |
| 142 | + "axs[1, 1].axis('off')\n", |
| 143 | + "\n", |
| 144 | + "plt.tight_layout()\n", |
| 145 | + "plt.show()" |
| 146 | + ] |
| 147 | + } |
| 148 | + ], |
| 149 | + "metadata": { |
| 150 | + "kernelspec": { |
| 151 | + "display_name": "Python 3 (ipykernel)", |
| 152 | + "language": "python", |
| 153 | + "name": "python3" |
| 154 | + }, |
| 155 | + "language_info": { |
| 156 | + "codemirror_mode": { |
| 157 | + "name": "ipython", |
| 158 | + "version": 3 |
| 159 | + }, |
| 160 | + "file_extension": ".py", |
| 161 | + "mimetype": "text/x-python", |
| 162 | + "name": "python", |
| 163 | + "nbconvert_exporter": "python", |
| 164 | + "pygments_lexer": "ipython3", |
| 165 | + "version": "3.10.9" |
| 166 | + } |
| 167 | + }, |
| 168 | + "nbformat": 4, |
| 169 | + "nbformat_minor": 5 |
| 170 | +} |
0 commit comments