基于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
設(shè)置圖片名字
img_path = './test.png'
用PIL的open函數(shù)讀取圖片
img = Image.open(img_path)
讀進來是一個Image對象
img

查看圖片的mode
img.mode
'RGB'
用PIL函數(shù)convert將彩色RGB圖像轉(zhuǎn)換為灰度圖像
img_g = img.convert('L')img_g.mode
'L'
img_g.save('./test_gray.png')使用PIL庫的crop函數(shù)可對圖像進行裁剪
img_c = img.crop((100,50,200,150))img_c

圖像旋轉(zhuǎn)
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時,可以進行不同程度的插值,當(dāng)繪制圖像很小時,這些方法比較有用,如上所示就是用了樣條插值。
基于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()
總結(jié)
到此這篇關(guān)于基于python讀取圖像的幾種方式的文章就介紹到這了,更多相關(guān)python讀取圖像內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
windows10下python3.5 pip3安裝圖文教程
這篇文章主要為大家詳細(xì)介紹了windows10下python3.5 pip3安裝圖文教程,注意區(qū)分python 2.x和python 3.x的相關(guān)命令,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-04-04
python通過pip更新所有已安裝的包實現(xiàn)方法
下面小編就為的帶來一篇python通過pip更新所有已安裝的包實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05
Python?Paramiko上傳下載sftp文件及遠(yuǎn)程執(zhí)行命令詳解
這篇文章主要為大家介紹了Python?Paramiko上傳下載sftp文件及遠(yuǎn)程執(zhí)行命令示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-07-07
Anaconda+Pycharm環(huán)境下的PyTorch配置方法
這篇文章主要介紹了Anaconda+Pycharm環(huán)境下的PyTorch配置方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-03-03
Python設(shè)計模式結(jié)構(gòu)型享元模式
這篇文章主要介紹了Python享元模式,享元模式即Flyweight Pattern,指運用共享技術(shù)有效地支持大量細(xì)粒度的對象,下面和小編一起進入文章了解更多詳細(xì)內(nèi)容吧2022-02-02

