Skip to content

Instantly share code, notes, and snippets.

@saltyJeff
Last active June 25, 2022 00:26
Show Gist options
  • Select an option

  • Save saltyJeff/5749095e1bda5099e5390bfb4fa9b9b5 to your computer and use it in GitHub Desktop.

Select an option

Save saltyJeff/5749095e1bda5099e5390bfb4fa9b9b5 to your computer and use it in GitHub Desktop.
Utility function that squeezes many images into one
"""
To use this library, make sure you have the following pip libraries installed:
- tifffile
- imagecodecs
"""
from os import PathLike
import os
import tifffile as tiff
import numpy as np
from typing import List, Tuple
def squeeze_images(imgs: List[Tuple[np.ndarray, str]], out_path: PathLike, level=31):
"""
Compressions a list of 2D NP arrays as images and a description string into a single TIFF
Args:
imgs (List[Tuple[np.ndarray, str]]): A list of images and their associated descriptions
out_path (PathLike): The output path to store the image
level (int, optional): The JPG compression level. 0 is maximum compression, 64 is no compression. Defaults to 31.
"""
with tiff.TiffWriter(out_path) as tif:
for img, desc in imgs:
tif.write(img, compression=('jpeg', level), metadata={'ImageDescription': desc})
if __name__ == '__main__':
"""
This demo program searches the CWD for any jpgs
It then squeezes them into a TIFF
The ImageDescription field in the TIFF will be the filenames of the images
"""
import glob
import imageio
jpgs = glob.glob('*.jpg')
imgs = []
total_size = 0
for jpg in jpgs:
imgs.append((imageio.imread(jpg), jpg))
total_size += os.stat(jpg).st_size
squeeze_images(imgs, 'out.tiff', level=0)
tiff_size = os.stat('out.tiff').st_size
print(f'Difference in size: {tiff_size-total_size} bytes')
with tiff.TiffReader('out.tiff') as tif:
for page in tif.pages:
print(page.description)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment