为什么网格采样后需要归一化?

时间:2021-02-26 13:52:10

标签: python image-processing pytorch

我有一个关于网格采样过程的问题。

在尝试理解网格采样时,制作了玩具网格采样代码。

它只是读取图像并通过纯网格采样制作扭曲图像,无需任何操作(=完全相同的图像再现)

但是如果我省略归一化(x_normalized, y_normalized),那么我无法使用网格样本获得相同的图像。

此时,为什么网格样本的归一化过程必不可少?

它只是使图像的高度从 -1 ~ 1.

如何理解这种规范化?

谢谢!

import cv2


img = cv2.imread('apple.jpg')
print("input image shape : ", img.shape)
height, width, channel = img.shape
batch = 1

img = torch.FloatTensor(img).unsqueeze(0).permute(0,3,1,2)

y_grid, x_grid = torch.meshgrid([torch.arange(0, height, dtype=torch.float32),
                    torch.arange(0, width, dtype=torch.float32)])

xy = torch.stack((x_grid, y_grid),2)
xy = torch.unsqueeze(xy, 0) #[B,H,W,2]
xy = xy.permute(0,3,1,2) #[B,H,W,2]

x_normalized = xy[:, 0, :, :] / ((width - 1) / 2) - 1
y_normalized = xy[:, 1, :, :] / ((height - 1) / 2) - 1

grid = torch.stack((x_normalized, y_normalized), dim=1)  # [B, 9, H*W, 2]
grid = grid.permute(0,2,3,1)

warped_img = torch.nn.functional.grid_sample(img,grid,mode='bilinear',padding_mode='zeros').permute(0,2,3,1).squeeze(0)
print("warped_img shape : ", warped_img.shape)
cv2.imwrite('warped_apple.jpg',np.array(warped_img))

enter image description here

0 个答案:

没有答案
相关问题