本文介紹幾種基於python的圖像讀取方式:
- 基於PIL庫的圖像讀取、保存和顯示
- 基於opencv-python的圖像讀取、保存和顯示
- 基於matplotlib的圖像讀取、保存和顯示
- 基於scikit-image的圖像讀取、保存和顯示
- 基於imageio的圖像讀取、保存和顯示
安裝方式基本使用pip
即可:
pip install pillow
pip install scikit-image
pip install matplotlib
pip install opencv-python
pip install numpy scipy scikit-learn
基於PIL庫的圖像讀取、保存和顯示
from PIL import Image
設置圖片名字
img_path = './test.png'
用PIL的open
函數讀取圖片
img = Image.open(img_path)
讀進來是一個Image對象
img
查看圖片的mode
img.mode
'RGB'
用PIL函數convert
將彩色RGB圖像轉換為灰度圖像
img_g = img.convert('L')
img_g.mode
'L'
img_g.save('./test_gray.png')
使用PIL庫的crop
函數可對圖像進行裁剪
img_c = img.crop((100,50,200,150))
img_c
圖像旋轉
img.rotate(45)
在圖像上添加文字
from PIL import ImageDraw, ImageFont
draw = ImageDraw.Draw(img)
font = ImageFont.truetype('/home/fsf/Fonts/ariali.ttf',size=24)
draw.text((10,5), "This is a picture of sunspot.", font=font)
del draw
img
基於opencv-python的圖像讀取、保存和顯示
import cv2
img = cv2.imread('./test.png')
使用cv2都進來是一個numpy矩陣,像素值介於0~255
,可以使用matplotlib進行展示
img.min(), img.max()
(0, 255)
import matplotlib.pyplot as plt
plt.imshow(img)
plt.axis('off')
plt.show()
基於matplotlib的圖像讀取、顯示和保存
import matplotlib.image as mpimg
img = mpimg.imread('./test.png')
img.min(),img.max()
(0.0, 1.0)
像素值介於0~1
之間,可以使用如下方法進行展示
import matplotlib.pyplot as plt
plt.imshow(img,interpolation='spline16')
plt.axis('off')
plt.show()
注意:matplotlib在進行imshow
時,可以進行不同程度的插值,當繪制圖像很小時,這些方法比較有用,如上所示就是用了樣條插值。
基於scikit-image的圖像讀取、保存和顯示
from skimage.io import imread, imsave, imshow
img = imread('./test.png')
這個和opencv-python類似,讀取進來也是numpy矩陣,像素值介於0~255
之間
img.min(), img.max()
(0, 255)
import matplotlib.pyplot as plt
plt.imshow(img,interpolation='spline16')
plt.axis('off')
plt.show()
基於imageio的圖像讀取、顯示和保存
import imageio
img = imageio.imread('./test.png')
img.min(), img.max()
(0, 255)
這個和opencv-python、scikit-image類似,讀取進來也都是numpy矩陣,像素值介於0~255
之間
import matplotlib.pyplot as plt
plt.imshow(img,interpolation='spline16')
plt.axis('off')
plt.show()