function outputIm = backward_geometry(inputIm, A, type)
% inputIm = 輸入的圖像
% A = 仿射變換的系數(shù)挺尾,一個2x3的矩陣
% 獲取輸入圖像的大小
inputSize = size(inputIm);
if(size(inputIm, 3) == 1)
inputSize(3) = 1;
end
h=inputSize(1);
w=inputSize(2);
% 計算輸出圖像的畫布大小
[outputSize, deltaShift] = calcOutputSize(inputSize, A, type);
outputIm=zeros(outputSize(2),outputSize(1));
% expand the previous image
inputImEx=zeros(h+2,w+2,1);
inputImEx(2:h+1,2:w+1,1)=inputIm(:,:,1);
inputImEx(1,2:w+1,1)=inputIm(1,:,1);
inputImEx(2:h+1,1,1)=inputIm(:,1,1);
inputImEx(h+2,2:w+1,1)=inputIm(h,:,1);
inputImEx(2:h+1,w+2,1)=inputIm(:,w,1);
inputImEx(1,1,1)=inputIm(1,1,1);
inputImEx(1,w+2,1)=inputIm(1,w,1);
inputImEx(h+2,1,1)=inputIm(h,1,1);
inputImEx(h+2,w+2,1)=inputIm(h,w,1);
% 根據(jù)確定的輸出畫布大小來進(jìn)行遍歷
for i = 1 : outputSize(1)
for j = 1 : outputSize(2)
y = j;
x = i;
% 進(jìn)行逆向變換咧虎,計算當(dāng)前點(x,y)在輸入圖像中的坐標(biāo)
A(3,:)=[0,0,1];
vec=[x-deltaShift(1);y-deltaShift(2);1];
vec0 = A\vec;
x0=vec0(1); y0=vec0(2);
% 進(jìn)行雙線性插值獲取像素點的值
if x0>0 && x0<=w && y0>0 && y0<=h
xf=floor(x0)+1; xc=xf+1;
yf=floor(y0)+1; yc=yf+1;
u=x0+1-xf; v=y0+1-yf;
res=u*v*inputImEx(yc,xc)+u*(1-v)*inputImEx(yf,xc)+...
(1-u)*v*inputImEx(yc,xf)+(1-u)*(1-v)*inputImEx(yf,xf);
outputIm(y,x,1)=round(res);
end
end
end
outputIm=uint8(outputIm);
end
function [outputSize, deltaShift] = calcOutputSize(inputSize, A, type)
% type 有兩種牲距,一種是 loose, 一種是crop菱皆,參考imrotate命令的幫助文件
% 需要實現(xiàn)這兩種
% 'crop'
% Make output image B the same size as the input image A, cropping the rotated image to fit
% {'loose'}
% Make output image B large enough to contain the entire rotated image. B is larger than A
% 獲取圖像的行和列的總數(shù)恤浪,其中行方向?qū)?yīng)著y方向,列方向?qū)?yīng)著x方向
ny = inputSize(1);
nx = inputSize(2);
% 計算四個頂點的齊次坐標(biāo)
inputBoundingBox = [ 1 1 1;...
nx 1 1;...
nx ny 1;...
1 ny 1];
inputBoundingBox = inputBoundingBox';
% 獲取輸入圖像經(jīng)過仿射變換后在輸出圖像中的框
outputBoundingBox = A * inputBoundingBox;
% 找到輸出圖像的緊致的框
xlo = floor(min(outputBoundingBox(1,:)));
xhi = ceil(max(outputBoundingBox(1,:)));
ylo = floor(min(outputBoundingBox(2,:)));
yhi = ceil(max(outputBoundingBox(2,:)));
if strcmp(type,'loose')==1
outputSize(1) = xhi-xlo+1;
outputSize(2) = yhi-ylo+1;
deltaShift(1) = -xlo+1;
deltaShift(2) = -ylo+1;
elseif strcmp(type,'crop')==1
outputSize(1) = inputSize(2);
outputSize(2) = inputSize(1);
deltaShift(1) = -(xlo+xhi-outputSize(1)-1)/2;
deltaShift(2) = -(ylo+yhi-outputSize(2)-1)/2;
end
end
type為'crop'或者'loose'俏险,最終輸出灰度圖严拒。