背景
使用python操作一批同樣分辨率的圖片,合并為tiff格式的文件。
由于opencv主要用于讀取單幀的tiff文件,對多幀的文件支持并不好。
通過搜索發現了兩個比較有用的包:TiffCapture和tifffile。兩者都可用pip安裝。
其中前者主要用于讀取tiff文件,后者可讀可寫。最終選擇tifffile來合成tiff圖片文件。
安裝tifffile
1
|
pip install tifffile |
原理及代碼
我的圖片是8 bit灰度圖。
每次讀取之后,先升維:
1
|
new_gray = gray_img[np.newaxis, ::] |
然后再使用np.append添加到數組里。每append一次,相當于tiff增加一幀圖片。
1
|
tiff_list = np.append(tiff_list, new_gray, axis = 0 ) |
所有操作完畢,則一次性保存到磁盤。
1
|
tifffile.imsave( out_tiff_path, tiff_list ) |
下面是我的完整代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
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文件讀寫方式就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/yuanlulu/article/details/83279768