| import torch |
| import torch.nn.functional as F |
| import numpy as np |
| from PIL import Image |
| import matplotlib.pyplot as plt |
| from matplotlib.colors import ListedColormap |
| from typing import List, Tuple |
| import faiss |
| import cv2 |
| import os |
| from matplotlib.patches import ConnectionPatch |
|
|
| def resize(img, target_res, resize=True, to_pil=True, edge=False): |
| original_width, original_height = img.size |
| original_channels = len(img.getbands()) |
| if not edge: |
| canvas = np.zeros([target_res, target_res, 3], dtype=np.uint8) |
| if original_channels == 1: |
| canvas = np.zeros([target_res, target_res], dtype=np.uint8) |
| if original_height <= original_width: |
| if resize: |
| img = img.resize((target_res, int(np.around(target_res * original_height / original_width))), Image.LANCZOS) |
| width, height = img.size |
| img = np.asarray(img) |
| canvas[(width - height) // 2: (width + height) // 2] = img |
| else: |
| if resize: |
| img = img.resize((int(np.around(target_res * original_width / original_height)), target_res), Image.LANCZOS) |
| width, height = img.size |
| img = np.asarray(img) |
| canvas[:, (height - width) // 2: (height + width) // 2] = img |
| else: |
| if original_height <= original_width: |
| if resize: |
| img = img.resize((target_res, int(np.around(target_res * original_height / original_width))), Image.LANCZOS) |
| width, height = img.size |
| img = np.asarray(img) |
| top_pad = (target_res - height) // 2 |
| bottom_pad = target_res - height - top_pad |
| img = np.pad(img, pad_width=[(top_pad, bottom_pad), (0, 0), (0, 0)], mode='edge') |
| else: |
| if resize: |
| img = img.resize((int(np.around(target_res * original_width / original_height)), target_res), Image.LANCZOS) |
| width, height = img.size |
| img = np.asarray(img) |
| left_pad = (target_res - width) // 2 |
| right_pad = target_res - width - left_pad |
| img = np.pad(img, pad_width=[(0, 0), (left_pad, right_pad), (0, 0)], mode='edge') |
| canvas = img |
| if to_pil: |
| canvas = Image.fromarray(canvas) |
| return canvas |
|
|
|
|
| def find_nearest_patchs(mask1, mask2, image1, image2, features1, features2, mask=False, resolution=None, edit_image=None): |
| def polar_color_map(image_shape): |
| h, w = image_shape[:2] |
| x = np.linspace(-1, 1, w) |
| y = np.linspace(-1, 1, h) |
| xx, yy = np.meshgrid(x, y) |
|
|
| |
| mask=mask2.cpu() |
| mask_center = np.array(np.where(mask > 0)) |
| mask_center = np.round(np.mean(mask_center, axis=1)).astype(int) |
| mask_center_y, mask_center_x = mask_center |
|
|
| |
| xx_shifted, yy_shifted = xx - x[mask_center_x], yy - y[mask_center_y] |
| max_radius = np.sqrt(h**2 + w**2) / 2 |
| radius = np.sqrt(xx_shifted**2 + yy_shifted**2) * max_radius |
| angle = np.arctan2(yy_shifted, xx_shifted) / (2 * np.pi) + 0.5 |
|
|
| angle = 0.2 + angle * 0.6 |
| radius = np.where(radius <= max_radius, radius, max_radius) |
| radius = 0.2 + radius * 0.6 / max_radius |
|
|
| return angle, radius |
| |
| if resolution is not None: |
| features1 = F.interpolate(features1, size=resolution, mode='bilinear') |
| features2 = F.interpolate(features2, size=resolution, mode='bilinear') |
| |
| |
| resized_image1 = resize(image1, features1.shape[2], resize=True, to_pil=False) |
| resized_image2 = resize(image2, features2.shape[2], resize=True, to_pil=False) |
|
|
| if mask: |
| resized_mask1 = F.interpolate(mask1.cuda().unsqueeze(0).unsqueeze(0).float(), size=features1.shape[2:], mode='nearest') |
| resized_mask2 = F.interpolate(mask2.cuda().unsqueeze(0).unsqueeze(0).float(), size=features2.shape[2:], mode='nearest') |
| features1 = features1 * resized_mask1.repeat(1, features1.shape[1], 1, 1) |
| features2 = features2 * resized_mask2.repeat(1, features2.shape[1], 1, 1) |
| |
| features1[(features1.sum(1)==0).repeat(1, features1.shape[1], 1, 1)] = 100000 |
| features2[(features2.sum(1)==0).repeat(1, features2.shape[1], 1, 1)] = 100000 |
|
|
| features1_2d = features1.reshape(features1.shape[1], -1).permute(1, 0).cpu().detach().numpy() |
| features2_2d = features2.reshape(features2.shape[1], -1).permute(1, 0).cpu().detach().numpy() |
|
|
| features1_2d = torch.tensor(features1_2d).to("cuda") |
| features2_2d = torch.tensor(features2_2d).to("cuda") |
| resized_image1 = torch.tensor(resized_image1).to("cuda").float() |
| resized_image2 = torch.tensor(resized_image2).to("cuda").float() |
|
|
| mask1 = F.interpolate(mask1.cuda().unsqueeze(0).unsqueeze(0).float(), size=resized_image1.shape[:2], mode='nearest').squeeze(0).squeeze(0) |
| mask2 = F.interpolate(mask2.cuda().unsqueeze(0).unsqueeze(0).float(), size=resized_image2.shape[:2], mode='nearest').squeeze(0).squeeze(0) |
|
|
| |
| resized_image1 = resized_image1 * mask1.unsqueeze(-1).repeat(1, 1, 3) |
| resized_image2 = resized_image2 * mask2.unsqueeze(-1).repeat(1, 1, 3) |
| |
| resized_image1 = (resized_image1 - resized_image1.min()) / (resized_image1.max() - resized_image1.min()) |
| resized_image2 = (resized_image2 - resized_image2.min()) / (resized_image2.max() - resized_image2.min()) |
|
|
| angle, radius = polar_color_map(resized_image2.shape) |
|
|
| angle_mask = angle * mask2.cpu().numpy() |
| radius_mask = radius * mask2.cpu().numpy() |
|
|
| hsv_mask = np.zeros(resized_image2.shape, dtype=np.float32) |
| hsv_mask[:, :, 0] = angle_mask |
| hsv_mask[:, :, 1] = radius_mask |
| hsv_mask[:, :, 2] = 1 |
|
|
| rainbow_mask2 = cv2.cvtColor((hsv_mask * 255).astype(np.uint8), cv2.COLOR_HSV2BGR) / 255 |
|
|
| if edit_image is not None: |
| rainbow_mask2 = cv2.imread(edit_image, cv2.IMREAD_COLOR) |
| rainbow_mask2 = cv2.cvtColor(rainbow_mask2, cv2.COLOR_BGR2RGB) / 255 |
| rainbow_mask2 = cv2.resize(rainbow_mask2, (resized_image2.shape[1], resized_image2.shape[0])) |
|
|
| |
| rainbow_image2 = rainbow_mask2 * mask2.cpu().numpy()[:, :, None] |
|
|
| |
| background_color = np.array([1, 1, 1], dtype=np.float32) |
| background_image = np.ones(resized_image2.shape, dtype=np.float32) * background_color |
|
|
| |
| rainbow_image2 = np.where(mask2.cpu().numpy()[:, :, None] == 1, rainbow_mask2, background_image) |
| |
| nearest_patches = [] |
|
|
| distances = torch.cdist(features1_2d, features2_2d) |
| nearest_patch_indices = torch.argmin(distances, dim=1) |
| nearest_patches = torch.index_select(torch.tensor(rainbow_mask2).cuda().reshape(-1, 3), 0, nearest_patch_indices) |
|
|
| nearest_patches_image = nearest_patches.reshape(resized_image1.shape) |
| rainbow_image2 = torch.tensor(rainbow_image2).to("cuda") |
|
|
| |
| |
| |
|
|
| nearest_patches_image = (nearest_patches_image).cpu().numpy() |
| resized_image2 = (rainbow_image2).cpu().numpy() |
|
|
| return nearest_patches_image, resized_image2 |
|
|
|
|
| def find_nearest_patchs_replace(mask1, mask2, image1, image2, features1, features2, mask=False, resolution=128, draw_gif=False, save_path=None, gif_reverse=False): |
| |
| if resolution is not None: |
| features1 = F.interpolate(features1, size=resolution, mode='bilinear') |
| features2 = F.interpolate(features2, size=resolution, mode='bilinear') |
| |
| |
| resized_image1 = resize(image1, features1.shape[2], resize=True, to_pil=False) |
| resized_image2 = resize(image2, features2.shape[2], resize=True, to_pil=False) |
|
|
| if mask: |
| resized_mask1 = F.interpolate(mask1.cuda().unsqueeze(0).unsqueeze(0).float(), size=features1.shape[2:], mode='nearest') |
| resized_mask2 = F.interpolate(mask2.cuda().unsqueeze(0).unsqueeze(0).float(), size=features2.shape[2:], mode='nearest') |
| features1 = features1 * resized_mask1.repeat(1, features1.shape[1], 1, 1) |
| features2 = features2 * resized_mask2.repeat(1, features2.shape[1], 1, 1) |
| |
| features1[(features1.sum(1)==0).repeat(1, features1.shape[1], 1, 1)] = 100000 |
| features2[(features2.sum(1)==0).repeat(1, features2.shape[1], 1, 1)] = 100000 |
| |
| features1_2d = features1.reshape(features1.shape[1], -1).permute(1, 0) |
| features2_2d = features2.reshape(features2.shape[1], -1).permute(1, 0) |
|
|
| resized_image1 = torch.tensor(resized_image1).to("cuda").float() |
| resized_image2 = torch.tensor(resized_image2).to("cuda").float() |
|
|
| mask1 = F.interpolate(mask1.cuda().unsqueeze(0).unsqueeze(0).float(), size=resized_image1.shape[:2], mode='nearest').squeeze(0).squeeze(0) |
| mask2 = F.interpolate(mask2.cuda().unsqueeze(0).unsqueeze(0).float(), size=resized_image2.shape[:2], mode='nearest').squeeze(0).squeeze(0) |
|
|
| |
| resized_image1 = resized_image1 * mask1.unsqueeze(-1).repeat(1, 1, 3) |
| resized_image2 = resized_image2 * mask2.unsqueeze(-1).repeat(1, 1, 3) |
| |
| resized_image1 = (resized_image1 - resized_image1.min()) / (resized_image1.max() - resized_image1.min()) |
| resized_image2 = (resized_image2 - resized_image2.min()) / (resized_image2.max() - resized_image2.min()) |
|
|
| distances = torch.cdist(features1_2d, features2_2d) |
| nearest_patch_indices = torch.argmin(distances, dim=1) |
| nearest_patches = torch.index_select(resized_image2.cuda().clone().detach().reshape(-1, 3), 0, nearest_patch_indices) |
|
|
| nearest_patches_image = nearest_patches.reshape(resized_image1.shape) |
|
|
| if draw_gif: |
| assert save_path is not None, "save_path must be provided when draw_gif is True" |
| img_1 = resize(image1, features1.shape[2], resize=True, to_pil=True) |
| img_2 = resize(image2, features2.shape[2], resize=True, to_pil=True) |
| mapping = torch.zeros((img_1.size[1], img_1.size[0], 2)) |
| for i in range(len(nearest_patch_indices)): |
| mapping[i // img_1.size[0], i % img_1.size[0]] = torch.tensor([nearest_patch_indices[i] // img_2.size[0], nearest_patch_indices[i] % img_2.size[0]]) |
| animate_image_transfer(img_1, img_2, mapping, save_path) if gif_reverse else animate_image_transfer_reverse(img_1, img_2, mapping, save_path) |
|
|
| |
| |
| |
|
|
| nearest_patches_image = (nearest_patches_image).cpu().numpy() |
| resized_image2 = (resized_image2).cpu().numpy() |
|
|
| return nearest_patches_image, resized_image2 |
|
|
| def chunk_cosine_sim(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: |
| """ Computes cosine similarity between all possible pairs in two sets of vectors. |
| Operates on chunks so no large amount of GPU RAM is required. |
| :param x: an tensor of descriptors of shape Bx1x(t_x)xd' where d' is the dimensionality of the descriptors and t_x |
| is the number of tokens in x. |
| :param y: a tensor of descriptors of shape Bx1x(t_y)xd' where d' is the dimensionality of the descriptors and t_y |
| is the number of tokens in y. |
| :return: cosine similarity between all descriptors in x and all descriptors in y. Has shape of Bx1x(t_x)x(t_y) """ |
| result_list = [] |
| num_token_x = x.shape[2] |
| for token_idx in range(num_token_x): |
| token = x[:, :, token_idx, :].unsqueeze(dim=2) |
| result_list.append(torch.nn.CosineSimilarity(dim=3)(token, y)) |
| return torch.stack(result_list, dim=2) |
|
|
| def pairwise_sim(x: torch.Tensor, y: torch.Tensor, p=2, normalize=False) -> torch.Tensor: |
| |
| if normalize: |
| x = torch.nn.functional.normalize(x, dim=-1) |
| y = torch.nn.functional.normalize(y, dim=-1) |
| result_list=[] |
| num_token_x = x.shape[2] |
| for token_idx in range(num_token_x): |
| token = x[:, :, token_idx, :].unsqueeze(dim=2) |
| result_list.append(torch.nn.PairwiseDistance(p=p)(token, y)*(-1)) |
| return torch.stack(result_list, dim=2) |
|
|
| def draw_correspondences_gathered(points1: List[Tuple[float, float]], points2: List[Tuple[float, float]], |
| image1: Image.Image, image2: Image.Image) -> plt.Figure: |
| """ |
| draw point correspondences on images. |
| :param points1: a list of (y, x) coordinates of image1, corresponding to points2. |
| :param points2: a list of (y, x) coordinates of image2, corresponding to points1. |
| :param image1: a PIL image. |
| :param image2: a PIL image. |
| :return: a figure of images with marked points. |
| """ |
| assert len(points1) == len(points2), f"points lengths are incompatible: {len(points1)} != {len(points2)}." |
| num_points = len(points1) |
|
|
| if num_points > 15: |
| cmap = plt.get_cmap('tab10') |
| else: |
| cmap = ListedColormap(["red", "yellow", "blue", "lime", "magenta", "indigo", "orange", "cyan", "darkgreen", |
| "maroon", "black", "white", "chocolate", "gray", "blueviolet"]) |
| colors = np.array([cmap(x) for x in range(num_points)]) |
| radius1, radius2 = 0.03*max(image1.size), 0.01*max(image1.size) |
| |
| |
| fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 8)) |
| ax1.axis('off') |
| ax2.axis('off') |
| ax1.imshow(image1) |
| ax2.imshow(image2) |
|
|
| for point1, point2, color in zip(points1, points2, colors): |
| y1, x1 = point1 |
| circ1_1 = plt.Circle((x1, y1), radius1, facecolor=color, edgecolor='white', alpha=0.5) |
| circ1_2 = plt.Circle((x1, y1), radius2, facecolor=color, edgecolor='white') |
| ax1.add_patch(circ1_1) |
| ax1.add_patch(circ1_2) |
| y2, x2 = point2 |
| circ2_1 = plt.Circle((x2, y2), radius1, facecolor=color, edgecolor='white', alpha=0.5) |
| circ2_2 = plt.Circle((x2, y2), radius2, facecolor=color, edgecolor='white') |
| ax2.add_patch(circ2_1) |
| ax2.add_patch(circ2_2) |
|
|
| return fig |
|
|
| def draw_correspondences_lines(points1: List[Tuple[float, float]], points2: List[Tuple[float, float]], |
| gt_points2: List[Tuple[float, float]], image1: Image.Image, |
| image2: Image.Image, threshold=None) -> plt.Figure: |
| """ |
| draw point correspondences on images. |
| :param points1: a list of (y, x) coordinates of image1, corresponding to points2. |
| :param points2: a list of (y, x) coordinates of image2, corresponding to points1. |
| :param gt_points2: a list of ground truth (y, x) coordinates of image2. |
| :param image1: a PIL image. |
| :param image2: a PIL image. |
| :param threshold: distance threshold to determine correct matches. |
| :return: a figure of images with marked points and lines between them showing correspondence. |
| """ |
|
|
| points2=points2.cpu().numpy() |
| gt_points2=gt_points2.cpu().numpy() |
|
|
| def compute_correct(): |
| alpha = torch.tensor([0.1, 0.05, 0.01]) |
| correct = torch.zeros(len(alpha)) |
| err = (torch.tensor(points2) - torch.tensor(gt_points2)).norm(dim=-1) |
| err = err.unsqueeze(0).repeat(len(alpha), 1) |
| correct = err < threshold.unsqueeze(-1) if len(threshold.shape)==1 else err < threshold |
| return correct |
|
|
| correct = compute_correct()[0] |
| |
|
|
| assert len(points1) == len(points2), f"points lengths are incompatible: {len(points1)} != {len(points2)}." |
| num_points = len(points1) |
|
|
| if num_points > 15: |
| cmap = plt.get_cmap('tab10') |
| else: |
| cmap = ListedColormap(["red", "yellow", "blue", "lime", "magenta", "indigo", "orange", "cyan", "darkgreen", |
| "maroon", "black", "white", "chocolate", "gray", "blueviolet"]) |
| colors = np.array([cmap(x) for x in range(num_points)]) |
| radius1, radius2 = 0.03*max(image1.size), 0.01*max(image1.size) |
| |
| fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 8)) |
| ax1.axis('off') |
| ax2.axis('off') |
| ax1.imshow(image1) |
| ax2.imshow(image2) |
| ax1.set_xlim(0, image1.size[0]) |
| ax1.set_ylim(image1.size[1], 0) |
| ax2.set_xlim(0, image2.size[0]) |
| ax2.set_ylim(image2.size[1], 0) |
|
|
| for i, (point1, point2) in enumerate(zip(points1, points2)): |
| y1, x1 = point1 |
| circ1_1 = plt.Circle((x1, y1), radius1, facecolor=colors[i], edgecolor='white', alpha=0.5) |
| circ1_2 = plt.Circle((x1, y1), radius2, facecolor=colors[i], edgecolor='white') |
| ax1.add_patch(circ1_1) |
| ax1.add_patch(circ1_2) |
| y2, x2 = point2 |
| circ2_1 = plt.Circle((x2, y2), radius1, facecolor=colors[i], edgecolor='white', alpha=0.5) |
| circ2_2 = plt.Circle((x2, y2), radius2, facecolor=colors[i], edgecolor='white') |
| ax2.add_patch(circ2_1) |
| ax2.add_patch(circ2_2) |
|
|
| |
| color = 'blue' if correct[i].item() else 'red' |
| con = ConnectionPatch(xyA=(x2, y2), xyB=(x1, y1), coordsA="data", coordsB="data", |
| axesA=ax2, axesB=ax1, color=color, linewidth=1.5) |
| ax2.add_artist(con) |
|
|
| return fig |
|
|
| def co_pca(features1, features2, dim=[128,128,128]): |
| processed_features1 = {} |
| processed_features2 = {} |
| s5_size = features1['s5'].shape[-1] |
| s4_size = features1['s4'].shape[-1] |
| s3_size = features1['s3'].shape[-1] |
|
|
| |
| s5_1 = features1['s5'].reshape(features1['s5'].shape[0], features1['s5'].shape[1], -1) |
| s4_1 = features1['s4'].reshape(features1['s4'].shape[0], features1['s4'].shape[1], -1) |
| s3_1 = features1['s3'].reshape(features1['s3'].shape[0], features1['s3'].shape[1], -1) |
|
|
| s5_2 = features2['s5'].reshape(features2['s5'].shape[0], features2['s5'].shape[1], -1) |
| s4_2 = features2['s4'].reshape(features2['s4'].shape[0], features2['s4'].shape[1], -1) |
| s3_2 = features2['s3'].reshape(features2['s3'].shape[0], features2['s3'].shape[1], -1) |
| |
| target_dims = {'s5': dim[0], 's4': dim[1], 's3': dim[2]} |
| |
| |
| for name, tensors in zip(['s5', 's4', 's3'], [[s5_1, s5_2], [s4_1, s4_2], [s3_1, s3_2]]): |
| target_dim = target_dims[name] |
|
|
| |
| features = torch.cat(tensors, dim=-1) |
| features = features.permute(0, 2, 1) |
|
|
| |
| |
|
|
| |
| |
|
|
| |
| |
|
|
| |
| |
| |
|
|
| |
| mean = torch.mean(features[0], dim=0, keepdim=True) |
| centered_features = features[0] - mean |
|
|
| U, S, V = torch.pca_lowrank(centered_features, q=target_dim) |
| reduced_features = torch.matmul(centered_features, V[:, :target_dim]) |
| features = reduced_features.unsqueeze(0).permute(0, 2, 1) |
| |
| |
| processed_features1[name] = features[:, :, :features.shape[-1] // 2] |
| processed_features2[name] = features[:, :, features.shape[-1] // 2:] |
|
|
| |
| processed_features1['s5']=processed_features1['s5'].reshape(processed_features1['s5'].shape[0], -1, s5_size, s5_size) |
| processed_features1['s4']=processed_features1['s4'].reshape(processed_features1['s4'].shape[0], -1, s4_size, s4_size) |
| processed_features1['s3']=processed_features1['s3'].reshape(processed_features1['s3'].shape[0], -1, s3_size, s3_size) |
|
|
| processed_features2['s5']=processed_features2['s5'].reshape(processed_features2['s5'].shape[0], -1, s5_size, s5_size) |
| processed_features2['s4']=processed_features2['s4'].reshape(processed_features2['s4'].shape[0], -1, s4_size, s4_size) |
| processed_features2['s3']=processed_features2['s3'].reshape(processed_features2['s3'].shape[0], -1, s3_size, s3_size) |
|
|
| |
| processed_features1['s5'] = F.interpolate(processed_features1['s5'], size=(processed_features1['s4'].shape[-2:]), mode='bilinear', align_corners=False) |
| processed_features2['s5'] = F.interpolate(processed_features2['s5'], size=(processed_features2['s4'].shape[-2:]), mode='bilinear', align_corners=False) |
|
|
| |
| processed_features1['s5'] = torch.cat([processed_features1['s4'], processed_features1['s5']], dim=1) |
| processed_features2['s5'] = torch.cat([processed_features2['s4'], processed_features2['s5']], dim=1) |
|
|
| |
| processed_features1['s4'] = processed_features1['s3'] |
| processed_features2['s4'] = processed_features2['s3'] |
|
|
| |
| processed_features1.pop('s3') |
| processed_features2.pop('s3') |
|
|
| |
| features1_gether_s4_s5 = torch.cat([processed_features1['s4'], F.interpolate(processed_features1['s5'], size=(processed_features1['s4'].shape[-2:]), mode='bilinear')], dim=1) |
| features2_gether_s4_s5 = torch.cat([processed_features2['s4'], F.interpolate(processed_features2['s5'], size=(processed_features2['s4'].shape[-2:]), mode='bilinear')], dim=1) |
|
|
| return features1_gether_s4_s5, features2_gether_s4_s5 |
|
|
| def animate_image_transfer(image1, image2, mapping, output_path): |
| import numpy as np |
| from PIL import Image |
| import matplotlib.pyplot as plt |
| import matplotlib.animation as animation |
|
|
| |
| |
| |
|
|
| |
| assert image1.size == image2.size, "Images must be the same size." |
| rec_size = 2 |
| |
| image1_array = np.array(image1) |
| image2_array = np.array(image2) |
|
|
| |
| height, width, _ = image1_array.shape |
|
|
| |
| mapping = mapping.cpu().numpy() |
|
|
| |
| gap = width // 10 |
|
|
| |
| |
| fig, ax = plt.subplots(figsize=((2 * width + gap) / 200, height / 200), dpi=300) |
|
|
| |
| ax.axis('off') |
|
|
| |
| combined_image = np.ones((height, 2 * width + gap, 3), dtype=np.uint8) * 255 |
|
|
| |
| combined_image[:, :width] = image1_array |
| combined_image[:, width + gap:] = image2_array |
|
|
| img_obj = ax.imshow(combined_image) |
|
|
| |
| starts = np.mgrid[:height, :width].reshape(2, -1).T |
| targets = np.array([mapping[i, j] for i in range(height) for j in range(width)]) + [0, width + gap] |
|
|
| |
| num_frames = 30 |
|
|
| def calculate_path(start, target, num_frames): |
| """Calculate the path of a pixel from start to target over num_frames.""" |
| |
| t = np.linspace(0, 1, num_frames) |
|
|
| |
| t = 1 - (1 - t) ** 2 |
|
|
| |
| path = start + t[:, np.newaxis] * (target - start) |
|
|
| return path |
|
|
| def update(frame): |
| |
| combined_image.fill(255) |
| combined_image[:, :width] = image1_array |
| combined_image[:, width + gap:] = image2_array |
| |
| |
| if frame >= num_frames - 1: |
| frame = num_frames - 1 |
| for i in range(height): |
| for j in range(width): |
| |
| start = starts[i * width + j] |
| target = targets[i * width + j] |
| |
| if target[0] > 0 and target[1] > 0: |
| position = calculate_path(start, target, num_frames)[frame] |
| |
| combined_image[int(position[0])-rec_size//2:int(position[0])-rec_size//2+rec_size, int(position[1])-rec_size//2:int(position[1])-rec_size//2+rec_size] = image1_array[i, j] |
| img_obj.set_array(combined_image) |
| return img_obj, |
|
|
| |
| ani = animation.FuncAnimation(fig, update, frames=num_frames + 30, blit=True) |
| if not os.path.exists(os.path.dirname(output_path)): |
| os.makedirs(os.path.dirname(output_path)) |
| |
| ani.save(output_path, writer='pillow', fps=30) |
| |
| np.save(output_path[:-4]+'.npy', mapping) |
|
|
|
|
| def animate_image_transfer_reverse(image1, image2, mapping, output_path): |
| import numpy as np |
| from PIL import Image |
| import matplotlib.pyplot as plt |
| import matplotlib.animation as animation |
|
|
| |
| |
| |
|
|
| |
| assert image1.size == image2.size, "Images must be the same size." |
| |
| |
| image1_array = np.array(image1) |
| image2_array = np.array(image2) |
|
|
| |
| height, width, _ = image1_array.shape |
|
|
| |
| mapping = mapping.cpu().numpy() |
|
|
| |
| gap = width // 10 |
|
|
| |
| |
| fig, ax = plt.subplots(figsize=((2 * width + gap) / 200, height / 200), dpi=300) |
|
|
| |
| ax.axis('off') |
|
|
| |
| combined_image = np.ones((height, 2 * width + gap, 3), dtype=np.uint8) * 255 |
|
|
| |
| combined_image[:, :width] = image2_array |
| combined_image[:, width + gap:] = image1_array |
|
|
| img_obj = ax.imshow(combined_image) |
|
|
| |
| starts = np.mgrid[:height, :width].reshape(2, -1).T + [0, width + gap] |
| targets = np.array([mapping[i, j] for i in range(height) for j in range(width)]) |
|
|
| |
| num_frames = 30 |
|
|
| def calculate_path(start, target, num_frames): |
| """Calculate the path of a pixel from start to target over num_frames.""" |
| |
| t = np.linspace(1, 0, num_frames) |
|
|
| |
| t = 1 - (1 - t) ** 2 |
|
|
| |
| path = start + t[:, np.newaxis] * (target - start) |
|
|
| return path |
|
|
| def update(frame): |
| |
| combined_image.fill(255) |
| combined_image[:, :width] = image2_array |
| combined_image[:, width + gap:] = image1_array |
| |
| |
| if frame >= num_frames - 1: |
| frame = num_frames - 1 |
| if frame >= num_frames // 6 * 5: |
| rec_size = 1 |
| else: |
| rec_size = 2 |
| for i in range(height): |
| for j in range(width): |
| |
| start = starts[i * width + j] |
| target = targets[i * width + j] |
| |
| if target[0] > 0 and target[1] > 0: |
| position = calculate_path(start, target, num_frames)[frame] |
| |
| combined_image[int(position[0])-rec_size//2:int(position[0])-rec_size//2+rec_size, int(position[1])-rec_size//2:int(position[1])-rec_size//2+rec_size] = image2_array[int(mapping[i, j][0]), int(mapping[i, j][1])] |
| img_obj.set_array(combined_image) |
| return img_obj, |
|
|
| |
| ani = animation.FuncAnimation(fig, update, frames=num_frames + 30, blit=True) |
| if not os.path.exists(os.path.dirname(output_path)): |
| os.makedirs(os.path.dirname(output_path)) |
| |
| ani.save(output_path, writer='pillow', fps=30) |
| |
| np.save(output_path[:-4]+'.npy', mapping) |
|
|
|
|
|
|
|
|
| def pca_reduce_features(features: torch.Tensor, target_dim: int) -> torch.Tensor: |
| """ |
| 对输入特征做mean-center和PCA降维,自动处理float16到float32兼容。 |
| |
| Args: |
| features: [bs, c, h, w] 的输入特征 |
| target_dim: 降维后的特征数 |
| |
| Returns: |
| [bs, target_dim, h, w] 的PCA降维特征 |
| """ |
| orig_dtype = features.dtype |
| if features.dtype != torch.float32: |
| features = features.float() |
|
|
| bs, c, h, w = features.shape |
| reduced_list = [] |
| for i in range(bs): |
| |
| single = features[i].reshape(c, h * w).transpose(0, 1) |
| mean = single.mean(dim=0, keepdim=True) |
| centered = single - mean |
| U, S, V = torch.pca_lowrank(centered, q=target_dim) |
| reduced = torch.matmul(centered, V[:, :target_dim]) |
| reduced = reduced.transpose(0, 1).reshape(target_dim, h, w) |
| reduced_list.append(reduced) |
| reduced_features = torch.stack(reduced_list, dim=0) |
|
|
| |
| if orig_dtype != torch.float32: |
| reduced_features = reduced_features.to(orig_dtype) |
| return reduced_features |