title: How to detect and extract signature from an image with OpenCV?
body: <p>I am importing the attached image. After importing the image, I want to remove horizontal lines, detect the signature and then extract it, create rectangle around signature, crop the rectangle and save it. I am struggling to identify entire region of a signature as one contour or a group of contours.</p>
  <p>I have already tried <code>findcontour</code> and then various ways to detect signature region. Please refer the code below.</p>
  <p><strong>Python Script:</strong></p>
  <pre><code>imagePath
  
  #read image
  image = cv2.imread(imagePath,cv2.COLOR_BGR2RGB)
  
  #Convert to greyscale
  gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # grayscale
  
  #Apply threshold
  ret,thresh1 = cv2.threshold(gray, 0, 255,cv2.THRESH_OTSU|cv2.THRESH_BINARY_INV)
  
  plt.imshow(thresh1,cmap = 'gray')
  
  
  #preprocessing
  rect_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15,15))
  dilation = cv2.dilate(thresh1, rect_kernel, iterations = 1)
  plt.imshow(dilation,cmap = 'gray')
  
  
  #Detect contours
  contours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
  contours[0]
  
  height, width, _ = image.shape
  min_x, min_y = width, height
  max_x = max_y = 0   
  for contour, hier in zip(contours, hierarchy):
      (x,y,w,h) = cv2.boundingRect(contour)
      min_x, max_x = min(x, min_x), max(x+w, max_x)
      min_y, max_y = min(y, min_y), max(y+h, max_y)
      if w &gt; 80 and h &gt; 80:
          cv2.rectangle(frame, (x,y), (x+w,y+h), (255, 0, 0), 2)
  
  if max_x - min_x &gt; 0 and max_y - min_y &gt; 0:
      fin=cv2.rectangle(image, (min_x, min_y), (max_x, max_y), (255, 0, 0), 2)
  
   
  
  plt.imshow(fin)
  
  
  
  final=cv2.drawContours(image, contours,-1,(0,0,255),6)
  
  plt.imshow(final,cmap = 'gray')
  </code></pre>
  <p>Final objective is to create rectangle around entire signature</p>
  <p><a href="https://i.stack.imgur.com/JpGZQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JpGZQ.jpg" alt="Signature image on which I am trying" /></a></p>
  <p>Trying to generalize on the other image:</p>
  <p><a href="https://i.stack.imgur.com/EuPKA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EuPKA.jpg" alt="enter image description here" /></a></p>