Python 各種讀取保存tif,tiff,png,jpg,mat等格式圖像方法大集合


利用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同)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM