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.

## app.py

import numpy as np
import cv2

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

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

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.

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

To add a new channel in 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.

## app.py

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 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.

#python #python cv2 #opencv #cv2.cvtcolor

Python cv2: How to Filter Image Pixels using OpenCV
1.60 GEEK