You're seeing a 2D NumPy array with values like 0, 1, 2 because the image you're loading appears to be either:
- A grayscale image — where each pixel is represented by a single value (intensity),
- Or a palette-based image (mode 'P') — where the pixel values are indices into a color palette.
Let's break it down:
How Image.open(fn) Works in PIL
When you open an image using PIL:
python
from PIL import Image
image = Image.open(fn)
The image.mode determines how the pixel data is stored:
'L': Grayscale image, 8-bit pixels.
'RGB': Full-color image (red, green, blue channels).
'RGBA': RGB with alpha (transparency).
'P': Palette mode (pixel values are indices into a palette).
'1': Black and white (1-bit).
- Others exist too.
Why np.array(image) Can Be 2D with Small Integer Values
When you do:
python
import numpy as np
a = np.array(image)
The resulting array a depends on the image mode:
1. Grayscale Mode ('L')
a will be 2D, shape (height, width)
- Each element is from 0 to 255, representing brightness:
python
>>> image.mode
'L'
>>> a.shape
(512, 512)
>>> a[0, 0]
127
2. Palette Mode ('P')
a will again be 2D, shape (height, width)
- Each element is an index (e.g.,
0, 1, 2, ...) into a color palette
- To see the actual RGB colors, you'd need to convert it:
python
image = image.convert('RGB') # or 'RGBA' if alpha is needed
a = np.array(image) # now a 3D array: (height, width, 3)
How to Check and Convert
To figure out what's really going on:
python
print(image.mode) # Check the image mode
If it's 'P', you're seeing palette indices.
To get actual colors:
python
image_rgb = image.convert('RGB')
a_rgb = np.array(image_rgb)
print(a_rgb.shape) # (height, width, 3)
Conclusion
You’re getting a 2D array with values 0, 1, 2 because:
- The image is likely in Palette ('P') mode
- The values are indices into a color map, not RGB intensities
To get actual color information, convert it to 'RGB':
python
a = np.array(image.convert('RGB'))
Let me know if you'd like help visualizing the palette or converting to grayscale/RGB properly.