Matlab图保留了以前图像的历史记录

时间:2013-03-26 18:30:29

标签: matlab image-processing

我正在使用Matlab手动旋转图像。每次我用不同的图像运行我的代码时,旋转的先前图像如图所示。我无法理解。任何帮助都会很明显。 代码在这里:

enter image description here [屏幕快照]

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);

1 个答案:

答案 0 :(得分: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
             ...

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