How do you output and indexed (black and white) tiff image in opencv

2.3k Views Asked by At

If I imwrite a binarized image, it only creates a grayscale image file not an indexed=2 file. What options do I need on the imwrite to accomplish this? I would also like LZW compression if possible.

  orig = cv2.imread('rgb.tiff')
  work = cv2.cvtColor(orig, cv2.COLOR_BGR2GRAY)
  work = cv2.ximgproc.niBlackThreshold(work, 255, cv2.THRESH_BINARY, 41, -0.2,
    binarizationMethod=cv2.ximgproc.BINARIZATION_NICK)
  cv2.imwrite('bw.tiff', work)

grayscale vs indexed

2

There are 2 best solutions below

3
On

If you really, really want a bi-level LZW-compressed TIFF, you can write one with wand like this:

#!/usr/bin/env python3

from wand.image import Image

# Open image and save as bi-level LZW-compressed version
with Image(filename='image.tif') as img: 
    img.compression='lzw'
    img.type='bilevel'
    img.save(filename='result.tif')

Input:

enter image description here

Result:

enter image description here

Note that you can save OpenCV images like this, but you must first convert from its BGR order to conventional RGB order first. You can use:

RGB = cv2.cvtColor(BGRimage, cv2.COLOR_BGR2RGB)

or pure Numpy:

RGB = BGRimage[...,::-1]

Keywords: Python, image processing, wand, TIFF, TIF, LZW, compressed, compression, bilevel, bi-level

0
On

imwrite Only 8-bit (or 16-bit unsigned (CV_16U) in case of PNG, JPEG 2000, and TIFF) single-channel or 3-channel (with ‘BGR’ channel order) images can be saved using this function.