如何在MATLAB中将图像变形为梯形

iar*_*edi 3 matlab image image-processing

我正在使用狒狒图像,我想要的是获得这样的图像:

在此输入图像描述

我试图用fitgeotrans,projective2daffine2d没有成功,也许我不能正确理解这些功能的行为.

谢谢您的帮助.

ray*_*ica 9

只是警告fitgeotrans是MATLAB R2013b的一部分,所以这不适用于此之下的任何版本.


将图像变形为"梯形"的过程非常简单.您需要做的是创建一个转换对象,该对象采用图像的四个角点并将它们放置到您想要的梯形的相应角落.找到此变换后,使用此变换对象扭曲图像,但请确保指定坐标系,使原点相对于原始图像的左上角.如果不这样做,那么原点就是要裁剪的新图像.一旦找到这个扭曲的图像,我们就会在相对于原始图像坐标系的图像帧上显示它.

您正在使用来自南加州大学SIPI(信号和图像处理协会)图像数据库的臭名昭着的Mandrill图像,MATLAB将其作为图像处理工具箱的一部分.首先加载数据集,因为这是带有指定颜色映射的索引图像,需要将其转换为彩色图像.ind2rgb

%// Load in the image
load mandrill;
img = ind2rgb(X,map);
Run Code Online (Sandbox Code Playgroud)

Mandrill图像存储在img,我们得到:

在此输入图像描述

现在,下一部分是创建一个变换对象,将图像的四个角点扭曲为梯形坐标. fitgeotrans做得很完美.您需要指定一组"移动点",这是您要转换的点.在这种情况下,这些是您要转换的原始图像的四个角点.将其放入4 x 2矩阵,其中第一列是列/ x坐标,第二列是行/ y坐标.我将分别指定左上角,右上角,左下角和右下角坐标.接下来,您需要指定一组"固定点",这些点是您希望移动点最终移动到的点.再次,这将是一个4 x 2矩阵,这些是梯形的坐标.我不得不愚弄坐标以使其正确,但我们非常欢迎您根据自己的喜好对其进行修改.由于梯形中经历过纯粹的经历,您还需要指定投影变换.

%// Create perspective transformation that warps the original 
%// image coordinates to the trapezoid
movingPoints = [1 1; size(img,2) 1; 1 size(img,1); size(img,2) size(img,1)];
fixedPoints = [180 100; 340 100; 50 300; 450 300];
tform = fitgeotrans(movingPoints, fixedPoints, 'Projective');
Run Code Online (Sandbox Code Playgroud)

tform存储转换对象.接下来,我们需要创建一个参考坐标系来扭曲我们的图像.我们希望对原始图像坐标系执行此操作.你可以imref2d用来做那件事.第一个输入是图像的大小,分别是向量中的行和列,然后指定x/列限制和y/行限制.我们希望这与原始图像有关.

%// Create a reference coordinate system where the extent is the size of
%// the image
RA = imref2d([size(img,1) size(img,2)], [1 size(img,2)], [1 size(img,1)]);
Run Code Online (Sandbox Code Playgroud)

RA存储此参考框架.您需要做的最后一件事是使用这个新的转换对象来扭曲图像.使用imwarp来实现这一翘曲.要使用此功能,请指定要变形的图像,变换对象,并且要确保变形是相对于原始图像框架坐标系的,因此必须将'OutputView'标记指定为上面创建的标记.

%// Warp the image
[out,r] = imwarp(img, tform, 'OutputView', RA);
Run Code Online (Sandbox Code Playgroud)

out包含扭曲图像并r包含图像相对于的坐标系. 对于这个问题的目的r应该是平等RA的.

现在,如果要查看图像,请使用imshow此新坐标系最终显示图像.执行此操作时,您将看到显示的轴,因此请将其关闭:

%// Show the image and turn off the axes
imshow(out, r);
axis off;
Run Code Online (Sandbox Code Playgroud)

....我们得到:

在此输入图像描述


为了您的复制和粘贴乐趣,这里是完整的代码:

%// Load in the image
load mandrill;
img = ind2rgb(X,map);

%// Create perspective transformation that warps the original 
%// image coordinates to the trapezoid
movingPoints = [1 1; size(img,2) 1; 1 size(img,1); size(img,2) size(img,1)];
fixedPoints = [180 100; 340 100; 50 300; 450 300];
tform = fitgeotrans(movingPoints, fixedPoints, 'Projective');

%// Create a reference coordinate system where the extent is the size of
%// the image
RA = imref2d([size(img,1) size(img,2)], [1 size(img,2)], [1 size(img,1)]);

%// Warp the image
[out,r] = imwarp(img, tform, 'OutputView', RA);

%// Show the image and turn off the axes
imshow(out, r);
axis off;
Run Code Online (Sandbox Code Playgroud)