Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/Contour-Detection-using-OpenCV/python/channel_experiments/channel_experiments.py
3150 views
1
"""
2
This Python script shows why we need to convert the image to grayscale
3
and why other single channel values like R, G, and B, do not work well for
4
contour detection.
5
"""
6
7
import cv2
8
9
# read the image
10
image = cv2.imread('../../input/image_1.jpg')
11
12
# B, G, R channel splitting
13
blue, green, red = cv2.split(image)
14
15
# detect contours using blue channel and without thresholding
16
contours1, hierarchy1 = cv2.findContours(image=blue, mode=cv2.RETR_TREE,
17
method=cv2.CHAIN_APPROX_NONE)
18
19
# draw contours on the original image
20
image_contour_blue = image.copy()
21
cv2.drawContours(image=image_contour_blue, contours=contours1, contourIdx=-1,
22
color=(0, 255, 0), thickness=2, lineType=cv2.LINE_AA)
23
# see the results
24
cv2.imshow('Contour detection using blue channels only', image_contour_blue)
25
cv2.waitKey(0)
26
cv2.imwrite('blue_channel.jpg', image_contour_blue)
27
cv2.destroyAllWindows()
28
29
# detect contours using green channel and without thresholding
30
contours2, hierarchy2 = cv2.findContours(image=green, mode=cv2.RETR_TREE,
31
method=cv2.CHAIN_APPROX_NONE)
32
# draw contours on the original image
33
image_contour_green = image.copy()
34
cv2.drawContours(image=image_contour_green, contours=contours2, contourIdx=-1,
35
color=(0, 255, 0), thickness=2, lineType=cv2.LINE_AA)
36
# see the results
37
cv2.imshow('Contour detection using green channels only', image_contour_green)
38
cv2.waitKey(0)
39
cv2.imwrite('green_channel.jpg', image_contour_green)
40
cv2.destroyAllWindows()
41
42
# detect contours using red channel and without thresholding
43
contours3, hierarchy3 = cv2.findContours(image=red, mode=cv2.RETR_TREE,
44
method=cv2.CHAIN_APPROX_NONE)
45
# draw contours on the original image
46
image_contour_red = image.copy()
47
cv2.drawContours(image=image_contour_red, contours=contours3, contourIdx=-1,
48
color=(0, 255, 0), thickness=2, lineType=cv2.LINE_AA)
49
# see the results
50
cv2.imshow('Contour detection using red channels only', image_contour_red)
51
cv2.waitKey(0)
52
cv2.imwrite('red_channel.jpg', image_contour_red)
53
cv2.destroyAllWindows()
54