Path: blob/master/Contour-Detection-using-OpenCV/python/contour_approximations/contour_approx.py
3150 views
import cv212# read the image3image = cv2.imread('../../input/image_1.jpg')4# convert the image to grayscale format5img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)6# apply binary thresholding7ret, thresh = cv2.threshold(img_gray, 150, 255, cv2.THRESH_BINARY)8# visualize the binary image9cv2.imshow('Binary image', thresh)10cv2.waitKey(0)11cv2.imwrite('image_thres1.jpg', thresh)12cv2.destroyAllWindows()1314# detect the contours on the binary image using cv2.CHAIN_APPROX_NONE15contours, hierarchy = cv2.findContours(image=thresh, mode=cv2.RETR_TREE,16method=cv2.CHAIN_APPROX_NONE)17# draw contours on the original image18image_copy = image.copy()19cv2.drawContours(image=image_copy, contours=contours, contourIdx=-1,20color=(0, 255, 0), thickness=2, lineType=cv2.LINE_AA)21# see the results22cv2.imshow('None approximation', image_copy)23cv2.waitKey(0)24cv2.imwrite('contours_none_image1.jpg', image_copy)25cv2.destroyAllWindows()2627"""28Now let's try with `cv2.CHAIN_APPROX_SIMPLE`29"""30# detect the contours on the binary image using cv2.ChAIN_APPROX_SIMPLE31contours1, hierarchy1 = cv2.findContours(thresh, cv2.RETR_TREE,32cv2.CHAIN_APPROX_SIMPLE)33# draw contours on the original image for `CHAIN_APPROX_SIMPLE`34image_copy1 = image.copy()35cv2.drawContours(image_copy1, contours1, -1, (0, 255, 0), 2,36cv2.LINE_AA)37# see the results38cv2.imshow('Simple approximation', image_copy1)39cv2.waitKey(0)40cv2.imwrite('contours_simple_image1.jpg', image_copy1)41cv2.destroyAllWindows()4243# to actually visualize the effect of `CHAIN_APPROX_SIMPLE`, we need a proper image44image1 = cv2.imread('../../input/image_2.jpg')45img_gray1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)46ret, thresh1 = cv2.threshold(img_gray1, 150, 255, cv2.THRESH_BINARY)47contours2, hierarchy2 = cv2.findContours(thresh1, cv2.RETR_TREE,48cv2.CHAIN_APPROX_SIMPLE)49image_copy2 = image1.copy()50cv2.drawContours(image_copy2, contours2, -1, (0, 255, 0), 2,51cv2.LINE_AA)52cv2.imshow('SIMPLE Approximation contours', image_copy2)53cv2.waitKey(0)54image_copy3 = image1.copy()55for i, contour in enumerate(contours2): # loop over one contour area56for j, contour_point in enumerate(contour): # loop over the points57# draw a circle on the current contour coordinate58cv2.circle(image_copy3, ((contour_point[0][0], contour_point[0][1])),592, (0, 255, 0), 2, cv2.LINE_AA)60# see the results61cv2.imshow('CHAIN_APPROX_SIMPLE Point only', image_copy3)62cv2.waitKey(0)63cv2.imwrite('contour_point_simple.jpg', image_copy3)64cv2.destroyAllWindows()6566