python+tifffile之tiff文件读写方式
2020-02-13 10:17
1341 查看
背景
使用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学习笔记(八)文件创建与读取方式介绍及读写文件(file IO)
- Python Dict and File -- python字典与文件读写
- python 读写文件包含多种编码格式的解决方式
- Python:file/file-like对象方法详解【单个文件读写】
- Windows 8实用窍门系列:12.windows 8的文件管理---1.File创建和String Stream Buffer方式读写
- python file读写文件笔记
- Python 读写文件和file对象的方法(推荐)
- Python读写文件的方式
- python文件读写方式
- Python 读写文件和file对象
- python文件处理,b模式的读写,rb, wb,编码的两种方式
- Python 读写文件和file对象的方法(推荐)
- Python文件读写打开方式
- Python文件(File)及读写操作及生成器yield
- Python文件读写方式
- Python 读写当前路径下文件错误 UnboundLocalError: local variable 'file' referenced before assignment
- python 12 文件file 读写文件练习题(从键盘读字符)
- python file-like Object:文件读写
- python文件读写(从file1中读出数据并计算,然后将结果写入到file2中)
- Symbian RFileWriteStream和RFile 以追加的方式 读写文件操作