2015-07-20 36 views
-1

我從參考圖像Ir中抽取一些像素,然後在輔助圖像In上移動它們。我已經寫入的第一個功能如下:從圖像中提取像素 - 提高性能

[r,c,d] = size(Ir); 
rSample = fix(r * 0.4);   % sample 40 percent of pixels 
cSample = fix(c * 0.4);   % sample 40 percent of pixels 
rIdx = randi(r,rSample,1);  % uniformly sample indices for rows 
cIdx = randi(c,cSample,1);  % uniformly sample indices for columns 
kk = 1; 
for ii = 1:length(rIdx) 
    for jj=1:length(cIdx) 
     In(rIdx(ii),cIdx(jj),:) = Ir(rIdx(ii),cIdx(jj),:) * fcn(rIdx(ii),cIdx(jj)); 
     kk = kk + 1; 
    end 
end 

加大碼的性能(速度)的另一種方法,我來圍繞如下:

nSample = fix(r*c*0.4); 
Idx = randi(r*c,nSample,1); 
for ii = 1:nSample 
    [I,J] = ind2sub([r,c],Idx(ii,1)); 
    In(I,J,:) = Ir(I,J,:) * fcn(I,J); 
end 

在這兩種代碼,fcn(I,J)是對[I,J]中的像素執行一些計算的函數,並且該處理可以根據像素的索引而不同。 儘管我已經刪除了一個for-loop,但我想還是有更好的技術來提高代碼的性能。

更新:

至於建議由@Daniel代碼的下面一行做這項工作。

In(rIdx,cIdx,:)=Ir(rIdx,cIdx,:); 

但重點是,我更喜歡只有採樣的像素能夠更快地處理它們。例如,採用矢量格式的樣本,RGB爲3層。

Io = Ir(rIdx,cIdx,:); 
Io1 = Io(:,:,1); 
Io1v = Io1(:); 
+0

'未定義函數或變量「rSample'.'用於第一和'未定義的函數‘sampleIdx’的輸入 參數類型爲」 double'.'對第二個例子的代碼。首先是清楚如何解決,其次不是真的。 – Daniel

+0

現在這兩個版本都在工作,但實現了不同的模式。用'In = ones(r,c,d)'和'Ir = In * 0'來嘗試。第一個代碼總是生成一個白色條紋圖案。 – Daniel

+0

我不明白你的更新。它不包含解決方案嗎? 'Io = Ir(rIdx,cIdx,:);' – Daniel

回答

1
Ir=ones(30,30,3); 
In=Ir*.5; 
[r,c,d] = size(Ir); 
rSamples = fix(r * 0.4);   % sample 40 percent of pixels 
cSamples = fix(c * 0.4);   % sample 40 percent of pixels 
rIdx = randi(r,rSamples,1);  % uniformly sample indices for rows 
cIdx = randi(c,cSamples,1);  % uniformly sample indices for columns 
In(rIdx,cIdx,:)=Ir(rIdx,cIdx,:);