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