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

Contour Detection using Python OpenCV

In this article, you will learn contour detection of an image using Python OpenCV.

Contours are defined as the lines joining all continuous points along the boundary of an image that have the same intensity and color. Contours are basically used in shape analysis, finding the size of the object of interest, and object detection and recognition.





Required Modules

  • OpenCV (cv2)
  • Matplotlib

We hope the above modules are installed in your system. If you do not have it installed, you can install it using the pip tool-

pip install opencv-contrib-python matplotlib




Contour Detection Code Explanation

Here, we have explained the contour detection code line by line.

First, we will load the image using OpenCV cv2.imread() function -

image = cv2.imread("house.jpg")

Next, we will convert the imported image to grayscale. The cv2.cvtColor() method is used to convert an image from one color-space to another. It specifies the type of conversion. We need to convert to grayscale, so we will use cv2.COLOR_BGR2GRAY in the second parameter.

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

It is necessary to create a binary image before contour detection. A binary image has each pixel either in black or white. In OpenCV, finding the contour in this binary image is like finding a white object in a black background. It gives us better accuracy.





So, we will create a binary threshold image. It disables the pixels having a value of less than 255 and enables the pixels having a value of more than 255.

_, binary = cv2.threshold(gray, 225, 255, cv2.THRESH_BINARY_INV)

Next, we will find the contour from the generated binary threshold image. OpenCV provides the cv2.findContours() function to create contours. It accepts three parameters, input image, hierarchy type, and the contour approximation type. The cv2.RETR_TREE gets the entire hierarchy of contours in the image and establishes a relationship between them. The cv2.CHAIN_APPROX_SIMPLE removes all redundant points and compresses the contour, thereby saving memory.

contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

The cv2.drawContours() method is used to draw all contours.

image = cv2.drawContours(image, contours, -1, (0, 255, 0), 2)




Complete Code: OpenCV Contour Detection

import cv2
from matplotlib import pyplot as plt

# loading the image
image = cv2.imread("house.jpg")

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

# create a binary thresholded image
_, binary = cv2.threshold(gray, 225, 255, cv2.THRESH_BINARY_INV)

# contours from the thresholded image
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# draw all contours
image = cv2.drawContours(image, contours, -1, (255, 0, 0), 4)

plt.subplot(121),plt.imshow(binary, cmap="gray")
plt.subplot(122),plt.imshow(image)
plt.show()

Output -

OpenCV Contour Detection



Related Articles

Capture a video in Python OpenCV and save
OpenCV Logical Operators
Arithmetic Operations on Images using Python OpenCV
OpenCV color detection
Face Recognition OpenCV Source Code
Canny Edge Detector OpenCV Python
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
Draw different shapes on image using Python OpenCV
How to convert MySQL query result to JSON in Python
How to display data from MongoDB in HTML table using Python




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
-----------------
PHP code to send email using SMTP
-----------------
Hypertext Transfer Protocol Overview
-----------------
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
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Fibonacci Series Program in PHP
-----------------
Simple pagination in PHP with MySQL
-----------------
How to generate QR Code in PHP
-----------------
PHP MYSQL Advanced Search Feature
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
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
-----------------
PHP User Authentication by IP Address
-----------------
Simple PHP File Cache
-----------------
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
-----------------
CSS Simple Menu Navigation Bar
-----------------
Date Timestamp Formats in PHP
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
Convert MySQL to JSON using PHP
-----------------
PHP Programming Error Types
-----------------
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
-----------------
File Upload Validation in PHP
-----------------
How to display PDF file in web page from Database 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.