MATLAB:摆脱for循环

时间:2015-12-03 09:32:43

标签: matlab image-processing vectorization

我循环遍历向量并为其中的每个元素调用一个函数 我想摆脱循环,我不知道如何。 关于代码的简短说明: 我有imageAImageB,我想将ImageB映射到ImageA,其中用户在ImageA中选择4个点来定位模式的位置({ {1}})

这是具有for循环的代码的一部分

ImageB

这是功能

newIm=im1; % newIm will have the mapped image
[r,c]=size(im1); %size of imageA

[p1,p2]=meshgrid(1:c, 1:r); % using indexes matrixes 
% p1 has the X indexes 
% p2 has the Y indexes

z = ones(r,c); % a vector of ones (for mapping algorithm)

% now calculate for every point in imageA the indexes for its new value
% from imageB    ( Inverse Mapping)

% X         a b e   X'
% Y  = pinv c d f * Y'
% 1         g h 1   1

newmatrix=pinv(mat)*[p1(:) p2(:) z(:)]'; 
newX=newmatrix(1,:)./newmatrix(3,:); % devide the x with z
newY=newmatrix(2,:)./newmatrix(3,:); % devide the y with z
newX=round(newX);   
newY=round(newY);

% %% the indexes we want are the ones in the range  of ImageB 
Xindex=(newX<Br & newX>1); % this gives us a vector of zeros and ones
Yindex=(newY<Bc & newY>1); 
ourPixels=Xindex(:).*Yindex(:); % gives us a vectors that has ones
%  in the places where the Y and X are both in the range

ourIndexes=find(ourPixels==1); % a vector that holds the indexes that we want
IndexesSize=size(ourIndexes); 
XXX=newX(ourIndexes); %the indexes we want
YYY=newY(ourIndexes);

% loop the quadrilateral and "paint" it (only looping the quadrilateral
% and not the whole image)


for i=1 : IndexesSize(1)
    newIm(ourIndexes(i))=BilinearInterpolation(im2,YYY(i), XXX(i));
end

fprintf('press any key to see the result...');
pause;

imshow(newIm);
title('The new mapped Image');

我试过了:

function NewVal=BilinearInterpolation(imgB,x,y)

% inpust: ImageB- the pattern image
% x and y the coordinates that locates the inverse mapping
% returns the new color of a spicifc pixel (x',y') in imageA


% SW SE NE NW are neighboors of (x,y) which will give us the new color


SW=imgB(floor(x),floor(y)+1);
SE=imgB(floor(x)+1,floor(y)+1);
NE=imgB(floor(x)+1,floor(y));
NW=imgB(floor(x),floor(y));


% the equations are the same as in the lecture
% S = SE * delta(x) + SW*(1- delta(x))
% N = NE * delta(x) + NW*(1- delta(x))
% V = N * delta(y) + S*(1 - delta(y))

deltax=x-floor(x);
S=SE*deltax+SW*(1-deltax);
N=NE*deltax+NW*(1-deltax);

deltay=1-(y-floor(y));
NewVal=N*deltay+S*(1-deltay);
end

但当然它没有用 我尝试更改函数以使用(newIm(ourIndexes)=BilinearInterpolation(im2,YYY, XXX); ),但也有很多问题

1 个答案:

答案 0 :(得分:1)

稍加修改就可以使你的函数接受一系列的点。

首先,如评论中所述,将*更改为元素乘法.*

此外,您还需要更改访问imgB的时间,以便接受点列表。输入两个向量(即使用未改变的代码)将调用那些点的所有组合,即nxn个点。通常我会使用for循环来避免这种情况,因为我很懒,很少需要优化我的代码。

由于您特别不想使用循环,我知道这样做的最简单方法是使用sub2ind用适当的线性索引替换对下标的调用。例如,SW=imgB(sub2ind(size(imgB),floor(x),floor(y)+1));

除了检查所有向量具有相同的长维度之外,我认为它们应该但是这取决于您的输入。