1

I'm trying to understand how image is stored as RGB value

I just realized image that has been read by cv2.imread() method is just bunch of numbers especially RGB number stored in numpy.ndarray for every pixel when I check with builtin function type()

import cv2
im = cv2.imread('./rgb.png', cv2.IMREAD_UNCHANGED)
print(type(im)) # Output: numpy.ndarray

But I still don't know what representation of each index in that array

To understand it, I want make 3col * 4row image manually with numpy.ndarray

I expect image where:

  • first column filled with red (255,0,0)
  • second column filled with green (0,255,0)
  • third column filled with blue (0,0,255)

for all rows!

Using numpy.ndarray declaration that stored in a variable for example im and successfully saved according what I expect

im = np.ndarray('What should I fill in here?')
cv2.imwrite('success.jpg',im)
1
  • Do print(im.shape). You should see something like (480,640,3), which tells you there are 480 rows of 640 columns, where each column is an RGB triple. Commented Apr 3, 2022 at 5:23

1 Answer 1

1

See if this helps. I create an empty numpy array, then I fill each quadrant with a solid color:

import numpy as np
from PIL import Image

im = np.zeros( (480,640,3), dtype=np.uint8 )

im[:240,:320,:] = (255,0,0)
im[:240,320:,:] = (0,255,0)
im[240:,:320,:] = (0,0,255)
im[240:,320:,:] = (255,255,255)
print(im.shape)

p = Image.fromarray(im)
p.save('x.jpg')

Output: enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.