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);
查找'sub2ind' – 2014-10-18 01:29:47