0

I am trying to run this simple code to have it output the image matrix of an image? I want it to output an image matrix with row and columns so that I can find the first rows/columns with nonzero pixel values so that I can crop... but right now my main problem is getting the matrix.

PLS&THANKYOU!

I keep getting this error:

Traceback (most recent call last): File "pillow_images.py", line 12, in matrix = np.array(im.getdata()).reshape(im.size) ValueError: cannot reshape array of size 147840 into shape (231,160)

import PIL #imports PIL library needed for pillow
from PIL import Image # imports Image class from pillow
import numpy as np

im = Image.open("whitewave.png") #loads in the image 

print(im.format, im.size, im.mode) #(PNG, (width,height), Type of image:RGB)

matrix = np.array(im.getdata()).reshape(im.size)
print(matrix)```
  • 1
    The error is a good hint on what the problem is. The size of the array is four times the size of the image (147840 = 231 * 160 * 4). There is also 3 color channels and 1 alpha channel for PNG files. – kkawabat Aug 22 '19 at 22:06
  • it seems your image in `RGBA` and you have to `reshape(231,160,4)` – furas Aug 22 '19 at 22:07
  • use `matrix = np.array(im)` and you get correct array without reshaping. – furas Aug 22 '19 at 22:09
  • Thank you, do you know if there is there a way to get this in form of a matrix like MATLAB? – Teresa Ramirez Aug 22 '19 at 22:11

1 Answers1

1

Use

matrix = np.array(im)

to get matrix with correct shape.


furas
  • 134,197
  • 12
  • 106
  • 148
  • Thank you, do you know if there is there a way to get this in form of a matrix like MATLAB? – Teresa Ramirez Aug 22 '19 at 22:15
  • after googling: [Matrix from Python to MATLAB](https://stackoverflow.com/questions/1095265/matrix-from-python-to-matlab) – furas Aug 22 '19 at 22:29