0

I'm just working on images and I found difficult on cropping the binary images automatically. I'm new to Image processing. Example images are shown below,

Original image:

enter image description here

Needed output(manually edited by GIMP Image editor):

enter image description here

I needed to crop the image by finding the edges of a whit pixels(mask) in image. But its hard to find the approximate edges. Please help me to find out.

thanks in advance..!

Anwarvic
  • 12,156
  • 4
  • 49
  • 69

1 Answers1

0

You can use findContours to find the bounding of the object, then use minAreaRect to draw your needed output, 1st image. Or you can just draw the bounding of the object, 2nd image.

import cv2
import numpy as np

img = cv2.imread('1.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

_,thresh = cv2.threshold(gray,128,255,cv2.THRESH_BINARY)

_,contours,_ = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

mask = np.zeros(img.shape)

cv2.drawContours(mask, contours, -1 , (255,255,255), 1)

rect = cv2.minAreaRect(contours[0])
box = cv2.boxPoints(rect)

box = np.int0(box)
cv2.drawContours(img,[box],0,(255,255,255),1)

cv2.imshow("img",img)
cv2.imshow("mask",mask)
cv2.waitKey(0)
cv2.destroyAllWindows()

enter image description here

enter image description here

Ha Bom
  • 2,787
  • 3
  • 15
  • 29
  • when I tried for this [image](https://drive.google.com/open?id=1laZW1GDsmtgH2CRfw7FVuv_SLg-ijN6R) it show like [output](https://drive.google.com/open?id=1Cm_gsCz79frQapBETNvYQFm78QM-IPDZ) but needed output is like [this](https://drive.google.com/open?id=1ltEcLDnrjk8w-2JTLp2bpuZbT_ivuqpv).Could you please suggest me any ideas related to this. – Ga Ne Sh Ku Ma R Jan 31 '19 at 06:55
  • `minAreaRect` returns smallest rectangle surrounding the object. If you want the boundary you can just draw the contour as image 2. – Ha Bom Jan 31 '19 at 08:30
  • I want to wrap the object from the image by perspective transform, for that I need edge points, I already tried 'Finding extreme points in contours with OpenCV' by Adrian Rosebrock (pyimagesearch blog owner), but for my case it's not working very well. So that's why I'm posting this question. – Ga Ne Sh Ku Ma R Jan 31 '19 at 09:02
  • So you want to draw a quadrangle which is closest to the object? – Ha Bom Jan 31 '19 at 09:30
  • yes if it makes me to extract the object from the image. My target is to crop the object without noise. – Ga Ne Sh Ku Ma R Jan 31 '19 at 09:52
  • So you should read this post https://stackoverflow.com/questions/28759253/how-to-crop-the-internal-area-of-a-contour – Ha Bom Jan 31 '19 at 09:57
  • I already tried that too, almost similar [output](https://drive.google.com/open?id=1F79alSe2teEpiFtk-PRhI80NB0ro-5lf), I just want to pick the white pixels to form a new image not black. – Ga Ne Sh Ku Ma R Jan 31 '19 at 10:25