具有变换坐标的图像的 Interp2

Interp2 of image with transformed coordinates

我有 2 张灰度图像,我正尝试使用标量缩放 1、旋转矩阵 [2,2] 和平移向量 [2,1] 对齐它们。我可以将 image1 的变换坐标计算为

y = s*R*x + t;

下面显示了生成的图像。

  1. 第一张图片是改造前的image1,
  2. 第二张图片是 image1(红色),尝试在 image2(绿色)上方显示使用 interp2 的插值
  3. 第三张图片是我使用转换后的坐标手动将 image1 中的像素值插入到一个空数组(与 image2 具有相同大小)时。

从这里我们可以看出坐标变换一定是成功的,因为图像对齐虽然不是很完美(这是意料之中的,因为在计算 s、R 和 t 时只使用了 2 个坐标)。

为什么 interp2 没有产生与我手动插入像素值时更相似的结果? 下面包含执行此操作的代码:

插值码

function [transformed_image] = interpolate_image(im_r,im_t,s,R,t)

[m,n] = size(im_t);

 % doesn't help if i use get_grid that the other function is using here
[~, grid_xr, grid_yr] = get_ipgrid(im_r);
[x_t, grid_xt, grid_yt] = get_ipgrid(im_t); 

y = s*R*x_t + t;
yx = reshape(y(1,:), m,n);
yy = reshape(y(2,:), m,n);

transformed_image = interp2(grid_xr, grid_yr, im_r, yx, yy, 'nearest');
end

function [x, grid_x, grid_y] = get_ipgrid(image)

[m,n] = size(image);
[grid_x,grid_y] = meshgrid(1:n,1:m);
x = [reshape(grid_x, 1, []); reshape(grid_y, 1, [])]; % X is [2xM*N] coordinate pairs
end

手动码


function [transformed_image] = transform_image(im_r,im_t,s,R,t)

[m,n] = size(im_t);
[x_t, grid_xt, grid_yt] = get_grid(im_t);
y = s*R*x_t + t;
ymat =  reshape(y',m,n,2);
yx = ymat(:,:,1);
yy = ymat(:,:,2);

transformed_image = zeros(m,n);


for i = 1:m
    for j = 1:n
        % make sure coordinates are inside
        if (yx(i,j) < m & yy(i,j) < n & yx(i,j) > 0.5 & yy(i,j) > 0.5)
            transformed_image(round(yx(i,j)),round(yy(i,j))) = im_r(i,j);
        end
    end
end
end

function [x, grid_x, grid_y] = get_grid(image)

[m,n] = size(image);
[grid_y,grid_x] = meshgrid(1:n,1:m);
x = [grid_x(:) grid_y(:)]'; % X is [2xM*N] coordinate pairs
end

谁能看出我对 interp2 做错了什么?我觉得我什么都试过了

原来我的插值全错了。

在我的问题中,我计算了 im1 在 im2 中的坐标。 然而,插值的工作方式是我需要计算 im1 中 im2 的坐标,以便我可以如下图所示映射图像。 这意味着我还计算了错误的 s、R 和 t,因为它们用于转换 im1 -> im2,而我需要 im2 -> im1。 (这也称为逆变换)。下面是手动代码,与最近邻插值的interp2基本相同

function [transformed_image] = transform_image(im_r,im_t,s,R,t)
[m,n] = size(im_t);
[x_t, grid_xt, grid_yt] = get_grid(im_t);
y = s*R*x_t + t;
ymat =  reshape(y',m,n,2);
yx = ymat(:,:,1);
yy = ymat(:,:,2);

transformed_image = zeros(m,n);
for i = 1:m
    for j = 1:n
        % make sure coordinates are inside
        if (yx(i,j) < m & yy(i,j) < n & yx(i,j) > 0.5 & yy(i,j) > 0.5)
            transformed_image(i,j) = im_r(round(yx(i,j)),round(yy(i,j)));
        end
    end
end
end