title: Find Region Boundaries in Marked Object in OpenCV for Python
body: <p>I'm looking to find the region boundaries (contour) of a quadrilateral in an image. I know the location of one point within the region, but I don't know much a priori about the color/size properties of the region. All I know is that there will be a strong edge surrounding the entire region and that it's a quadrilateral. </p>
  
  <p>Currently, I'm using a thresholding algorithm to find areas close in intensity/color to the starting point, and then finding the largest resulting contour that contains the reference point. However, there can be a gradual change in intensity/color over the region, which can cause this to fail. Below is a sample image as well as a snippet of my code using this method. It works okay with the first image, but not the second.</p>
  
  <pre><code>I = imread('bluerect.jpg') # Read image
  reference_marker = np.array([460,950]) # Manually mark note
  I_hsv = cv2.cvtColor(I, cv2.COLOR_BGR2HSV)
  
  # Set bounds based on color of reference point
  hsv_value = I_hsv[reference_marker[0],reference_marker[1],:]
  lower = np.array([hsv_value[0]-8,hsv_value[1]-hsv_value[1]*.3, hsv_value[2]-hsv_value[2]*.7])
  upper = np.array([hsv_value[0]+8,hsv_value[1]+hsv_value[1]*.3, hsv_value[2]+hsv_value[2]*.7])
  mask = cv2.inRange(I_hsv, lower, upper) # Find what's in that range
  
  # Fill holes in mask with morphological close
  closed_mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((5,5),np.uint8))
  
  # Find the contour with the maximum area that contains marker
  ret, contours, hierarchy = cv2.findContours(closed_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  for target in sorted(contours, key = cv2.contourArea, reverse=True):
      bb = cv2.boundingRect(target)
      if (bb[0] &lt; center[0] &lt; bb[0]+bb[2]) &amp; (bb[1] &lt; center[1] &lt; bb[1] + bb[3]):
          break
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/erBRf.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/erBRf.jpg" alt="Image 1 - Blue Rectangle"></a>
  <a href="https://i.stack.imgur.com/Vw0CS.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vw0CS.jpg" alt="Image 2 - White Rectangle"></a></p>
  
  <p>I think the best approach would be to "fill out" from the reference point until I hit a strong, contiguous boundary... something like a watershed algorithm? Anyone have any suggestions?</p>
  
  <p>Thank you! </p>