0

I tried using the PIL library to get a matrix consisting of arrays of pixels and RGB, however, I only get a one-dimensional array and I don’t understand how to form a matrix of them

img = Image.open("E:\\1f9114.png").convert('RGB')
obj = img.load()
width, height = img.size 
for j in range(height):        
    for i in range(width):             
        matrix1=[i,j,obj[i,j]]            
        print(matrix1)           
    print()

I know that the matrix can turn out huge, and the usual sheet does not cope .I hope somebody will help, as it is important for me.

1 Answers1

0

There are several issues with this code snippet:

  • matrix1 is always overridden. If you want to add pixels to an existing list, use list.append().
  • im.getdata() should be used to obtain a one-dimensional raw pixel list from the image.

Here is an example (adapted from here) to load pixels into a two-dimensional array that contains (r,g,b) tuples built using list comprehensions and slices.

pixels = list(img.getdata())
matrix1 = [pixels[i*width:(i+1)*width] for i in range(height)]
DurandA
  • 1,095
  • 1
  • 17
  • 35