mgaz
mgaz

Reputation: 43

Problems in displaying uint16 np.array as image

I have a uint16 3-dim numpy array reppresenting an RGB image, the array is created from a TIF image. The problem is that when I import the original image in QGIS for example is displayed correctly, but if I try to display within python (with plt.imshow) the result is different (in this case more green):

QGIS image:

QGIS image

Plot image:

Plot image

I think it is somehow related to the way matplotlib manages uint16 but even if I try to divide by 255 and convert to uint8 I can't get good results.

Upvotes: 1

Views: 2116

Answers (3)

mgaz
mgaz

Reputation: 43

If I try to normalize the image I get good results:

for every channel: image[i,:,:] = image[i,:,:] / image[i,:,:].max()

However, some images appear darker than others:

different images

Upvotes: 0

Alex
Alex

Reputation: 23

Going by your comment, the image isn't encoded using an RGB colour space, since the R, G and B channels have a value range of [0-255] assuming 8 bits per channel.

I'm not sure exactly which colour space the image is using, but TIFF files generally use CMYK which is optimised for printing.

Other common colour spaces to try include YCbCr (YUV) and HSL, however there are lots of variations of these that have been created over the years as display hardware and video streaming technologies have advanced.

To convert the entire image to an RGB colour space, I'd recommend the opencv-python pip package. The package is well documented, but as an example, here's how you would convert a numpy array img from YUV to RGB:

img_bgr = cv.cvtColor(img, cv.COLOR_YUV2RGB)

Upvotes: 1

PurpleCube
PurpleCube

Reputation: 36

When using plt.imshow there's the colormap parameter you can play with, try adding cmap="gray" so for example

plt.imshow(image, cmap="gray")

source: https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.imshow.html

Upvotes: 0

Related Questions