Work with color and image arrays
Mix colors from red, green and blue, convert them to gray, and mind the channel order.
- Describe a color pixel as red, green and blue values
- Convert color to grayscale the way the eye perceives brightness
- Avoid the RGB vs BGR channel-order trap
Screens make every color by mixing red, green and blue light. A color pixel therefore stores three numbers - [R, G, B], each usually 0–255. [255, 0, 0] is pure red, [255, 255, 255] is white (all lights on), and [0, 0, 0] is black (all off). A color image has shape height × width × 3.
pixel = [255, 80, 0]
red, green, blue = pixel
print(red, green, blue)255 80 0
Try it
Up to 15 XPColor mixer
Mix each target color with the three sliders, then check your mix. Mixing light is not like mixing paint: what do red and green make together? Keep an eye on the grayscale value too - is bright yellow light or dark in gray?
- As a pixel
- [128, 128, 128]
- Hex code
- #808080
- Grayscale
- 128
From color to gray
Many vision steps work on grayscale, which is a third of the data. A plain average of R, G and B looks wrong, because our eyes are most sensitive to green and least to blue. The standard formula weights them: gray = 0.299 R + 0.587 G + 0.114 B.
red, green, blue = 255, 80, 0
print(round(0.299 * red + 0.587 * green + 0.114 * blue))123
Key takeaways
A color pixel is
[R, G, B]; a color image is height × width × 3.Grayscale weights green most and blue least:
0.299 R + 0.587 G + 0.114 B.Check whether a library uses RGB or BGR before you trust the colors.
Lesson quiz
7 questions · pass with 5 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: apply computer vision with Python
Use small pixel arrays to explore vision concepts, run your code against sample images, and connect each result to the larger computer vision idea.
Read one color channel
Read a JSON RGB pixel such as [255, 80, 0]. Print only its green channel (the second value).
- Orange pixel
- Teal pixel
Python runs in a sandboxed browser worker with a 60 second time limit. Its runtime loads from the Pyodide CDN; your code stays in this browser.
Convert an image to grayscale
Read a JSON color image: a list of rows, each a list of [R, G, B] pixels. Print the grayscale image as a list of rows, using round(0.299 * R + 0.587 * G + 0.114 * B) for each pixel.
- Primary colors and white
- One gray pixel
Python runs in a sandboxed browser worker with a 60 second time limit. Its runtime loads from the Pyodide CDN; your code stays in this browser.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…