利用opencv读取tif 文件
1 #导入cv模块 2 import cv2 as cv 3 import numpy as np 4 #读取图像,支持 bmp、jpg、png、tiff 等常用格式 5 #第二个参数是通道数和位深的参数,有四种选择,参https://www.cnblogs.com/goushibao/p/6671079.html
6 img = cv.imread("filename.tif",2) 7 print img 8 #在这里一开始我写成了img.shape(),报错因为img是一个数组不是一个函数,只有函数才可以加()表示请求执行, 9 #参考http://blog.csdn.net/a19990412/article/details/78283742
10 print img.shape 11 print img.dtype 12 print img.min() 13 print img.max() 14 #创建窗口并显示图像 15 cv.namedWindow("Image") 16 cv.imshow("Image",img) 17 cv.waitKey(0)#释放窗口 18 cv.destroyAllWindows()
对于cv2,imread的关于通道数和位深的flags有四种选择:
1 IMREAD_UNCHANGED = -1#不进行转化,比如保存为了16位的图片,读取出来仍然为16位。 2 IMREAD_GRAYSCALE = 0#进行转化为灰度图,比如保存为了16位的图片,读取出来为8位,类型为CV_8UC1。 3 IMREAD_COLOR = 1#进行转化为RGB三通道图像,图像深度转为8位 4 IMREAD_ANYDEPTH = 2#保持图像深度不变,进行转化为灰度图。 5 IMREAD_ANYCOLOR = 4#若图像通道数小于等于3,则保持原通道数不变;若通道数大于3则只取取前三个通道。图像深度转为8位
PIL读取图像
1 from PIL import Image 2 im = Image.open("filename")
支持单通道及多通道Uint8 TIFF图像读取,读取单通道Uint16 TIFF图像转为Uint8处理,直接读取Uint16 TIFF图像会报错。
LIBTIFF包读取保存图像
1 from libtiff import TIFF 2 # to open a tiff file for reading: 3
4 tif = TIFF.open('filename.tif', mode='r') 5 # to read an image in the currect TIFF directory and return it as numpy array: 6
7 image = tif.read_image() 8 # to read all images in a TIFF file: 9
10 for image in tif.iter_images(): # do stuff with image 11 # to open a tiff file for writing: 12
13 tif = TIFF.open('filename.tif', mode='w') 14 # to write a image to tiff file 15
16 tif.write_image(image)
scikit包读取保存图像
1 from skimage import io 2 img = io.imread('testimg.tif') 3 import numpy as np 4 data=np.random.random([100,100]) 5 io.imsave('rand_data.tif',np.float32(data))
imageio包读取保存图像
1 import imageio 2 im = imageio.imread('imageio:chelsea.png') # read a standard image 3 im.shape # im is a numpy array (300, 451, 3) 4 imageio.imwrite('~/chelsea-gray.jpg', im[:, :, 0])
misc包读取保存图像
1 from scipy import misc 2
3 # 读入已有图像,数据类型和原图像一致 4 tif32 = misc.imread('.\test\lena32.tif') #<class 'numpy.float32'="">
5 tif16 = misc.imread('.\test\lena16.tif') #<class 'numpy.uint16'="">
6 tif8 = misc.imread('.\test\lena8.tif') #<class 'numpy.uint8'="">
7
8 #保存图像 9 misc.imsave('.\test\lena32_scipy.tif', tif32) #--> 8bit(tif16和tif8同) 10 misc.imsave('.\test\\randmat64_scipy.tif', flt) #--> 8bit 11 misc.imsave('.\test\\randmat8_scipy.tif', z8) #--> 8bit(z16和z32同)