-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontour-approximation-1.11.4-receipt.py
43 lines (34 loc) · 1.31 KB
/
contour-approximation-1.11.4-receipt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# import the necessary packages
import cv2
import imutils
# load the receipt image, convert it to grayscale, and detect
# edges
# image = cv2.imread("./images/receipt.png")
image = cv2.imread("./images/dog_contour.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
edged = cv2.Canny(gray, 75, 200)
# show the original image and edged map
cv2.imshow("Original", image)
cv2.imshow("Edge Map", edged)
# find contours in the image and sort them from largest to smallest,
# keeping only the largest ones
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:7]
# loop over the contours
for c in cnts:
# approximate the contour and initialize the contour color
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.1 * peri, True)
# show the difference in number of vertices between the original
# and approximated contours
print("original: {}, approx: {}".format(len(c), len(approx)))
# if the approximated contour has 4 vertices, then we have found
# our rectangle
if len(approx) == 4:
# draw the outline on the image
cv2.drawContours(image, [approx], -1, (0, 255, 0), 2)
# show the output image
cv2.imshow("Output", image)
cv2.waitKey()
cv2.destroyAllWindows()