-1

When I do np.asarray(my_img) or array(my_img).shape it returns (2412L, 3600L, 3L) on a jpg image,but I just want a 2D (2412L, 3600L) array, so how to convert it correctly? Thanks in advance.

my_image = "AI.jpg"

from matplotlib.pyplot import imread
from PIL import Image

fname = "images/" + my_image
image = Image.open(fname) 
print(image.size)    # output: (3600, 2412)
print(np.asarray(image).shape) # output: (2412L, 3600L, 3L)
print(np.array(image).shape) # output: (2412L, 3600L, 3L)
Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
  • Presumably what you have is RGB image, hence the 3 colour channels (that's what the 3rd dimension in that array represents). – Dan Mašek Feb 10 '20 at 14:05
  • `image.size` shows only `(x,y)` but numpy's `shape` shows `(x,y,channels)` - so it is correct result. `shape` can show `(x,y)` only if you have single value per pixel - it means `greyscale` – furas Feb 10 '20 at 14:08
  • but I know "my_image = scipy.misc.imresize(image, size=(num_px,num_px)).reshape((1, num_px*num_px*3)).T“ can convert it to 2D ( but imresize() deprecated), so how can i do that? – harrison dong Feb 10 '20 at 14:27
  • 3
    Does this answer your question? [How to convert a PIL Image into a numpy array?](https://stackoverflow.com/questions/384759/how-to-convert-a-pil-image-into-a-numpy-array) – Alperen Kantarcı Feb 10 '20 at 15:21
  • yes, it is. thanks. – harrison dong Feb 12 '20 at 08:17

1 Answers1

1

If your image dimensions have a 3 for the final axis, that normally means you have a 3-channel RGB image.

If you want a single channel image, you will lose the RGB colour and just have a greyscale image. You can do that like this:

grey = Image.open(fname).convert('L')
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • so if use deprecated imresize() (my_image = scipy.misc.imresize(image, size=(num_px,num_px)).reshape((1, num_px*num_px*3)).T), it also lose the RGB color and have greyscale image? – harrison dong Feb 10 '20 at 14:30
  • 1
    I don't understand what the connection is to `imresize()`. Your question is about going from 3 channels to 1 channel. That is normally a greyscale conversion, or the extraction or calculation of a new channel. `imresize()` is for changing the height and/or the width of the image. – Mark Setchell Feb 10 '20 at 14:33
  • It's a duplicated question. so pls visit: https://stackoverflow.com/questions/384759/how-do-i-convert-a-pil-image-into-a-numpy-array to get the answer. – harrison dong Sep 30 '22 at 03:06