Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/Contour-Detection-using-OpenCV/python/contour_extraction/contour_extraction.py
3150 views
1
import cv2
2
3
"""
4
Contour detection and drawing using different extraction modes to complement
5
the understanding of hierarchies
6
"""
7
image2 = cv2.imread('../../input/custom_colors.jpg')
8
img_gray2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
9
ret, thresh2 = cv2.threshold(img_gray2, 150, 255, cv2.THRESH_BINARY)
10
11
contours3, hierarchy3 = cv2.findContours(thresh2, cv2.RETR_LIST,
12
cv2.CHAIN_APPROX_NONE)
13
image_copy4 = image2.copy()
14
cv2.drawContours(image_copy4, contours3, -1, (0, 255, 0), 2,
15
cv2.LINE_AA)
16
# see the results
17
cv2.imshow('LIST', image_copy4)
18
print(f"LIST: {hierarchy3}")
19
cv2.waitKey(0)
20
cv2.imwrite('contours_retr_list.jpg', image_copy4)
21
cv2.destroyAllWindows()
22
23
contours4, hierarchy4 = cv2.findContours(thresh2, cv2.RETR_EXTERNAL,
24
cv2.CHAIN_APPROX_NONE)
25
image_copy5 = image2.copy()
26
cv2.drawContours(image_copy5, contours4, -1, (0, 255, 0), 2,
27
cv2.LINE_AA)
28
# see the results
29
cv2.imshow('EXTERNAL', image_copy5)
30
print(f"EXTERNAL: {hierarchy4}")
31
cv2.waitKey(0)
32
cv2.imwrite('contours_retr_external.jpg', image_copy5)
33
cv2.destroyAllWindows()
34
35
contours5, hierarchy5 = cv2.findContours(thresh2, cv2.RETR_CCOMP,
36
cv2.CHAIN_APPROX_NONE)
37
image_copy6 = image2.copy()
38
cv2.drawContours(image_copy6, contours5, -1, (0, 255, 0), 2,
39
cv2.LINE_AA)
40
# see the results
41
cv2.imshow('CCOMP', image_copy6)
42
print(f"CCOMP: {hierarchy5}")
43
cv2.waitKey(0)
44
cv2.imwrite('contours_retr_ccomp.jpg', image_copy6)
45
cv2.destroyAllWindows()
46
47
contours6, hierarchy6 = cv2.findContours(thresh2, cv2.RETR_TREE,
48
cv2.CHAIN_APPROX_NONE)
49
image_copy7 = image2.copy()
50
cv2.drawContours(image_copy7, contours6, -1, (0, 255, 0), 2,
51
cv2.LINE_AA)
52
# see the results
53
cv2.imshow('TREE', image_copy7)
54
print(f"TREE: {hierarchy6}")
55
cv2.waitKey(0)
56
cv2.imwrite('contours_retr_tree.jpg', image_copy7)
57
cv2.destroyAllWindows()
58
59