2013-03-26 47 views
0

我正在Matlab中手动旋转图像。每次我用不同的图像运行我的代码时,先前旋转的图像都显示在图中。我无法弄清楚。任何帮助将是可观的。 的代码是在这里: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); 
+2

你每次开始一个新的图像情节时都尝试过使用'cla'吗? – wakjah 2013-03-26 18:33:33

+0

我试过了,但不幸的是它并没有解决问题。 – 2013-03-26 18:42:12

+0

@RuhiAkaboy你有多个数字可以打开吗?如果是这样,你需要把关注的数字放在焦点上。另外,你有代码中的任何地方吗?如果你这样做,你需要在放置图像后放置一个“搁置”。 – Justin 2013-03-26 18:53:46

回答

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。尝试之前

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

加入加入

im2 = zeros(hh, ww, p);  

初始化im2作为奖励它可能使你的代码更快一点,因为Matlab的不会有调整im2,因为它生长在循环。

+0

是啊,其实我没有初始化'im2'之前我用它。谢谢@erikced – 2013-03-26 19:49:26