Python: How to save image with 16 bit channels (e.g. 48 RGB)?

Question:

I’m working scientifically with images from a microscope, where each of the 3 RGB channels are encoded as uint16 (0-65536). Currently I use OpenCV2 and NumPy to work with the images, and using the flag “cv2.IMREAD_UNCHANGED” everything works fine with the reading, and I can do some work on the image and return it to uint16,

img = cv2.imread('dummy.tif',cv2.IMREAD_UNCHANGED )
#do some work here
img = img.astype(numpy.uint16)
cv2.imwrite('processed.tif',img )

However, so far I can’t seem to find any way to save the processed images as 16bit RGB again. Using the cv2.imwrite command just convert the image to uint8, thus turning everything white (that is, everything is truncated to 255, the max for uint8 channels).

Any idea how to proceed?

Asked By: Happy

||

Answers:

Maybe it helps if the numpy.uint16 is replace by cv2.CV_16U.
In some example the parameter is passed in as a string e.g. ‘uint16’.

Sry, reputation too low for a comment.

Answered By: Robert Caspary

OpenCV does support writing 16 Bit TIFF images.

Make sure you are using a current version (>= 2.2).

The truncation probably happens to img in your code before saving with OpenCV.

Answered By: w-m
# Below is the solution using OpenCV: #

import cv2

image = cv2.imread("dummy.tif", cv2.IMREAD_UNCHANGED)

## do some work here ##
### make sure to update data type before saving ###

image = cv2.cvtColor(image, cv2.CV_16U)

cv2.imwrite("processed.tif", image)
Answered By: Phillip
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.