title: Check for pixel values in a neighborhood
body: <p>I'm trying to write a MATLAB script that does the following:</p>
  
  <p>Given: pixel coordinates(x,y) for a .jpg image
  Goal: Check, within a 5 pixel radius of given coordinates, if there is a pixel of a certain value. </p>
  
  <p>For example, let's say I'm given the coordinates (100,100), then I want to check the neighborhood of (100,100) within my image for any pixels that are black (0,0,0). So perhaps, pixel (103, 100) and (104,100) might have the value (0,0,0). </p>
  
  <p><strong>Current code</strong>: </p>
  
  <pre><code>x_coord = uint32(coord(:,1));  
  y_coord = uint32(coord(:,2));
  count = 0;
  
  for i = 1:length(x_coord)
      %(img(x,y) returns pixel value at that (x,y)
      %Note 0 = black. Indicating that, at that position, the image is just 
      % black 
      if img(x_coord(i),y_coord(i)) == 0 
          count = count + 1;
      end
  end
  </code></pre>
  
  <p>It currently only checks at an exact location. Not in a local neighborhood. How to could I extend this?</p>
  
  <p><strong>EDIT:</strong> Also note, as long as there as at least one pixel in the neighborhood with the value, I increment count. I'm <em>not trying to enumerate</em> how many pixels in the neighborhood have that value, just <em>trying to find evidence</em> of at least one pixel that has that value.</p>
  
  <p>EDIT:</p>
  
  <p>Even though I am unable to identify an error with the code, I am not able to get the exact results I want. Here is the code I am using. </p>
  
  <pre><code>val = 0; %pixel value to check
  N = 50; % neighbourhood radius
  
  %2D grid of coordinates surrounding center coordinate
  [R, C] = ndgrid(1 : size(img, 1), 1 : size(img, 2));
  
  for kk = 1 : size(coord, 1)
      r = coord(kk, 1); c = coord(kk, 2); % Get pixel locations
  
      % mask of valid locations within the neighbourhood (avoid boundary problems)
      mask = (R - r).^2 + (C - c).^2 &lt;= N*N;         
  
      pix = img(mask); % Get the valid pixels
      valid = any(pix(:) ~= val);
      % Add either 0 or 1 depending if we have found any matching pixels
      if(valid == 1)
          img = insertMarker(img, [r c], 'x', 'color', 'red', 'size', 10);
          imwrite(img, images(i).name,'tiff');
      end
      count = count + valid; 
  end
  </code></pre>