DEV Community

Cover image for Colors channels and Python
petercour
petercour

Posted on

2 1

Colors channels and Python

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)
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

Related links:

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay