Edge Detection with 15 lines of python code using OpenCV and Webcam

Source: Deep Learning on Medium

Edge Detection with 15 lines of python code using OpenCV and Webcam

Welcome to the exciting world of Computer vision where there are no boundaries when it comes to exploring.

In this article we will discuss on how to detect edges in a video feed. For the learning purposes, we will use the webcam for a live video feed which can be surely be replaced by an image or any video file.

Let’s get this working.

Pre-requisites:

  1. OpenCV

I am using Python version 3.7 to write our script for edge detection. Let us discuss the steps to accomplish the task.

Steps:

  1. Turn on webcam and read the video feed
  2. Display the read video feed on a display window
  3. Detect edges and display it on the display window

And those three magical words, “Let us code”.

import cv2
cap = cv2.VideoCapture(0)
while True:
ret, img = cap.read()

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
canny = cv2.Canny(blur, 10, 70)
ret, mask = cv2.threshold(canny, 70, 255, cv2.THRESH_BINARY)
cv2.imshow('Video feed', mask)

if cv2.waitKey(1) == 13:
break
cap.release()
cv2.destroyAllWindows()
cv2.destroyAllWindows()