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()


免責聲明!

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



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