Skip to content

Instantly share code, notes, and snippets.

@soura-b
Created September 3, 2021 10:32
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/4990ab899a3b0f89e0974d3e1e772699 to your computer and use it in GitHub Desktop.
Save soura-b/4990ab899a3b0f89e0974d3e1e772699 to your computer and use it in GitHub Desktop.
Contour detection with adaptive gaussian thresholding
import cv2
import numpy as np
image = cv2.imread('images_09_03/Lot1_RT.jpeg', 1)
img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# apply adaptive gaussian thresholding
thresh = cv2.adaptiveThreshold(img_gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2)
cv2.imshow('primary', image)
cv2.imshow('gray', img_gray)
cv2.imshow('binary', thresh)
# detect the contours on the binary image using CHAIN_APPROX_SIMPLE and mode RETR_EXTERNAL vs _TREE
contours, hierarchy = cv2.findContours(image=thresh, mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_SIMPLE)
# 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('Outlined', image_copy)
cv2.waitKey(0)
cv2.imwrite('images_09_03/Lot1_RT_outlined.jpeg', image_copy)
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment