0

I'm saving numpy arrays as jpeg compressed tiff files in the following way

 import tifffile
 import numpy as np
 im = np.zeros((4,256,256))

 tifffile.imsave('myFile.tif' , im, compression = 'jpeg' )

What I'm wondering is whether there is a parameter with which I can controll the compression strength in the same way as I can with imageio.

 import imageio
 imageio.imsave('myFile.jpg' , im, quality=20)

In the documentation I cannot find such a parameter, but maybe it is hidden somewhere. It feels like such a parameter should probably be out there.

  • (@CharlesDuffy: the function is merely renamed to `imwrite()`, not removed entirely. And JPEG-compressed TIFF is not a "non-TIFF format", it's merely one of the Thousands of Incompatible File Formats.) The only quality-related option I see is `subsampling` - values are tuples, valid options are `(1,1)`, `(2,1)`, `(2,2)` (default), and `(4,1)`, smaller numbers are higher qualities. – jasonharper Mar 17 '23 at 15:29
  • Personally, and YMMV, JPEG encoding within TIFF files is something to be avoided if you want compatibility and archival/longevity of storage. – Mark Setchell Mar 24 '23 at 10:06

2 Answers2

1

I'm not 100 percent sure, but I think this is the way to do it. At least the behavior looks correct, that is the image gets smaller and indeed looks like an imageio saved image with the quality parameter.

import tifffile
 import numpy as np
 im = np.zeros((4,256,256))
 quality = 20
 tifffile.imsave('myFile.tif' , im, compression = ('jpeg', quality )

In other words you pass the compression as a tuple, with the name of the compression and an integer.

  • That method works, but it is deprecated. In newer versions of tifffile, use the `compressionargs` argument, e.g. `compressionargs={'level': 20}` – cgohlke Mar 18 '23 at 04:43
1

It depends on which version of tifffile you are using (as cgohlke pointed out). In a recent version (e.g. 20233.15) you'd use compression="jpeg" and compressionargs={"level":quality} to overwrite the compressor's default quality (or any other parameters it may have).

import tifffile
import numpy as np

im = np.zeros((4,256,256), dtype=np.uint8)
quality = 20

tifffile.imsave(
    'myFile.tif', 
    im,
    compression = "jpeg",
    compressionargs={"level": quality}
)

Note: This requires imagecodecs (pip install imagecodecs.

Also, since ImageIO can use tiffile as backend you can do the same in ImageIO:

import imageio.v3 as iio
import numpy as np

im = np.zeros((4,256,256), dtype=np.uint8)
quality = 20

iio.imwrite(
    "myFile.tif",
    im,
    compression="jpeg",
    compressionargs={"level":quality},
)

This works, because ImageIO defaults to tifffile when it is installed and you try to create a TIFF. You could also add plugin="tifffile" to make sure it always uses tifffile here.

FirefoxMetzger
  • 2,880
  • 1
  • 18
  • 32