2014-10-18 33 views
0

我正在研究從灰度圖像中隨機選擇一組像素的代碼,然後通過從不同位置的另一個位置減去一個位置的像素強度來比較每個2像素的亮度。 我有代碼做隨機選擇,但我不確定這段代碼,我不知道如何做像素減法? 謝謝你提前..像素減法

{ 
N = 100; % number of random pixels 
im = imread('image.bmp'); 
[nRow,nCol,c] = size(im); 
randRow = randi(nRow,[N,1]); 
randCol = randi(nCol,[N,1]); 

subplot(2,1,1) 
imagesc(im(randRow,randCol,:)) 
subplot(2,1,2) 
imagesc(im) 
} 
+1

查找'sub2ind' – 2014-10-18 01:29:47

回答

0

Parag基本上給了你答案。爲了實現這種矢量化,您需要使用sub2ind。但是,我會做的是生成兩組行和列。原因是因爲你需要一組像素和另一組像素,因此你可以減去兩組強度。因此,做這樣的事情:

N = 100; % number of random pixels 
im = imread('image.bmp'); 
[nRow,nCol,c] = size(im); 

%// Generate two sets of locations 
randRow1 = randi(nRow,[N,1]); 
randCol1 = randi(nCol,[N,1]); 
randRow2 = randi(nRow,[N,1]); 
randCol2 = randi(nCol,[N,1]); 

%// Convert each 2D location into a single linear index 
%// for vectorization, then subtract 
locs1 = sub2ind([nRow, nCol], randRow1, randCol1); 
locs2 = sub2ind([nRow, nCol], randRow2, randCol2); 

im_subtract = im(locs1) - im(locs2); 
subplot(2,1,1) 
imagesc(im_subtract); 
subplot(2,1,2) 
imagesc(im); 

然而,上面的代碼只假定你的形象是灰度。如果你想爲顏色做這個,你必須做更多的工作。您需要訪問每個頻道並按頻道進行相減。上面定義的線性索引僅適用於單個通道。因此,如果您想訪問下一個頻道中相同的相應位置,則需要爲每個頻道偏移nRow*nCol。因此,我會使用sub2ind結合bsxfun正確生成向量化減法的正確值。這隻需要稍微修改上面的代碼。因此:

N = 100; % number of random pixels 
im = imread('image.bmp'); 
[nRow,nCol,c] = size(im); 

%// Generate two sets of locations 
randRow1 = randi(nRow,[N,1]); 
randCol1 = randi(nCol,[N,1]); 
randRow2 = randi(nRow,[N,1]); 
randCol2 = randi(nCol,[N,1]); 

%// Convert each 2D location into a single linear index 
%// for vectorization 
locs1 = sub2ind([nRow, nCol], randRow1, randCol1); 
locs2 = sub2ind([nRow, nCol], randRow2, randCol2); 

%// Extend to as many channels as we have 
skip_ind = permute(0:nRow*nCol:(c-1)*nRow*nCol, [1 3 2]); 

%// Create 3D linear indices 
locs1 = bsxfun(@plus, locs1, skip_ind); 
locs2 = bsxfun(@plus, locs2, skip_ind); 

%// Now subtract the locations 
im_subtract = im(locs1) - im(locs2); 
subplot(2,1,1) 
imagesc(im_subtract); 
subplot(2,1,2) 
imagesc(im); 
+0

我已經試過這個代碼和它的工作,但我期待的結果是different.the像我已經被劃分成更小的補丁,則選擇像素隨機均勻,這意味着選擇方法應始終保持一致。任何想法 ? – user3485941 2014-11-01 23:43:18