-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)
5
  • Presumably what you have is RGB image, hence the 3 colour channels (that's what the 3rd dimension in that array represents). Commented Feb 10, 2020 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 Commented Feb 10, 2020 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? Commented Feb 10, 2020 at 14:27
  • 3
    Does this answer your question? How to convert a PIL Image into a numpy array? Commented Feb 10, 2020 at 15:21
  • yes, it is. thanks. Commented Feb 12, 2020 at 8:17

1 Answer 1

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')
Sign up to request clarification or add additional context in comments.

3 Comments

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?
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.
It's a duplicated question. so pls visit: stackoverflow.com/questions/384759/… to get the answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.