Skip to content

Instantly share code, notes, and snippets.

@soura-b
Created August 27, 2021 04:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soura-b/bfc6e973c2e2b13f7d6046adf7074c5e to your computer and use it in GitHub Desktop.
Save soura-b/bfc6e973c2e2b13f7d6046adf7074c5e to your computer and use it in GitHub Desktop.
Contour detection - TREE mode
import cv2
import numpy as np
# https://learnopencv.com/read-display-and-write-an-image-using-opencv/
# https://learnopencv.com/contour-detection-using-opencv-python-c/
image = cv2.imread('foot2.jpeg', 1) # 1 for color, 0 for greyscale
# stored as <class 'numpy.ndarray'>
img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# apply binary thresholding
ret, thresh = cv2.threshold(img_gray, 28, 255, cv2.THRESH_BINARY)
print(type(image))
cv2.imshow('primary', image) # first argument (primary) is the window_name
# specify a new window name for each image
cv2.imshow('gray', img_gray)
cv2.imshow('binary', thresh)
# detect the contours on the binary image using cv2.CHAIN_APPROX_SIMPLE
contours, hierarchy = cv2.findContours(image=thresh, mode=cv2.RETR_TREE, method=cv2.CHAIN_APPROX_SIMPLE)
print(hierarchy)
# result format [Next, Previous, First_Child, Parent]
# draw contours on the original image
image_copy = image.copy()
cv2.drawContours(image=image_copy, contours=contours, contourIdx=-1, color=(0, 255, 0), thickness=2,
lineType=cv2.LINE_AA)
# see the results
cv2.imshow('Approx simple', image_copy)
# waitKey() waits for a key press to close the window and 0 specifies indefinite loop
# without this command, cv2 will open and close windows immediately
cv2.waitKey(0)
# save result
# cv2.imwrite('contours_none_foot2_v2.jpg', image_copy)
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment