title: Remove black borders on images with watermarks in Python
body: <p>I have a bunch of image I would like to uniformise by removing black borders. Usually I use the Trim function of Imagemagick with the fuzz parameters but in the case the image have some watermark the result is not here.</p>
  
  <p>Actually I'm making some tests with opencv and morphological transform to try to identify watermark and image and then select the bigger element but I'm really new with opencv and I struggle.</p>
  
  <p>Watermark can be everywhere, from bottom left to upper right.</p>
  
  <p><img src="https://i.stack.imgur.com/PXttd.jpg" alt="black borders with watermak 1"> 
  <img src="https://i.stack.imgur.com/9OQhI.jpg" alt="black borders with watermak 2">
  <img src="https://i.stack.imgur.com/EO2sr.jpg" alt="black borders with watermak 3"></p>
  
  <p>I would prefer a Python code but using some app like Imagemagick or similar is welcome.</p>
  
  <p>Actually using opencv only I get this result:</p>
  
  <pre><code>import copy
  import cv2
  
  from matplotlib import pyplot as plt
  
  
  IMG_IN = '/data/black_borders/island.jpg'
  
  
  # keep a copy of original image
  original = cv2.imread(IMG_IN)
  
  # Read the image, convert it into grayscale, and make in binary image for threshold value of 1.
  img = cv2.imread(IMG_IN,0)
  
  # use binary threshold, all pixel that are beyond 3 are made white
  _, thresh_original = cv2.threshold(img, 3, 255, cv2.THRESH_BINARY)
  
  # Now find contours in it.
  thresh = copy.copy(thresh_original)
  contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
  
  # get contours with highest height
  lst_contours = []
  for cnt in contours:
      ctr = cv2.boundingRect(cnt)
      lst_contours.append(ctr)
  x,y,w,h = sorted(lst_contours, key=lambda coef: coef[3])[-1]
  
  
  # draw contours
  ctr = copy.copy(original)
  cv2.rectangle(ctr, (x,y),(x+w,y+h),(0,255,0),2)
  
  
  # display results with matplotlib
  
  # original
  original = original[:,:,::-1] # flip color for maptolib display
  plt.subplot(221), plt.imshow(original)
  plt.title('Original Image'), plt.xticks([]),plt.yticks([])
  
  # Threshold
  plt.subplot(222), plt.imshow(thresh_original, cmap='gray')
  plt.title('threshold binary'), plt.xticks([]),plt.yticks([])
  
  # selected area for future crop
  ctr = ctr[:,:,::-1] # flip color for maptolib display
  plt.subplot(223), plt.imshow(ctr)
  plt.title('Selected area'), plt.xticks([]),plt.yticks([])
  
  plt.show()
  </code></pre>
  
  <p>results:</p>
  
  <p><img src="https://i.stack.imgur.com/FcSIb.jpg" alt="enter image description here"></p>