阈值化入门

Python 图像处理

Rebeca Gonzalez

Data Engineer

阈值化

将图像分成前景与背景

通过转为黑白

方法:将每个像素设为:

  • 255(白),若像素 > 阈值
  • 0(黑),若像素 < 阈值

相机男子的阈值化图像

Python 图像处理

阈值化

最简单的图像分割方法

  • 分离目标
    • 目标检测
    • 人脸检测
    • 等等

阈值化的多米诺骨牌图像

Python 图像处理

阈值化

仅适用于灰度图像

阈值化步骤,示例为多米诺骨牌:原始RGB三通道、转灰度、再阈值化

Python 图像处理

动手应用

# Obtain the optimal threshold value
thresh = 127

# Apply thresholding to the image binary = image > thresh
# Show the original and thresholded show_image(image, 'Original') show_image(binary, 'Thresholded')

相机男子的阈值化图像

Python 图像处理

反向阈值化

# Obtain the optimal threshold value
thresh = 127

# Apply thresholding to the image inverted_binary = image <= thresh
# Show the original and thresholded show_image(image, 'Original') show_image(inverted_binary, 'Inverted thresholded')

相机男子的反向阈值化图像

Python 图像处理

类别

  • 全局/基于直方图:适合背景均匀

  • 局部/自适应:适合背景不均匀

全局与局部阈值化对比

Python 图像处理

尝试更多阈值算法

from skimage.filters import try_all_threshold

# Obtain all the resulting images fig, ax = try_all_threshold(image, verbose=False)
# Showing resulting plots show_plot(fig, ax)
Python 图像处理

尝试更多阈值算法

在一页灰度文字图像上测试的所有全局阈值方法

Python 图像处理

最优阈值

全局

背景均匀
# Import the otsu threshold function
from skimage.filters import threshold_otsu

# Obtain the optimal threshold value thresh = threshold_otsu(image)
# Apply thresholding to the image binary_global = image > thresh
Python 图像处理

最优阈值

全局

# Show the original and binarized image
show_image(image, 'Original')
show_image(binary_global, 'Global thresholding')

相机男子的原图、阈值化结果及其直方图(红线为最优阈值)

Python 图像处理

最优阈值

局部

背景不均匀
# Import the local threshold function
from skimage.filters import threshold_local

# Set the block size to 35 block_size = 35
# Obtain the optimal local thresholding local_thresh = threshold_local(text_image, block_size, offset=10)
# Apply local thresholding and obtain the binary image binary_local = text_image > local_thresh
Python 图像处理

最优阈值

局部

# Show the original and binarized image
show_image(text_image, 'Original')
show_image(binary_local, 'Local thresholding')

文本页的局部阈值化图像

Python 图像处理

开始练习!

Python 图像处理

Preparing Video For Download...