Movatterモバイル変換


[0]ホーム

URL:


How to Detect Contours in Images using OpenCV in Python

Learning how to detect contours in images for image segmentation, shape analysis and object detection and recognition using OpenCV in Python.
  · 4 min read · Updated may 2024 ·Machine Learning ·Computer Vision

Kickstart your coding journey with ourPython Code Assistant. An AI-powered assistant that's always ready to help. Don't miss out!

A contour is a closed curve joining all the continuous points having some color or intensity, they represent the shapes of objects found in an image. Contour detection is a useful technique for shape analysis andobject detection and recognition.

In a previous tutorial, we have discussededge detection using the Canny algorithm and we've seen how to implement it inOpenCV, you may ask, what's the difference between edge detection and contour detection?

Well, when we perform edge detection, we find the points where the intensity of colors changes significantly, and then we simply turn those pixels on. However, contours are abstract collections of points and segments corresponding to the shapes of the objects in the image. As a result, we can manipulate contours in our programs such as counting the number of contours, using them to categorize the shapes of objects, cropping objects from an image (image segmentation), and much more.

Contour detection is not the only algorithm for image segmentation though, there are a lot of others, such as thecurrent state-of-the-art semantic segmentation using transformers,hough transform, andK-Means segmentation.

For better accuracy, here is the whole pipeline that we gonna follow to successfully detect contours in an image:

  • Convert the image to a binary image, it is a common practice for the input image to be a binary image (which should be a result of a thresholded image oredge detection).
  • Finding the contours usingfindContours()OpenCV function.
  • Draw these contours and show the image.

Related:How to Apply HOG Feature Extraction in Python.

Alright, let's get started. First, let's install the dependencies for this tutorial:

pip3 install matplotlib opencv-python

Importing the necessary modules:

import cv2import matplotlib.pyplot as plt

We gonna usethis image for this tutorial:

Thumbs up and down

Let's load it:

# read the imageimage = cv2.imread("thumbs_up_down.jpg")

Converting it toRGB and then grayscale:

# convert to RGBimage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)# convert to grayscalegray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

As mentioned earlier in this tutorial, we gonna need to create a binary image, which means each pixel of the image is either black or white. This is a necessity inOpenCV, finding contours is like finding a white object from a black background, objects to be found should be white and the background should be black.

# create a binary thresholded image_, binary = cv2.threshold(gray, 225, 255, cv2.THRESH_BINARY_INV)# show itplt.imshow(binary, cmap="gray")plt.show()

The above code creates the binary image by disabling (setting to0) pixels that have a value of less than225 and turning on (setting to255) the pixels that has a value of more than225, here is the output image:

Binary threshold image for contour detection

RELATEDMastering YOLO: Build an Automatic Number Plate Recognition System with OpenCV in Python.

Now, this is easy forOpenCV to detect contours:

# find the contours from the thresholded imagecontours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)# draw all contoursimage = cv2.drawContours(image, contours, -1, (0, 255, 0), 2)

The above code finds contours within the binary image and draws them with a thick green line to the image, let's show it:

# show the image with the drawn contoursplt.imshow(image)plt.show()

Output image:

Contours detected OpenCV PythonTo achieve good results on different and real-world images, you need to tune your threshold value or perform edge detection. For instance, for a pancakes image, I've decreased the threshold to127, here is the result:

Detected contours of pancake imageAlright, this is it for this tutorial, if you want to test this on your live camera, head tothis link.

RELATEDHow to Detect Shapes in Images using OpenCV in Python

You can always check theOpenCV's official documentation for more information.

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

Happy Coding ♥

Want to code smarter? OurPython Code Assistant is waiting to help you. Try it now!

View Full Code Transform My Code
Sharing is caring!



Read Also


How to Perform Edge Detection in Python using OpenCV
How to Detect Shapes in Images in Python using OpenCV
Image Transformations using OpenCV in Python

Comment panel

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





    Mastering YOLO - Topic - Top


    Join 50,000+ Python Programmers & Enthusiasts like you!



    Tags


    New Tutorials

    Popular Tutorials


    Mastering YOLO - Topic - Bottom

    CodingFleet - Topic - Bottom






    Claim your Free YOLO EBook

    Download a Completely Free EBook about YOLO Object Detection

    Build a custom object detector with YOLO from scratch using OpenCV in Python following this free EBook!



    [8]ページ先頭

    ©2009-2025 Movatter.jp