Code for How to Detect Contours in Images using OpenCV in Python Tutorial


View on Github

contour_detector.py

import cv2
import matplotlib.pyplot as plt

# read the image
image = cv2.imread("thumbs_up_down.jpg")
# convert to RGB
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# create a binary thresholded image
_, binary = cv2.threshold(gray, 225, 255, cv2.THRESH_BINARY_INV)
# show it
plt.imshow(binary, cmap="gray")
plt.show()
# find the contours from the thresholded image
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# draw all contours
image = cv2.drawContours(image, contours, -1, (0, 255, 0), 2)
# show the image with the drawn contours
plt.imshow(image)
plt.show()

live-contour-detector.py

import cv2

cap = cv2.VideoCapture(0)

while True:
    _, frame = cap.read()
    # convert to grayscale
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # create a binary thresholded image
    _, binary = cv2.threshold(gray, 255 // 2, 255, cv2.THRESH_BINARY_INV)
    # find the contours from the thresholded image
    contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    # draw all contours
    image = cv2.drawContours(frame, contours, -1, (0, 255, 0), 2)
    # show the images
    cv2.imshow("gray", gray)
    cv2.imshow("image", image)
    cv2.imshow("binary", binary)
    if cv2.waitKey(1) == ord("q"):
        break

cap.release()
cv2.destroyAllWindows()


🕒 Black Friday Limited-Time Offer!
EBook Image

Black Friday Week Special! Get our eBook Bundle at 52% off. Limited time only!

$102.0 $49.0