0

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

shirha
  • 453
  • 3
  • 11

2 Answers2

2

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

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • I tried your wand code on this image but it came out grayscale. [image.tif(zip)](https://www.dropbox.com/s/pe42a3dhvb6e7aw/image.zip) ![result_info](https://www.dropbox.com/s/sc3jk1y223efi79/result_info.png) – shirha May 28 '20 at 02:49
  • Oh, that's odd. I get a bi-level LZW-compressed result on my machine. Maybe you don't have `libtiff` installed, or your **ImageMagick** or `libtiff` are old versions... – Mark Setchell May 28 '20 at 11:05
  • I forgot to mention I'm on windows 10 and installed the latest ImageMagick-7.0.10-14-Q16-x64-dll.exe before I filed an [issue](https://github.com/ImageMagick/ImageMagick/issues/2069) with ImageMagick for performance problems with this bilevel problem. Now I'm running Q8. I'm able to do the conversion with this command: `magick mogrify -path ..\bw -colors 2 +dither -type bilevel -compress Group4 *.tiff` Any thoughts? Thanks. I also have the latest `wand` on Anaconda. – shirha May 28 '20 at 17:25
0

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.

shirha
  • 453
  • 3
  • 11