我正在研究从灰色图像中随机选择像素组的代码,然后通过从不同位置的另一个位置减去一个位置的像素强度来比较每个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)
}
答案 0 :(得分:0)
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);