DEV Community

loading...
Cover image for Colors channels and Python

Colors channels and Python

petercour
・1 min read

Computer screens are made up of color combinations (red, green, blue). If you have any color images, you can see the amount of red, green and blue for each colors.

This is all theoretical and all, but is that hard to do? No it's actually easy.

You need an image processing library. Most would say Pillow, Python image library. But OpenCV (cv2) is another good choice.

OpenCV is a computer vision module, so you can do a lot more besides the basic image processing.

Split the color channels:

First load an image (with OpenCV), then split into the red, green and blue color channels.

#!/usr/bin/python3
b, g, r = cv2.split(img)

So complete code:

#!/usr/bin/python3
import cv2
import numpy as np

img = cv2.imread("lena.png", cv2.IMREAD_UNCHANGED)

b, g, r = cv2.split(img)

cv2.imshow("B", b)
cv2.imshow("G", g)
cv2.imshow("R", r)

cv2.waitKey(0)
cv2.destroyAllWindows()

Related links:

Discussion (0)