Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/ConvexHull/example.py
3118 views
1
import cv2
2
import numpy as np
3
import sys
4
5
if __name__ == "__main__":
6
if(len(sys.argv)) < 2:
7
file_path = "sample.jpg"
8
else:
9
file_path = sys.argv[1]
10
11
# read image
12
src = cv2.imread(file_path, 1)
13
14
# show source image
15
cv2.imshow("Source", src)
16
17
# convert image to gray scale
18
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
19
20
# blur the image
21
blur = cv2.blur(gray, (3, 3))
22
23
# binary thresholding of the image
24
ret, thresh = cv2.threshold(blur, 200, 255, cv2.THRESH_BINARY)
25
26
# find contours
27
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, \
28
cv2.CHAIN_APPROX_SIMPLE)
29
30
# create hull array for convexHull points
31
hull = []
32
33
# calculate points for each contour
34
for i in range(len(contours)):
35
hull.append(cv2.convexHull(contours[i], False))
36
37
# create an empty black image
38
drawing = np.zeros((thresh.shape[0], thresh.shape[1], 3), np.uint8)
39
40
# draw contours and hull points
41
for i in range(len(contours)):
42
color_contours = (0, 255, 0) # color for contours
43
color = (255, 255, 255) # color for convex hull
44
# draw contours
45
cv2.drawContours(drawing, contours, i, color_contours, 2, 8, hierarchy)
46
# draw convex hull
47
cv2.drawContours(drawing, hull, i, color, 2, 8)
48
49
cv2.imshow("Output", drawing)
50
51
cv2.waitKey(0)
52
cv2.destroyAllWindows()
53
54