Victor. L
Victor. L

Reputation: 145

PIL open tif image only one channel

There are two situations when I open tif image by PIL. First one is a normal one that can open an image as RGB and display by plt well. However, the second one as shown in the codes below:

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
img = Image.open('test1.tif')
a = np.array(img)
a.shape
# output: (2040,2040)

can only open as a shape of (2040,2040), the previous one with a shape of (2040,2040,3). When I convert the (2040,2040) one into RGB mode using img = img.convert('RGB') and showing it via plt only saw a blank square.

Please, somebody, tell me what is going wrong? Thanks in advance!

Original Image: enter image description here

And numpy array:

array([[7256, 6926, 7270, ..., 7368, 7457, 7555],
   [7174, 6945, 6878, ..., 7401, 7353, 7895],
   [7288, 7099, 7140, ..., 7359, 7524, 7587],
   ...,
   [6769, 6695, 6698, ..., 6599, 6788, 6898],
   [6780, 6683, 6857, ..., 6723, 6761, 6861],
   [6788, 6626, 6761, ..., 6738, 6751, 7054]], dtype=uint16)

After convert to RGB mode: enter image description here numpy array:

array([[[255, 255, 255],
        [255, 255, 255],
        [255, 255, 255],
        ...,
        [255, 255, 255],
        [255, 255, 255],
        [255, 255, 255]]], dtype=uint8)

Upvotes: 3

Views: 6214

Answers (1)

Zev
Zev

Reputation: 3491

The issue you are having is because the image is a 16-bit image (uint16) which is unsupported by the PIL image library. You can, as you suggested, simply convert it to a different image type. However, you can also just use imageio

The following code should work:

import imageio
import matplotlib.pyplot as plt
%matplotlib inline

img = imageio.imread('test1.tif')
plt.imshow(img)

See here for a discussion of related topics: https://github.com/imageio/imageio/issues/204

BTW, here's a list of PIL image formats and how many channels they have (Adapted from https://helpful.knobs-dials.com/index.php/Python_usage_notes_-_PIL):

PIL pixel formats:

RGB 24bits per pixel, 8-bit-per-channel RGB), 3 channels
RGBA (8-bit-per-channel RGBA), 4 channels
RGBa (8-bit-per-channel RGBA, remultiplied alpha), 4 channels
1 - 1bpp, often for masks, 1 channel
L - 8bpp, grayscale, 1 channel
P - 8bpp, paletted, 1 channel
I - 32-bit integers, grayscale, 1 channel
F - 32-bit floats, grayscale, 1 channel
CMYK - 8 bits per channel, 4 channels
YCbCr - 8 bits per channel, 3 channels

Upvotes: 5

Related Questions