对python PLT中的image和skimage处理图片方法详解

  

python PLT中的image和skimage处理图片方法详解

前言

在Python中,matplotlib.pyplot(简称mpl或plt)和scikit-image(简称skimage)是常用的处理图像和可视化的库。本篇文章将详细讲解matplotlib.pyplot和scikit-image的常用API,以及使用案例。

matplotlib.pyplot处理图片

1、读取和显示图像

读取和显示图像是图像处理中的基础操作,最基本的方法如下:

import matplotlib.pyplot as plt
import numpy as np

# 读取图像
img = plt.imread('test.jpg')

# 显示图像
plt.imshow(img)
plt.show()

这里使用plt.imread读取图像,返回的是一个numpy数组。plt.imshow用来显示图片。

2、调整图像大小

修改图像大小的方法有很多,这里只介绍几种常用方法:

import matplotlib.pyplot as plt

# 读取图像
img = plt.imread('test.jpg')

# 调整大小为原来的2倍
img_resized = plt.resize(img, (img.shape[1] * 2, img.shape[0] * 2))

# 调整大小为256x256像素
img_resize = plt.resize(img, (256, 256))

# 显示调整大小后的图像
plt.imshow(img_resized)
plt.show()

其中,第一种方法可以将图像的宽和高都扩大2倍,第二种方法可以将图像大小修改为256x256像素。需要注意的是,如果对图像尺寸进行缩放,会造成图像失真。因此,在对图像进行缩放操作时,需要根据具体情况权衡。

3、图像裁剪

要裁剪图像,需要指定裁剪的区域。这里提供一种裁剪正方形区域的方法:

import matplotlib.pyplot as plt

# 读取图像
img = plt.imread('test.jpg')

# 裁剪正方形区域
h, w = img.shape[:2]
left, right, top, bottom = w // 4, w // 4 * 3, h // 4, h // 4 * 3
img_crop = img[top:bottom, left:right, :]

# 显示裁剪后的图像
plt.imshow(img_crop)
plt.show()

这里裁剪的区域是原图像的四分之一大小。其中,h和w表示原图像的高和宽。

示例1:生成包含噪声的图片

import matplotlib.pyplot as plt
import numpy as np

# 生成随机噪声
noise = np.random.normal(loc=0, scale=0.1, size=(512, 512))

# 读取图像
img = plt.imread('test.jpg')

# 对图像进行噪声处理
img_noise = np.clip(img + noise, 0, 1)

# 显示噪声处理后的图像
plt.imshow(img_noise)
plt.show()

这里使用np.random.normal生成符合正态分布的随机噪声,并使用np.clip函数将处理后的图像像素值限制在0-1之间。

scikit-image处理图片

1、读取和显示图像

使用scikit-image读取和显示图像的方法如下:

from skimage import io
import matplotlib.pyplot as plt

# 读取图像
img = io.imread('test.jpg')

# 显示图像
plt.imshow(img)
plt.show()

其中,io.imread用来读取图像。与matplotlib.pyplot类似,plt.imshow用来显示图像。

2、调整图像大小

调整图像大小的方法与matplotlib.pyplot类似,这里不再赘述。

3、图像裁剪

使用scikit-image裁剪图像的方法如下:

from skimage import io
import matplotlib.pyplot as plt

# 读取图像
img = io.imread('test.jpg')

# 裁剪图像
img_crop = img[100:300, 200:400]

# 显示裁剪后的图像
plt.imshow(img_crop)
plt.show()

这里裁剪的区域是从第100行到第300行、从第200列到第400列的图像区域。

示例2:使用Otsu算法实现图像二值化

from skimage import io, filters
import matplotlib.pyplot as plt

# 读取图像
img = io.imread('test.jpg', as_gray=True)

# 图像二值化
threshold = filters.threshold_otsu(img)
img_binary = img > threshold

# 显示二值化后的图像
plt.imshow(img_binary, cmap='gray')
plt.show()

这里使用scikit-image的filters.threshold_otsu函数进行自适应阈值处理,将图像二值化。最后使用plt.imshow函数显示二值化后的图像。

总结

本篇文章对matplotlib.pyplot和scikit-image的常用API进行了详细讲解,并提供了示例代码。使用这些API可以实现图像处理和可视化的各种操作。

相关文章