GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • The Python Code
  • Tutorials
  • Ethical Hacking
  • Machine Learning
  • General Python Tutorials
  • Web Scraping
  • Finance
  • Computer Vision
  • Python Standard Library
  • Application Programming Interfaces
  • Database
  • Game Development
  • Web Programming
  • Digital Forensics

This view

  • Original page
  • New address

GeezerVison is showing thepythoncode.com — How to Perform Edge Detection in Python using OpenCV - The Python Code

Unlock the secrets of your code with our AI-powered Code Explainer. Take a look!

Edge detection is an image processing technique for finding the boundaries of objects within images. It mainly works by detecting discontinuities in brightness. One of the most popular and widely used algorithms is the Canny edge detector.

Canny edge detector is an edge detection operator that uses a multi-stage algorithm to detect a wide range of edges in images.

The main stages are:

  1. Filtering out noise using the Gaussian blur algorithm.
  2. Finding the strength and direction of edges using Sobel Filters.
  3. Isolating the strongest edges and thinning them to one-pixel wide lines by applying non-maximum suppression.
  4. Using hysteresis to isolate the best edges.

Learn more here about the theory behind the Canny edge detector.

Read also: Image Transformations using OpenCV in Python.

Alright, let's implement it in Python using OpenCV, installing it:

$ pip install opencv-python matplotlib numpy

Open up a new Python file and follow along:

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

Now let's read the image when want to detect its edges:

# read the image
image = cv2.imread("little_flower.jpg")

I have an example image in my current directory, make sure you do too.

Before we pass the image to the Canny edge detector, we need to convert the image to grayscale:

# convert it to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

Let's see it:

# show the grayscale image
plt.imshow(gray, cmap="gray")
plt.show()

Image in Gray Scale

All we need to do now is to pass this image to cv2.Canny() function which finds edges in the input image and marks them in the output map edges using the Canny algorithm:

# perform the canny edge detector to detect image edges
edges = cv2.Canny(gray, threshold1=30, threshold2=100)

Learn also: Real-time Object Tracking with OpenCV and YOLOv8 in Python.

The smallest value between threshold1 and threshold2 is used for edge linking. The largest value is used to find initial segments of strong edges.

Let's see the resulting image:

Canny Edge Detection Resulting Image

Interesting, try to fine-tune the threshold values and see if you can make it better.

Mastering YOLO: Build an Automatic Number Plate Recognition System

Building a real-time automatic number plate recognition system using YOLO and OpenCV library in Python

Download EBook

If you want to use the live camera, here is the full code for that:

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

while True:
    _, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    edges = cv2.Canny(gray, 30, 100)
    cv2.imshow("edges", edges)
    cv2.imshow("gray", gray)
    if cv2.waitKey(1) == ord("q"):
        break

cap.release()
cv2.destroyAllWindows()

Alright, we are done!

The purpose of detecting edges is to capture important events and changes in the properties of the world. It is one of the fundamental steps in image processing, image pattern recognition, and computer vision techniques.

Learn also: How to Apply HOG Feature Extraction in Python.

Happy Learning ♥

Take the stress out of learning Python. Meet our Python Code Assistant – your new coding buddy. Give it a whirl!

View Full Code Fix My Code
Sharing is caring!

Read also

Face Detection using OpenCV in Python

Performing face detection using both Haar Cascades and Single Shot MultiBox Detector methods with OpenCV's dnn module in Python.

How to Detect Shapes in Images in Python using OpenCV

Detecting shapes, lines and circles in images using Hough Transform technique with OpenCV in Python. Hough transform is a popular feature extraction technique to detect any shape within an image.

How to Blur Faces in Images using OpenCV in Python

Blurring and anonymizing faces in images and videos after performing face detection using OpenCV library in Python.

Comments

    Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!




    Get our free Python guides

    Join 50,000+ Python programmers and enthusiasts like you!

    Topics
    Ethical Hacking Machine Learning General Python Tutorials Web Scraping Finance Computer Vision Python Standard Library Application Programming Interfaces Database Game Development Web Programming Digital Forensics Natural Language Processing Healthcare PDF File Handling Python for Multimedia GUI Programming Cryptography Packet Manipulation Using Scapy
    New tutorials View all
    • How AI Text Detection Works: The Technology Behind Modern AI Detectors
    • Beyond Guesswork: How Python Helps Identify AI-Generated Text
    • Discover the Possibilities of Python Programming
    • How to Track Your AI Visibility with Python
    • How to Automate Excel Reports in Python using Openpyxl
    Popular tutorials View all
    • How to Convert Speech to Text in Python
    • How to Read Emails in Python
    • How to Extract Tables from PDF in Python
    • How to Control your Mouse in Python
    • How to Make a Keylogger in Python
    Mastering YOLO - Topic - Bottom CodingFleet - Topic - Bottom
    You are visitor 01402503 — GeezerVison does not store the pages you look up.
    Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.