python讀取影像的幾種方式
本文介紹幾種基于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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/303130.html
標籤:其他
