increassing jpeg compression in the tifffile library

648 Views Asked by At

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.

2

There are 2 best solutions below

1
Daniel van der Maas On

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.

0
FirefoxMetzger On

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.