Home > Enterprise >  How to convert an image into an array of it's raw pixel data?
How to convert an image into an array of it's raw pixel data?

Time:11-30

I wanted to create a small pixel-by-pixel image manipulation program, so I wanted to ask if there is something (preferably in Python) that can convert a .png image into RGB raw pixel data.

For example, a 3px*3px image like this will output:

[(255, 0, 0), (0, 0, 0), (255, 0, 0), (0, 255, 0), (0, 255, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255), (0, 0, 255)]

The pixel array will be arranged left to right, up to down (regular Western reading style).

Additional Stuff (If you can do it, it would also be great)

If the array on top adds additional complications, it would also be ok to print out a list of HSV pixel data instead.

Any help would be greatly appreciated!

CodePudding user response:

You can do it with Pillow (PIL) library:

from PIL import Image
import numpy as np

path = 'image.png'
image = Image.open(path)
image = np.asarray(image)

Notice that returned arrays have a length of 4 because the ".png" format supports an additional Alpha channel (transparency), so it's RGBA. To get rid of this extra channel, you need to convert an image to RGB format first.

from PIL import Image
import numpy as np

path = 'image.png'
image = Image.open(path).convert('RGB')
image = np.asarray(image)

CodePudding user response:

Read your image with opencv python.
Few things to notice:

  1. PIL a little bit more user friendly, but opencv will serve you really good if you do heavy image processing stuff
  2. If you are familar with numpy, I would suggest using opencv because behind the scence, opencv image is actually a numpy array
"""
pip install opencv-python
"""
import cv2

im = cv2.imread("test.png")
# Use this to if you read png image
im = cv2.cvtColor(im,cv2.COLOR_BGRA2RGB)
# Use this to if you read jpg image
# im = cv2.cvtColor(im,cv2.COLOR_BGR2RGB)
print(im[0,0])
  • Related