Detect Edges in Image Using openCV

Sunny Kumar
2 min readDec 1, 2022

--

Finding edges in an image is a famous problem in image processing world. Believe me it is only 10 lines of code. If your use case requires edges in an image to do additional algorithm feeding, here is a set of steps you can follow.

I will be using OpenCV python package to process the image. I am assuming you already have some basics knowledge of Python.

I strongly feel, pictures can communicate better than text, Below is the diagram which points out the steps involved.

canny edge

well, image is just an overview of the steps. Lets us get into details.

First load the required package. After this

import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt

Once the package is loaded, next step is to load the image and convert it to grayscale. Basically, the image you will be using in real time world, will b ein RGB or RGBA format, to process it has to be converted to gray channel in common language it is called as black and white image. Plot is used to visualize the image. Below is the original images used.

img = cv.imread('test2.jpg')
img = cv.cvtColor(img , 6)
plt.subplot(122),plt.imshow(img,cmap = 'gray')

once image is in gray channel, we will try to reduce the noise the image in image by using some blurr and then we will apply canny edge.

blur = cv.GaussianBlur(img,(7,7),0)
edges = cv.Canny(blur,60,120)
plt.subplot(122),plt.imshow(edges,cmap = 'gray')

Voila , it is done.

Threshold value in canny function, uses hysteresis process. it will require two values, lower threshold and upper threshold. For every scenario threshold will be different. Try experimenting with different threshold to get better result. For this image i have taken lower value as 60 and upper value as 120.

--

--

Sunny Kumar

Loves technology . Combining AI and AR to create meaningful solutions.