不同类型的阈值处理(python->opencv)

这段代码演示了如何使用 OpenCV 在灰度图像上应用不同类型的阈值处理,并使用 Matplotlib 显示处理结果。为了全面理解这段代码,我们需要详细讲解每个步骤,包括阈值函数的不同模式及其对应的效果,以及如何使用 Matplotlib 显示多幅图像。

阈值处理概述

阈值处理是一种简单的图像分割技术,它通过设置一个阈值,将图像的像素值分成两类或多类。
OpenCV 的 cv2.threshold 函数
cv2.threshold 函数的基本调用格式如下:
ret, thresholded_image = cv2.threshold(src, thresh, maxval, type)
  • src:源图像,应该是灰度图像。
  • thresh:阈值。
  • maxval:最大值,当像素值超过(或低于,根据阈值类型)阈值时将被赋予的值。
  • type:阈值类型,决定如何应用阈值。
不同的阈值类型
  1. cv2.THRESH_BINARY:像素值大于阈值时赋值为 maxval,否则赋值为 0。
  2. cv2.THRESH_BINARY_INV:像素值大于阈值时赋值为 0,否则赋值为 maxval。
  3. cv2.THRESH_TRUNC:像素值大于阈值时赋值为阈值,否则保持原值。
  4. cv2.THRESH_TOZERO:像素值大于阈值时保持原值,否则赋值为 0。
  5. cv2.THRESH_TOZERO_INV:像素值大于阈值时赋值为 0,否则保持原值。

代码详解

以下是代码逐行解释:

import cv2 import matplotlib.pyplot as plt # 假设 img_gray 是一个灰度图像 img_gray = cv2.imread('path_to_image', cv2.IMREAD_GRAYSCALE) # 阈值处理,五种不同的阈值类型 ret, thresh1 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY) ret, thresh2 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY_INV) ret, thresh3 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TRUNC) ret, thresh4 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO) ret, thresh5 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO_INV) # 标题和处理后的图像列表 titles = ['Original Image', 'BINARY', 'BINARY_INV', 'TRUNC', 'TOZERO', 'TOZERO_INV'] images = [img_gray, thresh1, thresh2, thresh3, thresh4, thresh5] # 使用 Matplotlib 显示图像 for i in range(6): plt.subplot(2, 3, i + 1), plt.imshow(images[i], 'gray') # 在子图中显示图像

plt.title(titles[i]) # 设置子图标题

plt.xticks([]), plt.yticks([]) # 隐藏坐标轴刻度

plt.show() # 显示所有图像

详细解释

  1. 灰度图像读取
img_gray = cv2.imread('path_to_image', cv2.IMREAD_GRAYSCALE)
读取一幅灰度图像,用于后续的阈值处理。
  1. 应用不同的阈值处理
ret, thresh1 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY) ret, thresh2 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY_INV) ret, thresh3 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TRUNC) ret, thresh4 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO) ret, thresh5 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO_INV)
每种阈值处理方法都会生成不同的二值化图像。
  1. 准备显示
titles = ['Original Image', 'BINARY', 'BINARY_INV', 'TRUNC', 'TOZERO', 'TOZERO_INV'] images = [img_gray, thresh1, thresh2, thresh3, thresh4, thresh5]
准备好图像和对应的标题列表,用于在图像显示时使用。
  1. 显示图像
for i in range(6): plt.subplot(2, 3, i + 1), plt.imshow(images[i], 'gray') plt.title(titles[i]) plt.xticks([]), plt.yticks([]) plt.show()
使用 Matplotlib 的 subplot 函数将图像以2行3列的布局显示,并且设置标题和隐藏坐标轴。

总结

这段代码展示了如何使用 OpenCV 的 cv2.threshold 函数对图像进行不同类型的阈值处理,并使用 Matplotlib 来显示结果。通过这种方式,可以直观地比较不同阈值处理方法的效果。
Matplotlib 是 Python 中最流行的数据可视化库之一,广泛用于科学计算、工程和金融数据的可视化。它提供了一整套功能强大的绘图工具,使用户能够创建各种类型的图表,包括折线图、散点图、柱状图、直方图、饼图等。

Matplotlib 的主要组件

  1. pyplot
模块
  • pyplot 是 Matplotlib 的一个模块,提供了一组类似于 MATLAB 的绘图函数。它是最常用的模块,通过导入 matplotlib.pyplot 可以方便地使用各种绘图函数。
  • 常见的绘图函数包括 plt.plot(), plt.scatter(), plt.bar(), plt.hist(), plt.pie() 等。
  1. Figure 和 Axes
  • Figure:表示整个图形或画布。一个 Figure 可以包含多个子图(Axes)。
  • Axes:实际绘图的区域。一个 Figure 可以包含一个或多个 Axes 对象,每个 Axes 对象可以包含一个或多个图表。

基本使用示例

以下是一个简单的示例,展示如何使用 Matplotlib 创建折线图:
import matplotlib.pyplot as plt # 数据 x = [1, 2, 3, 4, 5] y = [10, 20, 25, 30, 40] # 创建折线图 plt.plot(x, y) # 添加标题和标签 plt.title('Simple Line Plot') plt.xlabel('X-axis') plt.ylabel('Y-axis') # 显示图表 plt.show()

常见图表类型

  1. 折线图(Line Plot)
plt.plot(x, y)
  1. 散点图(Scatter Plot)
plt.scatter(x, y)
  1. 柱状图(Bar Chart)
plt.bar(x, height)
  1. 直方图(Histogram)
plt.hist(data, bins=10)
  1. 饼图(Pie Chart)
plt.pie(sizes, labels=labels)

自定义图表

Matplotlib 提供了大量自定义选项,使用户能够对图表进行细致的调整。例如,可以自定义颜色、线型、标记、文本字体、图例位置等。
以下示例展示了如何自定义折线图:
import matplotlib.pyplot as plt # 数据 x = [1, 2, 3, 4, 5] y = [10, 20, 25, 30, 40] # 自定义折线图 plt.plot(x, y, color='red', linestyle='--', marker='o', markersize=8, label='Data Line') # 添加标题和标签 plt.title('Customized Line Plot') plt.xlabel('X-axis') plt.ylabel('Y-axis') # 添加图例 plt.legend() # 显示图表 plt.show()

子图和布局

有时需要在一个 Figure 中显示多个子图,Matplotlib 提供了 subplot 和 subplots 函数来实现这一点。
使用 subplot 函数:
import matplotlib.pyplot as plt # 数据 x = [1, 2, 3, 4, 5] y1 = [10, 20, 25, 30, 40] y2 = [40, 30, 25, 20, 10] # 创建一个 2x1 的子图布局 plt.subplot(2, 1, 1) plt.plot(x, y1) plt.title('Subplot 1') plt.subplot(2, 1, 2) plt.plot(x, y2) plt.title('Subplot 2') # 调整布局和显示图表 plt.tight_layout() plt.show()
使用 subplots 函数:
import matplotlib.pyplot as plt # 数据 x = [1, 2, 3, 4, 5] y1 = [10, 20, 25, 30, 40] y2 = [40, 30, 25, 20, 10] # 创建一个 2x1 的子图布局 fig, axs = plt.subplots(2, 1) axs[0].plot(x, y1) axs[0].set_title('Subplot 1') axs[1].plot(x, y2) axs[1].set_title('Subplot 2') # 调整布局和显示图表 plt.tight_layout() plt.show()

3D 绘图

Matplotlib 还支持3D绘图。使用 mpl_toolkits.mplot3d 模块,可以创建3D图表,如3D散点图和3D曲面图。
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np # 数据 x = np.linspace(-5, 5, 100) y = np.linspace(-5, 5, 100) x, y = np.meshgrid(x, y) z = np.sin(np.sqrt(x**2 + y**2)) # 创建一个 3D 轴对象 fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # 绘制 3D 曲面图 ax.plot_surface(x, y, z, cmap='viridis') # 显示图表 plt.show()

结论

Matplotlib 是一个功能强大且灵活的数据可视化库,它提供了创建各类图表的方法,并允许用户进行高度自定义。无论是简单的绘图需求还是复杂的可视化任务,Matplotlib 都能够满足。通过结合使用其他科学计算库(如 NumPy 和 Pandas),您可以实现更复杂的数据分析和可视化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张槊哲

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值