Path: blob/master/Contour-Detection-using-OpenCV/python/channel_experiments/channel_experiments.py
3150 views
"""1This Python script shows why we need to convert the image to grayscale2and why other single channel values like R, G, and B, do not work well for3contour detection.4"""56import cv278# read the image9image = cv2.imread('../../input/image_1.jpg')1011# B, G, R channel splitting12blue, green, red = cv2.split(image)1314# detect contours using blue channel and without thresholding15contours1, hierarchy1 = cv2.findContours(image=blue, mode=cv2.RETR_TREE,16method=cv2.CHAIN_APPROX_NONE)1718# draw contours on the original image19image_contour_blue = image.copy()20cv2.drawContours(image=image_contour_blue, contours=contours1, contourIdx=-1,21color=(0, 255, 0), thickness=2, lineType=cv2.LINE_AA)22# see the results23cv2.imshow('Contour detection using blue channels only', image_contour_blue)24cv2.waitKey(0)25cv2.imwrite('blue_channel.jpg', image_contour_blue)26cv2.destroyAllWindows()2728# detect contours using green channel and without thresholding29contours2, hierarchy2 = cv2.findContours(image=green, mode=cv2.RETR_TREE,30method=cv2.CHAIN_APPROX_NONE)31# draw contours on the original image32image_contour_green = image.copy()33cv2.drawContours(image=image_contour_green, contours=contours2, contourIdx=-1,34color=(0, 255, 0), thickness=2, lineType=cv2.LINE_AA)35# see the results36cv2.imshow('Contour detection using green channels only', image_contour_green)37cv2.waitKey(0)38cv2.imwrite('green_channel.jpg', image_contour_green)39cv2.destroyAllWindows()4041# detect contours using red channel and without thresholding42contours3, hierarchy3 = cv2.findContours(image=red, mode=cv2.RETR_TREE,43method=cv2.CHAIN_APPROX_NONE)44# draw contours on the original image45image_contour_red = image.copy()46cv2.drawContours(image=image_contour_red, contours=contours3, contourIdx=-1,47color=(0, 255, 0), thickness=2, lineType=cv2.LINE_AA)48# see the results49cv2.imshow('Contour detection using red channels only', image_contour_red)50cv2.waitKey(0)51cv2.imwrite('red_channel.jpg', image_contour_red)52cv2.destroyAllWindows()5354