etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

Canny Edge Detector OpenCV Python

In this article, you will learn how to detect the edges of an image using a canny edge detector (cv2.canny) in OpenCV Python.

The Canny Edge Detector(cv2.canny) uses a large number of algorithms to detect the edges of image. It solves the edge detection problem of an image processing. It was developed by John F. Canny in 1986. This is used in various computer vision systems. This process extracts structural information and reduces the amount of data to be processed.





There are several edge detector algorithms developed, such as Sobel, Scharr, and Laplacian filters. But, the Canny Edge Detector method is famous among them as it is a multi-stage algorithm that goes through each stage. It is a good and reliable detector. It catches as many edges shown in the image as possible with good accuracy.





cv2.canny()

Python OpenCV provides the cv2.canny() method to detect the edges of an image.

Syntax of cv2.canny()

cv2.canny(image, edges, threshold1, threshold2[, apertureSize[, L2gradient]])

image - single channel input image,
edges - output (edges), it has the same size and type as the image,
threshold1 - first threshold for the hysteresis procedure,
threshold2 - second threshold for the hysteresis procedure,
apertureSize - the size of Sobel kernel used for finding image gradients, the default value is 3.
L2gradient - the equation for finding gradient magnitude.





Canny Edge Detector Algorithm

The Canny Edge Detection uses multi-step algorithms to detect edges of an image. OpenCV puts all the following in a single function, cv2.Canny() -

  • Noise Reduction- The edges of an image are not properly detected if the image has noise. So the first step is to remove the noise from an image. This process can be done by Gaussian filter. It smooths the image and removes high frequency noise.
  • Gradient Computation- It computes the intensity gradient representation of an image.
  • Non-maximum Suppression- After applying the Gradient Computation, some of the edges of an image are thick while some are thin. The non-maximum suppression is used to overcome this issue. It removes 'false' responses to the edge detection and makes them uniform.
  • Hysteresis Thresholding- It takes two threshold values, minVal and maxVal. Any edges with an intensity gradient between these minVal and maxVal are sure to be classified edges and to be considered.




Required Modules

These are the modules that we have used in this article with the Canny Edge Detector module cv2.canny().

  • OpenCV (cv2)
  • NumPy
  • Matplotlib



Canny Edge Detection High Threshold Example

In the given code, we have read the image in OpenCV format and performed canny edge processing. This process is performed on the corresponding grayscale image.

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

# loading the image using imread built-in function
img = cv2.imread('cat.jpg',0)

# detect edges using canny edge detection
edges = cv2.Canny(img,100,200)

// display both original and canny edge detecting images
plt.subplot(121),plt.imshow(img,cmap = 'gray')
plt.title('Original Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(edges,cmap = 'gray')
plt.title('Edge Image'), plt.xticks([]), plt.yticks([])
plt.show()

The leftmost is the original image. The rightmost image has a high threshold (100,200). It did not detect the unnecessary info in the image.

Python OpenCV Canny edge detector



Canny Edge Detection Low Threshold Example

Now, let's check the output with a low threshold (50,60).

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

# loading the image using imread built-in function
img = cv2.imread('cat.jpg',0)

# detect edges using canny edge detection with given threshold
edges = cv2.Canny(img,50,70)

// display both original and canny edge detecting images
plt.subplot(121),plt.imshow(img,cmap = 'gray')
plt.title('Original Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(edges,cmap = 'gray')
plt.title('Edge Image'), plt.xticks([]), plt.yticks([])
plt.show()

Python OpenCV Canny edge detector





Automatic Canny Edge Detector Program

Here, we have defined the function auto_detect_canny(). It takes two arguments: source image and sigma value. The sigma is the percentage threshold. For computing the lower and upper threshold values, we will first compute the median of the single channel pixel intensities and then calculate the lower and upper thresholds.

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

def auto_detect_canny(image, sigma):
	# compute the median
	mi = np.median(image)

	# computer lower & upper thresholds 
	lower = int(max(0, (1.0 - sigma) * mi))
	upper = int(min(255, (1.0 + sigma) * mi))
	image_edged = cv2.Canny(image, lower, upper)

	return image_edged

img = cv2.imread('cat.jpg',0)
edges = auto_detect_canny(img, 0.33)

plt.subplot(121),plt.imshow(img,cmap = 'gray')
plt.title('Original Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(edges,cmap = 'gray')
plt.title('Edge Image'), plt.xticks([]), plt.yticks([])
plt.show()

The above code returns the following output -

Python OpenCV Canny auto edge detector



Related Articles

How to capture a video in Python OpenCV and save
Python OpenCV Overlaying or Blending Two Images
Contour Detection using Python OpenCV
Harris Corner Detection using Python OpenCV
Human Body Detection Program In Python OpenCV
Face Recognition OpenCV Source Code
OpenCV Logical Operators- Bitwise AND, OR, NOR, XOR
Python NumPy: Overview and Examples
Image processing using Python Pillow
Python OpenCV Histogram Equalization
Python OpenCV Histogram of Color Image
Python OpenCV Histogram of Grayscale Image
Python OpenCV Image Filtering
Python OpenCV ColorMap
Python OpenCV Gaussian Blur Filtering
Python OpenCV Overview and Examples




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP Create Word Document from HTML
-----------------
How to get data from XML file in PHP
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP code to send email using SMTP
-----------------
Characteristics of a Good Computer Program
-----------------
How to encrypt password in PHP
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
How to get current directory, filename and code line number in PHP
-----------------
How to add multiple custom markers on google map
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
Fibonacci Series Program in PHP
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Simple pagination in PHP with MySQL
-----------------
How to generate QR Code in PHP
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
PHP MYSQL Advanced Search Feature
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
PHP Server Side Form Validation
-----------------
jQuery File upload progress bar with file size validation
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
To check whether a year is a leap year or not in php
-----------------
Php file based authentication
-----------------
Simple File Upload Script in PHP
-----------------
Simple PHP File Cache
-----------------
PHP User Authentication by IP Address
-----------------
Calculate the distance between two locations using PHP
-----------------
PHP Secure User Registration with Login/logout
-----------------
Polling system using PHP, Ajax and MySql
-----------------
How to print specific part of a web page in javascript
-----------------
Detect Mobile Devices in PHP
-----------------
Simple Show Hide Menu Navigation
-----------------
Simple way to send SMTP mail using Node.js
-----------------
SQL Injection Prevention Techniques
-----------------
Get Visitor\'s location and TimeZone
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
Google Street View API Example
-----------------
PHP Sending HTML form data to an Email
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
CSS Simple Menu Navigation Bar
-----------------
Date Timestamp Formats in PHP
-----------------
PHP Programming Error Types
-----------------
Convert MySQL to JSON using PHP
-----------------
Set and Get Cookies in PHP
-----------------
How to add google map on your website and display address on click marker
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
PHP Getting Document of Remote Address
-----------------
How to display PDF file in web page from Database in PHP
-----------------
File Upload Validation in PHP
-----------------
PHP FTP Connection and File Handling
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial




General Knowledge

listen
listen
listen
listen
listen
listen
listen
listen
listen


Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2022. All Rights Reserved.