python讀取圖片的方式

1. opencv-python包

opencv的像素值在[0,1] 之間,存儲的時候轉換到[0,255] ,show的時候轉換到[0,255]

import cv2
img = cv2.imread("imgfile")
cv2.imshow("img_win_name", img)
cv2.waitKey(0)  # 無限期等待輸入

cv2.imwrite("write_file_name", img)

注意,opencv打開圖片的格式爲:

height×width×channels

即通道數在最後面
其中3 個通道的順序分別是BGR
分離方法爲:
b, g, r = cv2.split(img)

2. scikit-image包

scikit-image的像素值在[1,1] 之間,存儲的時候轉換到[0,255] ,show的時候轉換到[0,255]

import skimage.io as io
import matplotlib.pyplot as plt

img = io.imread("a.jpg")
io.imshow(img)
plt.show()

注意skimage讀取圖片也是height×width×channels
通道順序是R,G,B

3. matplotlib包

matplotlib的像素值在[-1,1]之間,存儲的時候轉換到[0,255] ,show的時候轉換到[0,255]

import matplotlib.pyplot as plt

img = plt.imread("img_name")
plt.imshow(img)

matplotlib讀取圖片也是height×widht×channels ,也是R,G,B

4. tifffile包

import tifffile as tiff

# 將圖片的像素值放縮到[0,1]之間
def scale_percentile(matrix):
    w, h, d = matrix.shape
    matrix = np.reshape(matrix, [w * h, d]).astype(np.float64)
    # Get 2nd and 98th percentile
    mins = np.percentile(matrix, 1, axis=0)
    maxs = np.percentile(matrix, 99, axis=0) - mins
    matrix = (matrix - mins[None, :]) / maxs[None, :]
    matrix = np.reshape(matrix, [w, h, d])
    matrix = matrix.clip(0, 1)
    return matrix

img = tiff.imread("file_name")
tiff.imshow(scale_percentile(img))

注意tifffile的圖片的讀取順序height×width×channelsR,G,B 按照波段來獲取。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章