{ "cells": [ { "cell_type": "code", "execution_count": 2, "id": "71c25a25", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "cuda\n" ] }, { "ename": "NameError", "evalue": "name 'exit' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[2], line 55\u001b[0m\n\u001b[1;32m 53\u001b[0m torch\u001b[38;5;241m.\u001b[39mcuda\u001b[38;5;241m.\u001b[39mmanual_seed(SEED)\n\u001b[1;32m 54\u001b[0m torch\u001b[38;5;241m.\u001b[39mbackends\u001b[38;5;241m.\u001b[39mcudnn\u001b[38;5;241m.\u001b[39mbenchmark \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mTrue\u001b[39;00m\n\u001b[0;32m---> 55\u001b[0m model, aug \u001b[38;5;241m=\u001b[39m \u001b[43mload_model\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdiffusion_ver\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mVER\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mimage_size\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mSIZE\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mnum_timesteps\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mTIMESTEP\u001b[49m\u001b[43m,\u001b[49m\u001b[43mdecoder_only\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43;01mFalse\u001b[39;49;00m\u001b[43m)\u001b[49m\n", "File \u001b[0;32m~/code/DeCLIP/extractor_sd.py:186\u001b[0m, in \u001b[0;36mload_model\u001b[0;34m(config_path, seed, diffusion_ver, image_size, num_timesteps, block_indices, decoder_only, encoder_only, resblock_only)\u001b[0m\n\u001b[1;32m 184\u001b[0m dataset_cfg \u001b[38;5;241m=\u001b[39m cfg\u001b[38;5;241m.\u001b[39mdataloader\u001b[38;5;241m.\u001b[39mtest\n\u001b[1;32m 185\u001b[0m \u001b[38;5;28mprint\u001b[39m(cfg\u001b[38;5;241m.\u001b[39mtrain\u001b[38;5;241m.\u001b[39mdevice)\n\u001b[0;32m--> 186\u001b[0m \u001b[43mexit\u001b[49m()\n\u001b[1;32m 187\u001b[0m aug \u001b[38;5;241m=\u001b[39m instantiate(dataset_cfg\u001b[38;5;241m.\u001b[39mmapper)\u001b[38;5;241m.\u001b[39maugmentations\n\u001b[1;32m 188\u001b[0m model \u001b[38;5;241m=\u001b[39m instantiate_odise(cfg\u001b[38;5;241m.\u001b[39mmodel)\n", "\u001b[0;31mNameError\u001b[0m: name 'exit' is not defined" ] } ], "source": [ "import os\n", "from training.utils import build_vfm\n", "os.environ['CUDA_VISIBLE_DEVICES'] = '3'\n", "import torch\n", "import os\n", "import pandas as pd\n", "import numpy as np\n", "from PIL import Image\n", "from tqdm import tqdm\n", "import torch.nn.functional as F\n", "from extractor_sd import load_model, process_features_and_mask, get_mask\n", "from third_party.utils.utils_correspondence import co_pca, resize, find_nearest_patchs, find_nearest_patchs_replace\n", "import matplotlib.pyplot as plt\n", "import sys\n", "from extractor_dino import ViTExtractor\n", "from sklearn.decomposition import PCA as sklearnPCA\n", "import math\n", "from sklearn.cluster import KMeans\n", "from scipy.optimize import linear_sum_assignment\n", "from torchvision import transforms\n", "\n", "def preprocess_pil(pil_image):\n", " prep = transforms.Compose([\n", " transforms.ToTensor(),\n", " transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))\n", " ])\n", " prep_img = prep(pil_image)[None, ...]\n", " return prep_img\n", "\n", "MASK = True\n", "VER = \"v1-5\"\n", "PCA = False\n", "CO_PCA = True\n", "PCA_DIMS = [256, 256, 256]\n", "SIZE =960\n", "EDGE_PAD = False\n", "\n", "FUSE_DINO = 1\n", "ONLY_DINO = 0\n", "MODEL_SIZE = 'base'\n", "DRAW_DENSE = 1\n", "DRAW_SWAP = 1\n", "TEXT_INPUT = False\n", "SEED = 42\n", "TIMESTEP = 100\n", "\n", "DIST = 'l2' if FUSE_DINO and not ONLY_DINO else 'cos'\n", "if ONLY_DINO:\n", " FUSE_DINO = True\n", "\n", "np.random.seed(SEED)\n", "torch.manual_seed(SEED)\n", "torch.cuda.manual_seed(SEED)\n", "torch.backends.cudnn.benchmark = True\n", "model, aug = load_model(diffusion_ver=VER, image_size=SIZE, num_timesteps=TIMESTEP,decoder_only=False)\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "75082563", "metadata": {}, "outputs": [], "source": [ "def compute_pair_feature(model, aug, save_path, files, category, mask=False, dist='cos', real_size=960):\n", " img_size = 840\n", " stride = 14 \n", " device = 'cuda' if torch.cuda.is_available() else 'cpu'\n", " extractor=build_vfm(\"dinov2-B\").to(device).eval().to(torch.float32)\n", " patch_size = 14\n", " num_patches = int(patch_size / stride * (img_size // patch_size - 1) + 1)\n", " input_text = None\n", "\n", " # Load image 1\n", " img1 = Image.open(files[0]).convert('RGB')\n", " img1_input = resize(img1, real_size, resize=True, to_pil=True, edge=EDGE_PAD)\n", " img1 = resize(img1, img_size, resize=True, to_pil=True, edge=EDGE_PAD)\n", "\n", " # Load image 2\n", " img2 = Image.open(files[1]).convert('RGB')\n", " img2_input = resize(img2, real_size, resize=True, to_pil=True, edge=EDGE_PAD)\n", " img2 = resize(img2, img_size, resize=True, to_pil=True, edge=EDGE_PAD)\n", "\n", " with torch.no_grad():\n", " features1 = process_features_and_mask(model, aug, img1_input, input_text=input_text, mask=False, raw=True)\n", " features2 = process_features_and_mask(model, aug, img2_input, input_text=input_text, mask=False, raw=True)\n", " processed_features1, processed_features2 = co_pca(features1, features2, PCA_DIMS)\n", " img1_desc = processed_features1.reshape(1, 1, -1, num_patches**2).permute(0,1,3,2)\n", " img2_desc = processed_features2.reshape(1, 1, -1, num_patches**2).permute(0,1,3,2)\n", " img1_batch = preprocess_pil(img1).to(device)\n", " img1_desc_dino = extractor.get_intermediate_layers(img1_batch)[0].unsqueeze(1)\n", " img2_batch = preprocess_pil(img2).to(device)\n", " img2_desc_dino = extractor.get_intermediate_layers(img2_batch)[0].unsqueeze(1)\n", " img1_desc = img1_desc / img1_desc.norm(dim=-1, keepdim=True)\n", " img2_desc = img2_desc / img2_desc.norm(dim=-1, keepdim=True)\n", " img1_desc_dino = img1_desc_dino / img1_desc_dino.norm(dim=-1, keepdim=True)\n", " img2_desc_dino = img2_desc_dino / img2_desc_dino.norm(dim=-1, keepdim=True)\n", " img1_desc = torch.cat((img1_desc, img1_desc_dino), dim=-1)\n", " img2_desc = torch.cat((img2_desc, img2_desc_dino), dim=-1)\n", " if DRAW_DENSE:\n", " mask1 = get_mask(model, aug, img1, category[0])\n", " mask2 = get_mask(model, aug, img2, category[-1])\n", " img1_desc_reshaped = img1_desc.permute(0,1,3,2).reshape(-1, img1_desc.shape[-1], num_patches, num_patches)\n", " img2_desc_reshaped = img2_desc.permute(0,1,3,2).reshape(-1, img2_desc.shape[-1], num_patches, num_patches)\n", " trg_dense_output, src_color_map = find_nearest_patchs(mask2, mask1, img2, img1, img2_desc_reshaped, img1_desc_reshaped, mask=mask)\n", "\n", " if not os.path.exists(f'{save_path}/{category[0]}'):\n", " os.makedirs(f'{save_path}/{category[0]}')\n", " fig_colormap, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 8))\n", " ax1.axis('off')\n", " ax2.axis('off')\n", " ax1.imshow(src_color_map)\n", " ax2.imshow(trg_dense_output)\n", " fig_colormap.savefig(f'{save_path}/{category[0]}_colormap.png')\n", " plt.close(fig_colormap)\n", " \n", " if DRAW_SWAP:\n", " if not DRAW_DENSE:\n", " mask1 = get_mask(model, aug, img1, category[0])\n", " mask2 = get_mask(model, aug, img2, category[-1])\n", "\n", " if (ONLY_DINO or not FUSE_DINO) and not DRAW_DENSE:\n", " img1_desc = img1_desc / img1_desc.norm(dim=-1, keepdim=True)\n", " img2_desc = img2_desc / img2_desc.norm(dim=-1, keepdim=True)\n", " \n", " img1_desc_reshaped = img1_desc.permute(0,1,3,2).reshape(-1, img1_desc.shape[-1], num_patches, num_patches)\n", " img2_desc_reshaped = img2_desc.permute(0,1,3,2).reshape(-1, img2_desc.shape[-1], num_patches, num_patches)\n", " trg_dense_output, src_color_map = find_nearest_patchs_replace(mask2, mask1, img2, img1, img2_desc_reshaped, img1_desc_reshaped, mask=mask, resolution=156)\n", " if not os.path.exists(f'{save_path}/{category[0]}'):\n", " os.makedirs(f'{save_path}/{category[0]}')\n", " fig_colormap, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 8))\n", " ax1.axis('off')\n", " ax2.axis('off')\n", " ax1.imshow(src_color_map)\n", " ax2.imshow(trg_dense_output)\n", " fig_colormap.savefig(f'{save_path}/{category[0]}/swap.png')\n", " plt.close(fig_colormap)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "e4d1bdc6", "metadata": {}, "outputs": [], "source": [ "def process_images(src_img_path,trg_img_path):\n", "\n", " categories = [['dog'], ['dog']]\n", " files = [src_img_path, trg_img_path]\n", " save_path = './my_results_vis' + f'/{trg_img_path.split(\"/\")[-1].split(\".\")[0]}_{src_img_path.split(\"/\")[-1].split(\".\")[0]}'\n", " result = compute_pair_feature(model, aug, save_path, files, mask=MASK, category=categories, dist=DIST)\n", " return result\n", "\n", "src_img_path = \"demo_images/dog.jpg\"\n", "trg_img_path = \"demo_images/whitedog.jpg\"\n", "\n", "result = process_images(src_img_path, trg_img_path)" ] } ], "metadata": { "kernelspec": { "display_name": "declip", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.0" } }, "nbformat": 4, "nbformat_minor": 5 }