How to detect specific colors from an image using OpenCV?

This recipe helps you detect specific colors from an image using OpenCV.

Recipe Objective: How to detect specific colors from an image using OpenCV?

This recipe will discuss color detection from image in Python OpenCV.

Deep Learning Project for Text Detection in Images Using Python

Steps For Python OpenCV Detect Color

The following steps will show you how to detect red color with OpenCV Python.

Step 1: Import Library and read the image

The image that we are using here is

OpenCV_Logo.jpg

 

import cv2
import numpy as np
image = cv2.imread('OpenCV_Logo.jpg')

Step 2: Define boundaries for the colors

In this example, let us detect the red color from the above image. We need to define a lower limit and an upper limit of BGR values of red colors for that purpose.

lower_red = np.array([0, 0, 200], dtype = "uint8")
upper_red= np.array([0, 0, 255], dtype = "uint8")

As we can see from the above lines of code, any color whose R > 200 and R < 255 is considered red.

Step 3: Python OpenCV- Find Color in Image Using cv2.inRange Function

The cv2.inRange() is the most commonly used function to detect colors in an image. This function expects three parameters as given below

  • src: Image from which the colors are to be detected

  • lowerb: Lower boundary of the color

  • upperb: Upper boundary of the color

The cv2.inRange() function returns a white binary image where the colors are detected and 0 otherwise.

mask = cv2.inRange(image, lower_red, upper_red)

Step 4: Perform Bitwise AND with the input image.

We perform bitwise and of the input image and mask the output with the image present in the mask variable to highlight the area where the color is detected in the input image. This can be achieved using the cv2.bitwise_and() function

detected_output = cv2.bitwise_and(image, image, mask = mask)
cv2.imshow("red color detection", detected_output)
cv2.waitKey(0)

Output:

red_detect.jpg




Download Materials

What Users are saying..

profile image

Anand Kumpatla

Sr Data Scientist @ Doubleslash Software Solutions Pvt Ltd
linkedin profile url

ProjectPro is a unique platform and helps many people in the industry to solve real-life problems with a step-by-step walkthrough of projects. A platform with some fantastic resources to gain... Read More

Relevant Projects

End-to-End Snowflake Healthcare Analytics Project on AWS-1
In this Snowflake Healthcare Analytics Project, you will leverage Snowflake on AWS to predict patient length of stay (LOS) in hospitals. The prediction of LOS can help in efficient resource allocation, lower the risk of staff/visitor infections, and improve overall hospital functioning.

Word2Vec and FastText Word Embedding with Gensim in Python
In this NLP Project, you will learn how to use the popular topic modelling library Gensim for implementing two state-of-the-art word embedding methods Word2Vec and FastText models.

House Price Prediction Project using Machine Learning in Python
Use the Zillow Zestimate Dataset to build a machine learning model for house price prediction.

Loan Eligibility Prediction using Gradient Boosting Classifier
This data science in python project predicts if a loan should be given to an applicant or not. We predict if the customer is eligible for loan based on several factors like credit score and past history.

Build a Credit Default Risk Prediction Model with LightGBM
In this Machine Learning Project, you will build a classification model for default prediction with LightGBM.

Deploying Machine Learning Models with Flask for Beginners
In this MLOps on GCP project you will learn to deploy a sales forecasting ML Model using Flask.

Build Portfolio Optimization Machine Learning Models in R
Machine Learning Project for Financial Risk Modelling and Portfolio Optimization with R- Build a machine learning model in R to develop a strategy for building a portfolio for maximized returns.

Mastering A/B Testing: A Practical Guide for Production
In this A/B Testing for Machine Learning Project, you will gain hands-on experience in conducting A/B tests, analyzing statistical significance, and understanding the challenges of building a solution for A/B testing in a production environment.

Linear Regression Model Project in Python for Beginners Part 2
Machine Learning Linear Regression Project for Beginners in Python to Build a Multiple Linear Regression Model on Soccer Player Dataset.

AWS MLOps Project for ARCH and GARCH Time Series Models
Build and deploy ARCH and GARCH time series forecasting models in Python on AWS .