0

我正在 Matlab 中手动旋转图像。每次我用不同的图像运行我的代码时,之前旋转的图像都会显示在图中。我想不通。任何帮助都是不言而喻的。代码在这里:

在此处输入图像描述[截屏]

im1 = imread('gradient.jpg');

[h, w, p] = size(im1);
theta = pi/12;
hh = round( h*cos(theta) + w*abs(sin(theta)));      %Round to nearest integer
ww = round( w*cos(theta) + h*abs(sin(theta)));      %Round to nearest integer

R = [cos(theta) -sin(theta); sin(theta) cos(theta)];
T = [w/2; h/2];
RT = [inv(R) T; 0 0 1];
for z = 1:p
for x = 1:ww
    for y = 1:hh
        % Using matrix multiplication
        i = zeros(3,1);
        i = RT*[x-ww/2; y-hh/2; 1];


        %% Nearest Neighbour
        i = round(i);
        if i(1)>0 && i(2)>0 && i(1)<=w && i(2)<=h
            im2(y,x,z) = im1(i(2),i(1),z);
        end
    end
end
end



 x=1:ww;
 y=1:hh;

 [X, Y] = meshgrid(x,y);      %  Generate X and Y arrays for 3-D plots
 orig_pos = [X(:)' ; Y(:)' ; ones(1,numel(X))];   %  Number of elements in array or   subscripted array expression
 orig_pos_2 = [X(:)'-(ww/2) ; Y(:)'-(hh/2) ; ones(1,numel(X))];

 new_pos = round(RT*orig_pos_2); % Round to nearest neighbour

 % Check if new positions fall from map:
 valid_pos = new_pos(1,:)>=1 & new_pos(1,:)<=w & new_pos(2,:)>=1 & new_pos(2,:)<=h;

 orig_pos = orig_pos(:,valid_pos);
 new_pos = new_pos(:,valid_pos);

 siz = size(im1);
 siz2 = size(im2);

%  Expand the 2D indices to include the third dimension.
 ind_orig_pos = sub2ind(siz2,orig_pos(2*ones(p,1),:),orig_pos(ones(p,1),:), (1:p)'*ones(1,length(orig_pos)));
 ind_new_pos  = sub2ind(siz, new_pos(2*ones(p,1),:), new_pos(ones(p,1),:), (1:p)'*ones(1,length(new_pos)));

 im2(ind_orig_pos) = im1(ind_new_pos);
  imshow(im2);
4

1 回答 1

2

的初始化存在问题im2,或者更确切地说,缺少它。im2在如下所示的部分中创建:

if i(1)>0 && i(2)>0 && i(1)<=w && i(2)<=h
    im2(y,x,z) = im1(i(2),i(1),z);
end

如果im2在此代码运行之前存在并且其宽度或高度大于您正在生成的图像,则新图像只会覆盖现有im2. im2尝试通过添加来初始化

im2 = zeros(hh, ww, p);    

for z = 1:p
    for x = 1:ww
        for y = 1:hh
             ...

im2作为奖励,它可能会使您的代码更快一点,因为 Matlab在循环中增长时不必调整大小。

于 2013-03-26T19:34:02.313 回答