2013-03-26 41 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