Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/Contour-Detection-using-OpenCV/python/contour_approximations/contour_approx.py
3150 views
1
import cv2
2
3
# read the image
4
image = cv2.imread('../../input/image_1.jpg')
5
# convert the image to grayscale format
6
img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
7
# apply binary thresholding
8
ret, thresh = cv2.threshold(img_gray, 150, 255, cv2.THRESH_BINARY)
9
# visualize the binary image
10
cv2.imshow('Binary image', thresh)
11
cv2.waitKey(0)
12
cv2.imwrite('image_thres1.jpg', thresh)
13
cv2.destroyAllWindows()
14
15
# detect the contours on the binary image using cv2.CHAIN_APPROX_NONE
16
contours, hierarchy = cv2.findContours(image=thresh, mode=cv2.RETR_TREE,
17
method=cv2.CHAIN_APPROX_NONE)
18
# draw contours on the original image
19
image_copy = image.copy()
20
cv2.drawContours(image=image_copy, contours=contours, contourIdx=-1,
21
color=(0, 255, 0), thickness=2, lineType=cv2.LINE_AA)
22
# see the results
23
cv2.imshow('None approximation', image_copy)
24
cv2.waitKey(0)
25
cv2.imwrite('contours_none_image1.jpg', image_copy)
26
cv2.destroyAllWindows()
27
28
"""
29
Now let's try with `cv2.CHAIN_APPROX_SIMPLE`
30
"""
31
# detect the contours on the binary image using cv2.ChAIN_APPROX_SIMPLE
32
contours1, hierarchy1 = cv2.findContours(thresh, cv2.RETR_TREE,
33
cv2.CHAIN_APPROX_SIMPLE)
34
# draw contours on the original image for `CHAIN_APPROX_SIMPLE`
35
image_copy1 = image.copy()
36
cv2.drawContours(image_copy1, contours1, -1, (0, 255, 0), 2,
37
cv2.LINE_AA)
38
# see the results
39
cv2.imshow('Simple approximation', image_copy1)
40
cv2.waitKey(0)
41
cv2.imwrite('contours_simple_image1.jpg', image_copy1)
42
cv2.destroyAllWindows()
43
44
# to actually visualize the effect of `CHAIN_APPROX_SIMPLE`, we need a proper image
45
image1 = cv2.imread('../../input/image_2.jpg')
46
img_gray1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
47
ret, thresh1 = cv2.threshold(img_gray1, 150, 255, cv2.THRESH_BINARY)
48
contours2, hierarchy2 = cv2.findContours(thresh1, cv2.RETR_TREE,
49
cv2.CHAIN_APPROX_SIMPLE)
50
image_copy2 = image1.copy()
51
cv2.drawContours(image_copy2, contours2, -1, (0, 255, 0), 2,
52
cv2.LINE_AA)
53
cv2.imshow('SIMPLE Approximation contours', image_copy2)
54
cv2.waitKey(0)
55
image_copy3 = image1.copy()
56
for i, contour in enumerate(contours2): # loop over one contour area
57
for j, contour_point in enumerate(contour): # loop over the points
58
# draw a circle on the current contour coordinate
59
cv2.circle(image_copy3, ((contour_point[0][0], contour_point[0][1])),
60
2, (0, 255, 0), 2, cv2.LINE_AA)
61
# see the results
62
cv2.imshow('CHAIN_APPROX_SIMPLE Point only', image_copy3)
63
cv2.waitKey(0)
64
cv2.imwrite('contour_point_simple.jpg', image_copy3)
65
cv2.destroyAllWindows()
66