Path: blob/master/Contour-Detection-using-OpenCV/python/contour_extraction/contour_extraction.py
3150 views
import cv212"""3Contour detection and drawing using different extraction modes to complement4the understanding of hierarchies5"""6image2 = cv2.imread('../../input/custom_colors.jpg')7img_gray2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)8ret, thresh2 = cv2.threshold(img_gray2, 150, 255, cv2.THRESH_BINARY)910contours3, hierarchy3 = cv2.findContours(thresh2, cv2.RETR_LIST,11cv2.CHAIN_APPROX_NONE)12image_copy4 = image2.copy()13cv2.drawContours(image_copy4, contours3, -1, (0, 255, 0), 2,14cv2.LINE_AA)15# see the results16cv2.imshow('LIST', image_copy4)17print(f"LIST: {hierarchy3}")18cv2.waitKey(0)19cv2.imwrite('contours_retr_list.jpg', image_copy4)20cv2.destroyAllWindows()2122contours4, hierarchy4 = cv2.findContours(thresh2, cv2.RETR_EXTERNAL,23cv2.CHAIN_APPROX_NONE)24image_copy5 = image2.copy()25cv2.drawContours(image_copy5, contours4, -1, (0, 255, 0), 2,26cv2.LINE_AA)27# see the results28cv2.imshow('EXTERNAL', image_copy5)29print(f"EXTERNAL: {hierarchy4}")30cv2.waitKey(0)31cv2.imwrite('contours_retr_external.jpg', image_copy5)32cv2.destroyAllWindows()3334contours5, hierarchy5 = cv2.findContours(thresh2, cv2.RETR_CCOMP,35cv2.CHAIN_APPROX_NONE)36image_copy6 = image2.copy()37cv2.drawContours(image_copy6, contours5, -1, (0, 255, 0), 2,38cv2.LINE_AA)39# see the results40cv2.imshow('CCOMP', image_copy6)41print(f"CCOMP: {hierarchy5}")42cv2.waitKey(0)43cv2.imwrite('contours_retr_ccomp.jpg', image_copy6)44cv2.destroyAllWindows()4546contours6, hierarchy6 = cv2.findContours(thresh2, cv2.RETR_TREE,47cv2.CHAIN_APPROX_NONE)48image_copy7 = image2.copy()49cv2.drawContours(image_copy7, contours6, -1, (0, 255, 0), 2,50cv2.LINE_AA)51# see the results52cv2.imshow('TREE', image_copy7)53print(f"TREE: {hierarchy6}")54cv2.waitKey(0)55cv2.imwrite('contours_retr_tree.jpg', image_copy7)56cv2.destroyAllWindows()575859