好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

总结

到此这篇关于基于python读取图像的几种方式的文章就介绍到这了,更多相关python读取图像内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

查看更多关于基于python读取图像的几种方式汇总的详细内容...

  阅读:36次