Rajat Jog
Rajat Jog

Reputation: 53

Crop the rectangular paper from the image

from the discussion : Crop exactly document paper from image I'm trying to get the white paper from the image and I'm using the following code which not cropping exactly rectangular.

def crop_image(image):
image = cv2.imread(image)

# convert to grayscale image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# threshold
thresh = cv2.threshold(gray, 190, 255, cv2.THRESH_BINARY)[1]

# apply morphology
kernel = np.ones((7, 7), np.uint8)
morph = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
kernel = np.ones((9, 9), np.uint8)
morph = cv2.morphologyEx(morph, cv2.MORPH_ERODE, kernel)


# Get Largest contour
contours = cv2.findContours(morph, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
contours = contours[0] if len(contours) == 2 else contours[1]
area_thresh = 0
for cnt in contours:
    area = cv2.contourArea(cnt)
    if area > area_thresh:
        area_thresh = area
        big_contour = cnt

# get bounding box
x, y, w, h = cv2.boundingRect(big_contour)

# draw filled contour on black background
mask = np.zeros_like(gray)
mask = cv2.merge([mask, mask, mask])
cv2.drawContours(mask, [big_contour], -1, (255, 255, 255), cv2.FILLED)

# apply mask to input
result = image.copy()
result = cv2.bitwise_and(result, mask)

# crop result
img_result = result[y:y+h, x:x+w]
filename = generate_filename()
cv2.imwrite(filename, img_result)
logger.info('Successfully saved cropped file : %s' % filename)
return img_result, filename

I'm able to get the desired result but not the rectangular image. Here I'm attaching Originally captured photo and here is what I'm getting after cropping image Cropped image. I want a rectangular image of the paper. Please help me with this.

Thanks in advance

Upvotes: 1

Views: 229

Answers (1)

E. Soria
E. Soria

Reputation: 71

The first problem I can see is that the threshold value is not low enough so the bottom part of the paper is not correctly capture (it's too dark to be captured by the threshold)

The second problem as far I can understand is being able to fit the square to the image. What you need to do is wrapping perspective.

To do that you can find more information in this amazing post of PyImageSearch

Upvotes: 1

Related Questions