Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

So i wrote some Python code to get the contour of the paper sheet.

import numpy as np
import cv2

# Original image
image = cv2.imread('images/sheet.jpg')
# Resize
image = cv2.resize(image, (500,500))
draw = np.zeros_like(image)
# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Get black and white image
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))

# Some erosions and dilations to remove noise.
thresh = cv2.erode(thresh, kernel, iterations=4)
thresh = cv2.dilate(thresh, kernel, iterations=4)

# Get Contours of binary image
im, cnts, hier = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# Find the biggest contour
max_area = -1
max_c = 0
for i in range(len(cnts)):
    contour = cnts[i]
    area = cv2.contourArea(contour)
    if (area > max_area):
        max_area = area
        max_c = i
contour = cnts[max_c]

# Get minAreaRect
rect = cv2.minAreaRect(contour)
box = cv2.boxPoints(rect)
box = np.int0(box)


# Draw contour and minAreaRect
cv2.drawContours(image, [box],-1, (0, 255, 0), 2)
cv2.drawContours(image, [contour], -1, (255,0,0), 2)
cv2.imshow('Sheet', image)

cv2.waitKey(0)
cv2.destroyAllWindows()

After that the image looks like this (blue is the contour and green is the rectangle around the contour:

image description