How to Filter Image Pixels using cv2 in Python

To filter image pixels means you can convert the image from color to grayscale or add an extra layer. To convert a color image to a grayscale image, you can use the “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)

To add a new transparency channel, divide the original image into three channels, 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 you must consider converting it into png for jpg.

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

That is it.

Leave a Comment

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