title: Python - OpenCV - Cropping images and isolating specific objects
body: <p>Using python - OpenCV I have succeeded to read the following image, detect the rectangles , crop them and save every rectangle as an image.</p>
  
  <p><img src="https://i.stack.imgur.com/mwZLV.png" alt="Main Image"></p>
  
  <p>and this is a sample of the rectangles that I have succeeded to crop and save as an image. (So there will be 12 of them)</p>
  
  <p><img src="https://i.stack.imgur.com/AsHDG.png" alt="Rectanle Image"></p>
  
  <p>Then working on every rectangle image, in order to isolate the circle and create a new image for every circle - which I have succeeded to do too using cv2.HoughCircles.</p>
  
  <p>The output of the image <code>A</code> contains the circle looks like :</p>
  
  <p><img src="https://i.stack.imgur.com/6edxT.png" alt="Image contains circle and more"></p>
  
  <p>Now: what I need to do is to remove everything outside of the green circle and convert everything outside the green circle to black, then get <code>B</code>(only the green circle):</p>
  
  <p><img src="https://i.stack.imgur.com/mUb7O.png" alt="Isolated Image Circle"></p>
  
  <p>The question is: How to get <code>B</code> from <code>A</code>. </p>
  
  <p>I take code from <a href="https://stackoverflow.com/questions/48356398/opencv-remove-background-of-an-image/48356640#48356640">OpenCV : Remove background of an image</a>, but it is not work for the image <code>A</code> as excepted, while output such a image instead:</p>
  
  <p><img src="https://imgur.com/2VVSI4W.png" alt=""></p>
  
  <hr>
  
  <p>This is the code taken from <a href="https://stackoverflow.com/questions/48356398/opencv-remove-background-of-an-image/48356640#48356640">OpenCV : Remove background of an image</a>. </p>
  
  <pre><code>circle_path_test = 'D:\rec.png'
  
  img  = cv2.imread(circle_path_test)
  gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  
  ## (2) Threshold
  th, threshed = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)
  
  ## (3) Find the min-area contour
  _, cnts, _ = cv2.findContours(threshed, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  cnts = sorted(cnts, key=cv2.contourArea)
  for cnt in cnts:
      if cv2.contourArea(cnt) &gt; 100:
          break
  
  ## (4) Create mask and do bitwise-op
  mask = np.zeros(img.shape[:2],np.uint8)
  cv2.drawContours(mask, [cnt],-1, 255, -1)
  dst = cv2.bitwise_and(img, img, mask=mask)
  
  ## Save it
  # cv2.imshow("dst.png", dst);cv2.waitKey()       
  #rec_img_name_without_extension ,img_ext = os.path.splitext(circle_path_test)                
  cv2.imwrite(os.path.join(os.getcwd(), 'dst_circle_gray - Copy.png') , dst) 
  </code></pre>