Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Hue
3.
Saturation
4.
Value
5.
Filtering Colors
5.1.
Reason For Using Bitwise Operations Between Images
6.
Implementation
7.
Frequently Asked Questions
8.
Key Takeaways
Last Updated: Mar 27, 2024

Color Filtering

Author Mayank Goyal
0 upvote

Introduction

Color filtering is widely used in OpenCV to identify specific objects/regions with a particular color. The most commonly used is BGR color space. BGR is an additive color space because the three color shades sum up giving different colors to the image. If we want to identify a region of a specific color, specify the threshold values and create a mask to separate the other colors.

In this OpenCV with Python tutorial, we will cover how to create a filter, revisit the Bitwise operations, filter for a specific color, and attempt to show it. Alternatively, you could also filter out a particular color and replace it with a scene.

For color filtering, all we need is the threshold values,i.e., the value of the lower and upper bound range of colors in one of the color spaces. To filter like this, you have a few options. Generally, we will probably convert our colors to HSV, which is Hue Saturation Value. For example, this can help you pinpoint a more specific color based on hue and saturation ranges, with a value variance. We can produce filters based on BGR values, but this would be a bit more difficult. After we specify the range of color to be filtered, we need to create a mask accordingly, and by using it, a particular region of the image can be separated.

Also See, Image Sampling 

Hue

The degree to which a stimulus is described as similar or different from the stimuli described as yellow, green, red, orange, blue, purple, which in particular theories of color vision are called unique hues.

Yeah, I know this might sound agonizing over understanding but let me break this down. In this context, the word "stimulus" means the light that reaches our eyes when we see an object. Now let me rephrase the definition. All the colors that we see can be interpreted as a variant of the colors: yellow, green, red, orange, blue, purple, which are known as unique hues in particular theories of color vision. To sum up, hue is the purest form of the primary and secondary colors. Generally, the hue is measured in 360 degrees of a color circle, but in OpenCV, the hue scale is only 180 degrees.

Saturation

Saturation gives the purity of a color. A pure color has no gray mixed in it: the greater the amount of gray mixed in color, the lesser is the saturation. The saturation value is measured from 0 to 100%, but in OpenCV, the scale for saturation is from 0 to 255.

Value

Value is the measure of the brightness of a color. When the brightness value is maximum, the color turns white, and when the brightness value is minimum, the color is black. Value is measured from 0 to 100%, but in OpenCV, the value scale is 0 to 255.

Also read, Sampling and Quantization

Filtering Colors

To filter a color using OpenCV, we have to specify the hue range of the color. We need to filter and then create a mask for the color. Lastly, we perform a bitwise AND operation between the original image arrays using the mask to get the filtered color as a result.

Reason For Using Bitwise Operations Between Images

The bitwise operations are performed on an image when we need to extract only the required parts of the image. Consider a situation where we need to remove an irregular-shaped object from a photo and paste it on another image. That'sThat's precisely when we use bitwise operations on the image to separate the foreground from the background. OpenCV has inbuilt methods to perform and, or and not operations. They are bitwise_and, bitwise_or, and bitwise_not.

Implementation

Firstly We import all the required modules.

import cv2
import numpy as np
import matplotlib. pyplot as plt
You can also try this code with Online Python Compiler
Run Code

Reading(Taking input) the image

img = cv2.imread("example.jpeg")
plt.imshow(img)
You can also try this code with Online Python Compiler
Run Code

print(img.shape)
You can also try this code with Online Python Compiler
Run Code

(464, 696, 3)

We can print the image using the matplotlib library or using imshow function of opencv. We should press zero for terminating the process.

cv2.imshow('Image',img)  # Showing The Sample Test Image
cv2.waitKey(0)
cv2.destroyWindow('Image')
You can also try this code with Online Python Compiler
Run Code

Converting BGR to HSV color space.

hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
You can also try this code with Online Python Compiler
Run Code

Threshold of Blue in HSV color space.

lower = np.array([60, 35, 140])
upper = np.array([180, 255, 255])
mask = cv2.inRange(hsv, lower, upper)
You can also try this code with Online Python Compiler
Run Code

The black region in the masked area has the value of zero, so when we multiply the mask with the original image, it removes all non-blue regions

result = cv2.bitwise_and(img, img, mask = mask)
You can also try this code with Online Python Compiler
Run Code
fig= plt.figure(figsize=(30, 30))
fig.add_subplot(1, 3, 1)
You can also try this code with Online Python Compiler
Run Code
# showing image
plt.imshow(img)
plt.axis('off')
plt.title("First")
You can also try this code with Online Python Compiler
Run Code
# Adds a subplot at the 2nd position
fig.add_subplot(1, 3, 2)
  
# showing image
plt.imshow(mask)
plt.axis('off')
plt.title("Second")
fig.add_subplot(1, 3, 3)
You can also try this code with Online Python Compiler
Run Code
# showing image
plt.imshow(result)
plt.axis('off')
plt.title("Third")
You can also try this code with Online Python Compiler
Run Code

We can also use the below code for displaying images. Make sure to enter zero to terminate the process.

cv2.imshow('frame', frame)
cv2.imshow('mask', mask)
cv2.imshow('result', result)
You can also try this code with Online Python Compiler
Run Code

 

Read about Bitwise Operators in C here.

Frequently Asked Questions

1. Why do we convert RGB to HSV?

Ans. We use HSV colorspace for color detection/thresholding over RGB/BGR because HSV is more robust towards external lighting changes. This means that minor changes in exterior lighting (such as pale shadows, etc. Hue values vary relatively lesser than RGB values.

2. What is the difference between HSV and RGB?

Ans. RGB is a projective coloring system. RGB coloring system is based on light and the colors of lights. HSV measures the hue angle of color, saturation (or amount of grayness), and brightness (or value, in respect of the chosen word).

3. How do you convert RGB to HSV color?

Ans. Convert RGB image to HSV Image. HSV = rgb2hsv(RGB); Process the HSV image. This example increases the image saturation by multiplying the S channel by a scale factor.

4. What are color filters used for?

Ans. Colored filters are used primarily for black and white photography to control tone rather than color. Color filters work by filtering out specific wavelengths of light while letting other wavelengths pass through. By doing so, they change the contrast between different areas.

Key Takeaways

Let us brief the article.

Firstly, we learned about HSV and why we should use HSV for color filtering. Further, we saw why we need bit manipulation for color filtering. Lastly, we saw the implementation of color filtering. 

I hope you all like this article.

Happy Learning Ninjas!

Live masterclass