Python: Read and write TIFF 16 bit , three channel , colour images

后端 未结 6 2260
眼角桃花
眼角桃花 2020-12-07 14:32

Does anyone have a method for importing a 16 bit per channel, 3 channel TIFF image in Python?

I have yet to find a method which will preserve the 16 bit depth per ch

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 15:18

    The answer by @Jaime works.

    In the mean time I managed to also solve the problem using cv2.imread in OpenCV.

    By default cv2.imread will convert a 16 bit, three channel image in a.tif to 8 bit as shown in the question.

    cv2.imread accepts a flag after the filename ( cv2.imread(filename[, flags]) ) which specifies the colour type of the loaded image cf. the documentation:

    1. >0 returns a 3 channel colour image. This results in conversion to 8 bit as shown above.
    2. 0 returns a greyscale image. Also results in conversion to 8 bit.
    3. <0 returns the image as is. This will return a 16 bit image.

    So the following will read the image without conversion:

    >>> im = cv2.imread('a.tif', -1)
    >>> im.dtype
    dtype('uint16')
    >>> im.shape
    (288, 384, 3)
    

    Note that OpenCV returns the R, G and B channels in reverse order so im[:,:,0] is the B channel, im[:,:,1] the G channel and im[:,:,2] is the R channel.

    I have also found that cv2.imwrite can write 16 bit, three channel TIFF files.

    >>> cv2.imwrite('out.tif', im)
    

    Checking the bit depth with ImageMagick:

    $ identify -verbose out.tif
      Format: TIFF (Tagged Image File Format)
      Class: DirectClass
      Geometry: 384x288+0+0
      Resolution: 72x72
      Print size: 5.33333x4
      Units: PixelsPerInch
      Type: TrueColor
      Base type: TrueColor
      Endianess: MSB
      Colorspace: sRGB
      Depth: 16-bit
      Channel depth:
        red: 16-bit
        green: 16-bit
        blue: 16-bit
      ....
    

提交回复
热议问题