PiRK
PiRK

Reputation: 1075

How to load a 16-bits/channel RGB(A) image with PIL?

I'm trying to load a 16 bits colors RGBA image with PIL.

I downloaded the image pnggrad16rgba.png from the following link: https://www.fnordware.com/superpng/samples.html enter image description here I checked that it has indeed 16 bits per pixel's color channel:

screenshot of file properties in Windows Explorer

But then when I try to load the data in PIL, I get uint8 data:

>>> from PIL import Image
>>> import numpy
>>> im = Image.open("D:/pnggrad16rgba.png")
>>> arr = numpy.array(im)
>>> arr.dtype
dtype('uint8')
>>> arr[0, 0]
array([  0,   0, 255, 255], dtype=uint8)

Is there a way to access the 16 bits data without downcasting it to uint8 with PIL?

If not, what other library could handle this?

Upvotes: 2

Views: 3952

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207883

PIL doesn't support multi-channel 16-bit/channel images - see documentation. I would suggest you use OpenCV with the cv2.IMREAD_UNCHANGED flag like this:

import cv2                                                                                               

# Load image as 16-bits per channel, 4 channels
BGRA = cv2.imread('pnggrad16rgba.png', cv2.IMREAD_UNCHANGED) 

# Check channels and depth
print(BGRA.dtype, BGRA.shape)                                                                                                
dtype('uint16')
(600, 600, 4)

Be aware that your image will be in BGRA order, not RGBA, because OpenCV is... well, OpenCV.

If you need to, you can get from BGRA to RGBA using

RGBA = cv2.cvtColor(BGRA, cv2.COLOR_BGRA2RGBA)

Upvotes: 5

Related Questions