在 Python 中读取图像的四种方案

385 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第3天,点击查看活动详情

在 Python 中读取图像

在图像处理方面,Python 支持非常强大的工具。让我们看看如何使用不同的库处理图像,如ImageIO、OpenCV、Matplotlib、PIL等。

使用 ImageIO: Imageio 是一个 Python 库,它提供了一个简单的接口来读取和写入各种图像数据,包括动画图像、视频、体积数据和科学格式。它是跨平台的,在 Python 3.7+ 上运行,并且易于安装。它是 scipy.misc.imread 的推荐替代品,并由scikit-image等库在内部使用以加载图像。

# Python program to read an write an imageimport imageio as iio
​
# read an image
img = iio.imread("g4g.png")
​
# write it in a new format
iio.imwrite("g4g.jpg", img)
​

使用 OpenCV: OpenCV(开源计算机视觉)是一个计算机视觉库,包含对图片或视频执行操作的各种功能。它最初由 Intel 开发,后来由 Willow Garage 维护,现在由 Itseez 维护。这个库是跨平台的,它可以在多种编程语言(如 Python、C++ 等)上使用。

# Python program to read image using OpenCV# importing OpenCV(cv2) module
import cv2
​
# Save image in set directory
# Read RGB image
img = cv2.imread('g4g.png')
​
# Output img with window name as 'image'
cv2.imshow('image', img)
​
# Maintain output window utill
# user presses a key
cv2.waitKey(0)  
​
# Destroying present windows on screen
cv2.destroyAllWindows()
​

使用 MatplotLib: Matplotlib 是 Python 中用于二维数组绘图的惊人可视化库。Matplotlib 是一个基于 NumPy 数组构建的多平台数据可视化库,旨在与更广泛的 SciPy 堆栈一起使用。它由 John Hunter 在 2002 年推出。Matplotlib 带有各种各样的绘图。绘图有助于理解趋势、模式并建立相关性。它们通常是推理定量信息的工具。

# Python program to read
# image using matplotlib# importing matplotlib modules
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
​
# Read Images
img = mpimg.imread('g4g.png')
​
# Output Images
plt.imshow(img)
​

使用 PIL: PIL 是 Python 图像库,它为 Python 解释器提供图像编辑功能。它由 Fredrik Lundh 和其他几位贡献者开发。Pillow 是由 Alex Clark 和其他贡献者开发的友好 PIL 分支和易于使用的库。

# Python program to read
# image using PIL module# importing PIL
from PIL import Image
​
# Read image
img = Image.open('g4g.png')
​
# Output Images
img.show()
​
# prints format of image
print(img.format)
​
# prints mode of image
print(img.mode)
​