Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum the 8-neighbor pixel values of the current pixel.

I have a binary image. I want to find the pixel value = 1 and label it as the current pixel. Then, I want to sum its 8-neighbor pixel values. If the summation of the 8-neighbor pixel values of the current pixel = 1, then mark that current pixel with marker. Some part of a binary image as follows:

0 0 0 0 0
0 1 0 0 0
0 0 1 1 0
0 0 0 0 1
0 0 0 0 0

I tried the following matlab code but it has some errors (at this line -> Sums = sum(currentPix, nOffsets);). How can I fix it?


Sums = 0; 
S = size(BW,1);
nOffsets = [S, S+1, 1, -S+1, -S, -S-1, -1, S-1]';  %8-neighbors offsets
BW_Out = BW;

for row=1:S    
   for col=1:S 
     if BW(row,col),
         break; 
      end 
   end 

   idx = sub2ind(size(BW),row,col);
   neighbors = bsxfun(@plus, idx, nOffsets); 
   currentPix = find(BW==1); %if found 1, define it as current pixel 

     while ~isempty(currentPix)

        % new current pixel list is  set of neighbors of current list.
        currentPix = bsxfun(@plus, currentPix, nOffsets);
        currentPix = currentPix(:);
        Sums = sum(currentPix, nOffsets); %error at this line

        if (Sums==1)   %if the sum of 8-neighbor values = 1, mark ROI
            plot(currentPix,'r*','LineWidth',1);
        end

        % Remove from the current pixel list pixels that are already
        currentPix(BW_Out(currentPix)) = [];

        % Remove duplicates from the list.
        currentPix = unique(currentPix);
    end
end   
like image 669
W-W Avatar asked Dec 05 '25 05:12

W-W


1 Answers

I think you can actually do this in one line (after defining a kernel that is)

I = [0 0 0 0 0
     0 1 0 0 0
     0 0 1 1 0
     0 0 0 0 1
     0 0 0 0 0];

K = [1 1 1;
     1 0 1;
     1 1 1;];

(conv2(I,K,'same')==1) & I

ans =

   0   0   0   0   0
   0   1   0   0   0
   0   0   0   0   0
   0   0   0   0   1
   0   0   0   0   0

Breaking this up:

M = conv2(I,K, 'same'); %// convolving with this specific kernel sums up the 8 neighbours excluding the central element (i.e. the 0 in the middle)

(M==1) & I %// Only take results where there was a 1 in the original image.
like image 155
Dan Avatar answered Dec 07 '25 05:12

Dan