本文对Python图像处理中的二值化技术进行了详细的归纳和实操演示,通过具体代码示例帮助读者掌握多种常见的二值化算法。
在使用Python进行图像处理时,二值化是一个非常关键的步骤。这里总结了自己遇到过的六种图像二值化的方法(当然这并不是全部方法,如果发现新的方法会继续增加)。以下是这些方法:
1. 使用OpenCV库中的简单阈值函数 `cv2.threshold`。
2. 使用OpenCV库中的自适应阈值函数 `cv2.adaptiveThreshold`。在该函数中计算阈值的方式有两种:mean_c 和 guassian_c,可以尝试使用不同的方式来观察效果。
以下是一个Otsu二值化的示例代码:
```python
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread(path_to_your_image) # 加载图像文件路径替换为实际的图片路径
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh1 = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# 显示结果(可选)
plt.figure(figsize=[16,8])
plt.subplot(131); plt.imshow(img,cmap=gray); plt.title(Original Image)
plt.subplot(132); plt.hist(gray.ravel(), bins=50, range=(0, 255)); plt.axvline(x=ret,color=red)
plt.subplot(133); plt.imshow(thresh1,cmap=gray); plt.title(Otsus thresholding)
plt.show()
```