2014-10-18 44 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