投影变换-matlab代码



我不能使用从头开始构建它所需的任何工具箱函数。

% load images
img1 = readImage('roadSign.tif');
img2 = readImage('lena.tif');
% call the main function  
mapIntoImage(img1,img2)

function    [newImage] = mapIntoImage(imageA,imageB)
%  Input:      imageA, imageB - a grayscale image in the range [0..255].
% 
%  Output:    newImage – imageA into which image B has been mapped.
% 
showImage(imageA)
hold on
% Initially, the list of points is empty.
xy = [];
% Loop, picking up the points.
disp('Please enter corners of place to insert image in clockwise order.')
for j = 1:4
[xi,yi] = ginput(1);
%draw a yellow dot
plot(xi,yi,'yo')
xy(:,j) = [xi;yi];
end
% get x1 y1 cordinates  - xy(:, 1)
imgRow = size(imageB,1);
imgCol = size(imageB,2);
[X,Y] = meshgrid(1:imgCol,1:imgRow);
imgBcords = [0 size(imageB, 1) size(imageB,1) 0 ;
0 0 size(imageB,2) size(imageB,2)];
coefs = findCoefficients(xy, imgBcords);
A = [coefs(1) coefs(2) coefs(5);coefs(3) coefs(4) coefs(6); coefs(7) coefs(8) 1];
temp = zeros(size(X,1), size(X,2), 3);
new = ones(256);
for i = 1:size(X,1)
for j = 1:size(X,2)
temp(i,j,:) =A*[X(i,j); Y(i,j); new(i,j)];
end
end
end 
function [ result ] = findCoefficients( imageA, imageB )
% finds coefficients for inverse mapping algorithem 
%   takes 2 X 2d vectors each consists of 4 points x,y
%   and returns the coef accroding to reverse mapping function
%
% x y 0 0 1 0 -xx' -yx'
% 0 0 x y 0 1 -xy' -yy'  
%                       y' and x' are in the destenation picture;

A = [imageB(1,1) imageB(2,1) 0 0 1 0 -imageB(1,1)*imageA(1,1) -imageB(2,1)*imageA(1,1); 
0 0 imageB(1,1) imageB(2,1) 0 1 -imageB(1,1)*imageA(2,1) -imageB(2,1)*imageA(2,1);
imageB(1,2) imageB(2,2) 0 0 1 0 -imageB(1,2)*imageA(1,2) -imageB(2,2)*imageA(1,2);
0 0 imageB(1,2) imageB(2,2) 0 1 -imageB(1,2)*imageA(2,2) -imageB(2,2)*imageA(2,2);
imageB(1,3) imageB(2,3) 0 0 1 0 -imageB(1,3)*imageA(1,3) -imageB(2,3)*imageA(1,3);
0 0 imageB(1,3) imageB(2,3) 0 1 -imageB(1,3)*imageA(2,3) -imageB(2,3)*imageA(2,3);
imageB(1,4) imageB(2,4) 0 0 1 0 -imageB(1,4)*imageA(1,4) -imageB(2,4)*imageA(1,4);
0 0 imageB(1,4) imageB(2,4) 0 1 -imageB(1,4)*imageA(2,4) -imageB(2,4)*imageA(2,4)];
B = [imageB(1,1); imageB(2,1); imageB(1,2); imageB(2,2); imageB(1,3); imageB(2,3); imageB(1,4); imageB(2,4)];
result = pinv(A)*B;
end

我想现在构建转换[x'y'1]=A*[x Y1];我已经知道我需要使用repmat,但如果没有循环,我似乎无法获得真正的语法。最有效的方法是什么?

投影变换具有的形式

$x'=\frac{a_{11}x+a_{12}y+a_{13}}{a_{13}x+a_{23}y+a_{33}}\\y'=\frac{a_{21}x+a_{22}y+a_{23}}{a_{13}x+a_{23}y+a_{33}$

其中系数定义为某个比例因子。确保恒定比例因子的方法之一是设置$a_{33}=1$。一个简单的方法是使用齐次坐标:

$\left(\begin{array}{ccc}x'\\y'\\S\end{array}\right)=\左\left(\begin{array}{ccc}x\\y\\1\end{array}\right)$

这些坐标是按比例定义的。也就是说,

$\left(\begin{array}{ccc}x'/S\\y'/S\\1\end{array}\right)\equiv\left(\begin{array}{ccc}x'\\y'\\S\end{array}\right)$

因此,在您的情况下,您应该这样做:(假设xy是列向量,A是我上面描述的矩阵的转置:

XY = A * [x y ones(size(x))];
XY(:,1) = XY(:,1)./XY(:,3);
XY(:,2) = XY(:,2)./XY(:,3);

最新更新