2016-01-06 118 views
1

我需要使用圖像2中的rgb值更新圖像1以獲取特定座標。MATLAB - 將一個3d陣列的特定值複製到另一個

我有兩個2d矩陣(im1Cart_toupdate 2x114056和im2EstCart_tocopy也是2x114056)。這些包含我想要從圖像2複製rgb值到圖像1的有序x-y對。

即有114,056像素,我希望在其中複製顏色。

im1(440x1370x3)和im2(240x320x3)是圖像陣列。注意im2將被拉伸,因此來自im2的一些像素將在im2EstCart_tocopyfrom中出現多次。

我需要一個有效的方法來做到這一點,因爲即使對於上面的圖像尺寸,我目前的實現也很慢。我曾認爲可能有一些使用sub2ind的方法 - 但我不確定如何用3d數組來做到這一點。

這是我目前的代碼。這是for循環,殺了我!

%Create a matrix of all pixel coordinates in im1 (homogenised form) 
[im1gridx im1gridy]=meshgrid(1:im1width,1:im1height); 
im1Cart = [im1gridx(:) im1gridy(:)]'; 
im1Hom = [im1Cart; ones(1,numel(im1gridy))]; 

%transform pixel positions with homography (HEst is a matrix built 
%elsewhere) to find where they are in the coordinates of image 2 
im2EstHom = HEst*im1Hom; 
im2EstCart = im2EstHom(1:2,:)./repmat(im2EstHom(3,:),2,1); 
im2EstCart = round(im2EstCart); 

%check if the the transformed position is within the boundary of image 2 
validCoords = im2EstCart(1,:)>0 & im2EstCart(2,:)>0 & im2EstCart(1,:)<=im2width & im2EstCart(2,:)<=im2height; 
im1Cart_toupdate=im1Cart(:,validCoords); 
im2EstCart_tocopyfrom=im2EstCart(:,validCoords); 

%copy colour from image 2 to image 1 - currently pixel by pixel 
%but CAN THIS BE VECTORISED? 
for i=1:size(im1Cart_toupdate,2) 
    im1y=im1Cart_toupdate(1,i); 
    im1x=im1Cart_toupdate(2,i); 
    im2y=im2EstCart_tocopyfrom(1,i); 
    im2x=im2EstCart_tocopyfrom(2,i); 
    im1(im1y,im1x,:) = im2(im2y,im2x,:); 
    drawnow 
end 

非常感謝您的任何建議!

回答

1

方法#1

這將是使用linear indexingbsxfun一個矢量化方法 -

[m2,n2,r2] = size(im2); 
RHS_idx1 = (im2EstCart_tocopyfrom(2,:)-1)*m2 + im2EstCart_tocopyfrom(1,:) 
RHS_allidx = bsxfun(@plus,RHS_idx1(:),(0:r2-1)*m2*n2) 

[m1,n1,r1] = size(im1); 
LHS_idx1 = (im1Cart_toupdate(2,:)-1)*m1 + im1Cart_toupdate(1,:) 
LHS_allidx = bsxfun(@plus,LHS_idx1(:),(0:r1-1)*m1*n1) 

im1(LHS_allidx) = im2(RHS_allidx) 

方法2

這裏的另一種方法是,輸入3D陣列重塑到然後,在合併前兩個維度之後,一個2D數組使用linear indexing提取和設定值,最終重塑恢復到原來的大小3D,像這樣 -

[m2,n2,r2] = size(im2) 
RHS_idx1 = (im2EstCart_tocopyfrom(2,:)-1)*m2 + im2EstCart_tocopyfrom(1,:) 
im2r = reshape(im2,[],r2) 

[m1,n1,r1] = size(im1) 
LHS_idx1 = (im1Cart_toupdate(2,:)-1)*m1 + im1Cart_toupdate(1,:) 
im1r = reshape(im1,[],r1) 
im1r(LHS_idx1,:) = im2r(RHS_idx1,:) 

im1 = reshape(im1r,size(im1)); 
+0

非常感謝Divakar。我採取了方法2,它完美地工作。 – rupchap

+0

實際上,我做了一個小修改,即將im2EstCart_tocopy的索引從(2,:)從im1EstCart_tocopy(1,:)和im1Cart_topupdate()的類似物中交換。這是因爲這些矩陣存儲第一行中的X座標,第二行中存儲Y座標,並且因爲圖像數組im1和im2在第一維中具有Y值,在第二維中存儲X值。 (雖然從我上面發佈的代碼中看不到這一點)。再次感謝。 – rupchap

相關問題