title: How can I detect uniform color rectangles in an image using OpenCV?
body: <p>I would like to use OpenCV to detect which rectangles in an image have a majority of pixels close to a given color.</p>
  
  <p>Here's an example of an image I would like to process using this to identify rectangular regions that contain mostly gray pixels (possibly roads):</p>
  
  <p><a href="https://i.stack.imgur.com/ux5SO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ux5SO.png" alt="looking for roads"></a></p>
  
  <p>More precisely, given:</p>
  
  <ul>
  <li>dimensions <em>h</em> x <em>w</em> (height and weight of candidate rectangles)</li>
  <li>a distance function <em>dist</em> for colors (for example, the norm of the vector difference between the color vector, which could be RGB or any other representation)</li>
  <li>a color vector <em>C</em></li>
  <li>a maximum distance <em>d</em> for colors to be from <em>C</em></li>
  <li>a minimum percentage rate <em>r</em> of pixels in a given rectangle to be within distance <em>d</em> from <em>C</em> for the rectangle to be of interest,</li>
  </ul>
  
  <p>return a mask <em>M</em> in which each pixel <em>P</em> is 1 if the rectangle of size <em>h</em> x <em>w</em> left-cornered by <em>P</em> contains at least <em>r</em> % of its pixels within distance <em>d</em> from <em>C</em> when measured with <em>dist</em>.</p>
  
  <p>In pseudo-code, pixel <em>P</em> in the mask is 1 if and only if:</p>
  
  <pre><code>def rectangle_left_cornered_at_P_is_of_interest(P):
      n_pixels_near_C = size([P' for P' in rectangle(P, P + (h,w)) if dist(P',C) &lt; d])
      return n_pixels_near_C / (h * w) &gt; r
  </code></pre>
  
  <p>I imagine there may already exist a filter/kernel that does just that (or can be used to do that) in OpenCV, but I am still learning about it and could not identify one by looking at the documentation. Is there such a thing?</p>