具有变换坐标的图像的 Interp2

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

y = s*R*x + t;

下面显示了结果图像。

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

具有变换坐标的图像的 Interp2

由此我们可以看出坐标变换一定是成功的,因为图像虽然不是完美对齐的(这是可以预料的,因为在计算 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,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,[])]; % X is [2xM*N] coordinate pairs
end

手动代码


function [transformed_image] = transform_image(im_r,n] = size(im_t);
[x_t,grid_yt] = get_grid(im_t);
y = s*R*x_t + t;
ymat =  reshape(y',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_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 时做错了什么?我觉得我什么都试过了

jacod2980 回答:具有变换坐标的图像的 Interp2

结果我的插值全错了。

在我的问题中,我计算了 im2 中 im1 的坐标。 然而,插值的工作方式是我需要计算 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
本文链接:https://www.f2er.com/4464.html

大家都在问