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