1

(using python 3.9.1) I'm trying to convert a PNG to a list of RGB values, but I am not sure how to. I've searched online and found that I can convert an image to an array using pillow and numpy. The thing is, I have the data, but I have no idea how to use it.

I was wondering if someone can help me or point me in the right direction.

EDIT:

I was asked by Mr.T to provide an example of the problem i was having. So here it is:

Here is some example code, it opens an image and converts it to a numpy array

Example Image

from PIL import Image
import numpy

image = Image.open('./Untitled.png')

narray = numpy.array(image)
for i in range(len(narray)):
        print(numpy.array_str(narray[i]) + '\n')

The output it gives is:

[0 1 1 1 1 1 1 1 1 0]

[0 1 1 2 1 1 2 1 1 0]

[0 1 1 2 1 1 2 1 1 0]

[0 1 1 2 1 1 2 1 1 0]

[0 1 1 1 1 1 1 1 1 0]

[0 1 2 1 1 1 1 2 1 0]

instead of the RGB values like I thought it would:

[255,233,0,255,233,0,255,233,0,255,233,0,255,233,0,255,233,0,255,233,0,255,233,0,255,233,0,255,233,0,
255,233,0,255,178,0 ...
Sect0r
  • 21
  • 6
  • @Mr.T i found a way to convert it to an array, but i dont know how to use it, i was looking for a way to have an array that looks something like: [103, 10, 42, 12, 42, 83, 100, 255, 430]. – Sect0r Jan 24 '21 at 13:09
  • 1
    Obviously, the structure would be different, given that an image has the size n x m, and then you have the three color channels, R, G, and B (or four, if an alpha channel is included). It also depends on the normalization if you get arrays normalized as int between 0 and 255 or as float between 0 and1. I suggest you edit your question, post a specific example (small sample image), your code to convert it, and why the result did not meet your expectations. – Mr. T Jan 24 '21 at 13:14
  • @Mr.T Thank you! I'm doing that now. – Sect0r Jan 24 '21 at 14:59
  • @Mr.T There, finished. – Sect0r Jan 24 '21 at 15:15
  • 1
    Being so small, and having so few colours, your image is a *"palette"* image. The answer is here... https://stackoverflow.com/a/52307690/2836621 – Mark Setchell Jan 24 '21 at 16:51
  • 1
    @MarkSetchell Thank you so much! It works now. I figured out how to use the resulting numpy array. :) – Sect0r Jan 24 '21 at 17:54
  • 1
    Cool - good luck with your project. – Mark Setchell Jan 24 '21 at 18:03
  • Does this answer your question? [What is the difference between images in 'P' and 'L' mode in PIL?](https://stackoverflow.com/questions/52307290/what-is-the-difference-between-images-in-p-and-l-mode-in-pil) Just for close voting, kindly self close if Mark's linked Q&A answered your question. – HansHirse Jan 28 '21 at 10:19
  • how do i close it? @HansHirse – Sect0r Feb 02 '21 at 14:05

0 Answers0