How to Filter Image Pixels using cv2 in Python

Python cv2 - How to Filter Image Pixels using OpenCV

Python cv2.imread() function reads the image and 1 indicates reads in full color and then convert that image to gray scale using cv2.cvtColor() method.

How to filter images in Python

To filter image pixels means you can convert the image from color to grayscale or add an extra layer to the image. To convert a color image to a grayscale image, use cv2.cvtColor() method. We can then write the image to the disk using the cv2.imwrite() function.


import numpy as np
import cv2

img = cv2.imread('data.png', 1)

gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Python cv2: How to add a new channel in the image

To add a new channel of transparency, first, divide the original image into three channels and then use the cv2.merge() function and pass the fourth channel as the fourth parameter.


import numpy as np
import cv2

img = cv2.imread('data.png', 1)

b = img[:, :, 0]
g = img[:, :, 1]
r = img[:, :, 2]

rgba = cv2.merge((b, g, r, g))
cv2.imwrite('rgba.png', rgba)

In this code, if you look carefully at to merge() method, I have passed four arguments: b, g, r, g.

The fourth g is the fourth layer of the image. By adding the fourth layer, we have filtered the image. The original image is the following.

How to Filter Image Pixels using OpenCV

After adding a fourth layer, the image looks like the following.


Filter Image Pixels in cv2

In this rgba.png image, the gray part is a transparent part of the image. The jpg type of image does not support the layer; the png type supports the layered image. So, if you are reading a jpg image and adding an extra layer to that image, then write that image in a png file. 

If you are already reading png images, you will write in png, but for jpg, you have to consider converting it into png.

You can’t use an inbuilt Python interpreter to view this image because it also does not support layered images. So you have to use external software to view this image. For example, if you are using Mac, you can use preview inbuilt software to view this image.

That is it for filtering the image in Python using OpenCV.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.