python+tifffile之tiff文件读写方式

yipeiwu_com6年前Python基础

背景

使用python操作一批同样分辨率的图片,合并为tiff格式的文件。

由于opencv主要用于读取单帧的tiff文件,对多帧的文件支持并不好。

通过搜索发现了两个比较有用的包:TiffCapture和tifffile。两者都可用pip安装。

其中前者主要用于读取tiff文件,后者可读可写。最终选择tifffile来合成tiff图片文件。

安装tifffile

pip install tifffile

原理及代码

我的图片是8 bit灰度图。

每次读取之后,先升维:

new_gray = gray_img[np.newaxis, ::]

然后再使用np.append添加到数组里。每append一次,相当于tiff增加一帧图片。

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

所有操作完毕,则一次性保存到磁盘。

tifffile.imsave( out_tiff_path, tiff_list )

下面是我的完整代码:

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

img_path = '../word_all'
out_txt_path = '../out_word_all.box'
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()
    os.chdir(dir_path)
    
    for img in img_list:
      
      print('dir_path:{}'.format(dir_path))
      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
      else:
        print('np.append')
        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)
      print(content)
      f.write(content.encode('UTF-8'))
      cnt_num += 1
    os.chdir(pwd)

  tifffile.imsave( out_tiff_path, tiff_list )


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

以上这篇python+tifffile之tiff文件读写方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

详解python调度框架APScheduler使用

最近在研究python调度框架APScheduler使用的路上,那么今天也算个学习笔记吧! # coding=utf-8 """ Demonstrates how to use t...

Python实现求数列和的方法示例

本文实例讲述了Python实现求数列和的方法。分享给大家供大家参考,具体如下: 问题: 输入 输入数据有多组,每组占一行,由两个整数n(n<10000)和m(m<1000)组...

Python GUI布局尺寸适配方法

如下所示: #coding=utf-8 #布局自定义尺寸 from tkinter import * class App: def __init__(self,master...

Python的垃圾回收机制深入分析

一、概述: Python的GC模块主要运用了“引用计数”(reference counting)来跟踪和回收垃圾。在引用计数的基础上,还可以通过“标记-清除”(mark and swee...

Python3实现从排序数组中删除重复项算法分析

本文实例讲述了Python3实现从排序数组中删除重复项算法。分享给大家供大家参考,具体如下: 题目:给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数...