title: Cropping an image after detecting the contours using opencv python
body: <p>I'm trying to crop an image after detecting the contours and then extract information from it using python, opencv, and numpy.</p>
  
  <p>Detecting the contours was successful but then I couldn't find a way to crop. I tried some code but I didn't get the result that I wanted:</p>
  
  <pre><code>import numpy as np
  import cv2
  image = cv2.imread('2.jpg') # Read in your image
  blurred=cv2.blur(image,(23,51))#blur the image
  gray=cv2.cvtColor(blurred,cv2.COLOR_BGR2GRAY)#gray scale
  ret,threshold=cv2.threshold(gray , 2 , 255 , cv2.THRESH_BINARY+cv2.THRESH_OTSU)
  contours,hierachy=cv2.findContours(threshold,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)#detect contours
  mask = np.zeros_like(image) # Create mask where white is what we want, black otherwise
  cv2.drawContours(mask,  contours,  0,  (0 ,0,255),1)
  out = np.zeros_like(image) # Extract out the object and place into output image
  out[mask == 255] = image[mask == 255]
  
  # Now crop
  mask=mask.transpose(2,0,1).reshape(-1,mask.shape[1])
  (x, y) = np.where(mask == 255)
  (topx, topy) = (np.min(x), np.min(y))
  (bottomx, bottomy) = (np.max(x), np.max(y))
  topx=topx
  topy=topy
  bottomx=bottomx
  bottomy=bottomy
  out = out[topx:bottomx,topy:bottomy]
  print(out)
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/VM5z2.png" alt="enter image here"></p>
  
  <p>The array <code>out</code> is  empty which is weird because when I print <code>topx</code>, <code>topy</code>, <code>bottomx</code>, and <code>bottomy</code>, I get integers, so logically cropping would give me a result.</p>