Find and Draw Contours – OpenCV 3.4 with python 3 Tutorial 19

[Locker] The locker [id=2113] doesn't exist or the default lockers were deleted.

We’re going to see in this tutorial how to find and draw the contours.
Contours are simply the boundaries of an object.

We first import the libraries and we load the Camera.

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

We start the while loop to work with a video, so we loop trough frame after frame.
On line 7 we blur the frame to remove the noise for the contorus detection, otherwise we would many false contours, or not so clean boundaries.
On line 8 we convert the frame from BGR to HSV format. We need to do this so that later we can create a mask.

while True:
    _, frame = cap.read()
    blurred_frame = cv2.GaussianBlur(frame, (5, 5), 0)
    hsv = cv2.cvtColor(blurred_frame, cv2.COLOR_BGR2HSV)

We define the HSV ranges lower and upper of a specific color, in our case we choosed the blue.

    lower_blue = np.array([38, 86, 0])
    upper_blue = np.array([121, 255, 255])
    mask = cv2.inRange(hsv, lower_blue, upper_blue)

We can at this point find the contours using the opencv built in function findContours.
The value contours contains an array with the coordinates of all the contours of the object.

    _, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

We loop trough the countours and we draw each single one.

    for contour in contours:
        cv2.drawContours(frame, contour, -1, (0, 255, 0), 3)

Finally we display everything.

    cv2.imshow("Frame", frame)
    cv2.imshow("Mask", mask)
    key = cv2.waitKey(1)
    if key == 27:
        break
        
cap.release()
cv2.destroyAllWindows()

[Locker] The locker [id=2113] doesn't exist or the default lockers were deleted.
Blueprint

Learn to build Computer Vision Software easily and efficiently.

This is a FREE Workshop where I'm going to break down the 4 steps that are necessary to build software to detect and track any object.

Sign UP for FREE