38

I'm trying to read a 16 bit grayscale image using OpenCV 2.4 in Python, but it seems to be loading it as 8 bit.

I'm doing:

im = cv2.imread(path,0)
print im

[[25 25 28 ...,  0  0  0]
[ 0  0  0 ...,  0  0  0]
[ 0  0  0 ...,  0  0  0]
..., 

How do I get it as 16 bit?

Kkov
  • 1,472
  • 2
  • 11
  • 20

4 Answers4

50

Figured it out. In case anyone else runs into this problem:

im = cv2.imread(path,-1)

Setting the flag to 0, to load as grayscale, seems to default to 8 bit. Setting the flag to -1 loads the image as is.

Kkov
  • 1,472
  • 2
  • 11
  • 20
  • The flags works perfectly for me. It reads the image as `uint16` instead of `uint8`. – Amir Pourmand Jul 05 '22 at 06:11
  • you should not use fixed numbers if there are approriate flags like `cv2.IMREAD_ANYDEPTH` (readability, maintainability, protection against changes in flag values) – DomTomCat Dec 15 '22 at 12:17
38

To improve readability use the flag cv2.IMREAD_ANYDEPTH

image = cv2.imread( path, cv2.IMREAD_ANYDEPTH )
Thomio
  • 1,403
  • 15
  • 19
8

I had the same issue (16-bit .tif loading as 8-bit using cv2.imread). However, using the -1 flag didn't help. Instead, I was able to load 16-bit images using the tifffile package.

Eric Olmon
  • 919
  • 7
  • 5
  • 7
    The `tifffile` package worked perfectly. Nothing I tried worked for `cv2.imread` flags: `cv2.IMREAD_ANYDEPTH`, `cv2.IMREAD_ANYCOLOR`, those two combined (`6`), as well as `-1`. – colllin Nov 30 '18 at 18:44
3

This question suggests that image = cv2.imread('16bit.png', cv2.IMREAD_UNCHANGED) will also solve your problem.

Breadman10
  • 81
  • 6