Python Extracting Red Channels from Color Image

Python

OpenCV – Extract red channel from image

To extract the red channel of the image, we will first read the color image using cv2 and then extract the red channel 2D array from the image array.

In this tutorial, we will learn how to extract the red channel from a colored image, by applying array clipping on the multicolor array representation of the image.

 

Step-by-step procedure for extracting the red channel of a color image

Following is the sequence of steps to extract the red channel from an image.

  1. Read the image using cv2.imread().
  2. imread() returns a BGR (Blue-Green-Red) array. It is a three-dimensional array i.e. 2D pixel array for three color channels.
  3. Extract the red channel alone by slicing the array.

 

Example 1: Get the red channel from the color image.

In the following example we will do all the steps mentioned above to extract the Red Channel from the following image.

Input image

Python Program

import cv2
 
#read image
src = cv2.imread('D:/cv2-resize-image-original.png', cv2.IMREAD_UNCHANGED)
print(src.shape)

#extract red channel
red_channel = src[:,:,2]

#write red channel to greyscale image
cv2.imwrite('D:/cv2-red-channel.png',red_channel) 

We have recorded the red channel to an image. Since this is just a 2D array with values ​​from 0 to 255, the output looks like a grayscale image, but these are the red channel values.

Python OpenCV - Extract red channel from image

If you look at triangles, which one is bluer and greener is darker than the other.

To display the image in red, let’s make the blue and green components zero.

Python Program

import cv2
import numpy as np

#read image
src = cv2.imread('D:/cv2-resize-image-original.png', cv2.IMREAD_UNCHANGED)
print(src.shape)

# extract red channel
red_channel = src[:,:,2]

# create empty image with same shape as that of src image
red_img = np.zeros(src.shape)

#assign the red channel of src to empty image
red_img[:,:,2] = red_channel

#save image
cv2.imwrite('D:/cv2-red-channel.png',red_img) 
Python OpenCV - Extract red channel from image

 

Summary

In this guide of Python example we learned how to extract the red channel of an image with color.

Hope this helps!

Source link

Share: