How to read and write TIFF file in Python + tifffile



Use Python to operate a batch of images with the same resolution, and merge them into TIFF format files.

Because opencv is mainly used to read single frame TIFF files, it does not support multi frame files well.

Two useful packages are found: tiffcapture and tifffile. Both can be installed with PIP.

The former is mainly used to read TIFF files, while the latter is readable and writable. Finally, the TIFF file is selected to synthesize the TIFF image file.

Install tifffile

pip install tifffile

Principle and code

My picture is 8 bit grayscale.

After each read, first upgrade dimension:

new_gray = gray_img[np.newaxis, ::]

Then use it again np.append Add to the array. Each append is equivalent to TIFF adding a frame of picture.

tiff_list = np.append(tiff_list, new_gray, axis=0)

After all operations are completed, it will be saved to disk at one time.

tifffile.imsave( out_tiff_path, tiff_list )

Here is my complete code:

import cv2
import tifffile
import time
import numpy as np
import time
import os

img_path = '../word_all'
out_txt_path = '../'
out_tiff_path = '../out_word_all.tif'

tiff_list = None

with open(out_txt_path, 'wb') as f:
  dir_list = os.listdir(img_path)
  cnt_num = 0
  for dir_name in dir_list:
    dir_path = os.path.join(img_path, dir_name)
    img_list = os.listdir(dir_path)
    pwd = os.getcwd()
    for img in img_list:
      gray_img = cv2.imread(img, cv2.IMREAD_GRAYSCALE)
      new_gray = gray_img[np.newaxis, ::]
      print('gray_img shape:{}, new_gray shape:{}'.format(gray_img.shape, new_gray.shape))
      #global cnt_num
      if cnt_num == 0:
        print('cnt_num == 0')
        tiff_list = new_gray
        tiff_list = np.append(tiff_list, new_gray, axis=0)
        print('tiff_list shape:{}'.format(tiff_list.shape))
      content = '{} 2 2 60 60 {}\n'.format(dir_name, cnt_num)
      cnt_num += 1

  tifffile.imsave( out_tiff_path, tiff_list )

print('tiff_list shape:{}'.format(tiff_list.shape))

The above way to read and write the TIFF file in Python + tifffile is the whole content shared by Xiaobian. I hope it can give you a reference and support developer.