Python|使用 OpenCV 的阈值技术 | Set-3(大津阈值)
在之前的帖子中,解释了简单阈值和自适应阈值。在 Simple Thresholding 中,使用了全局阈值,该值始终保持不变。在自适应阈值化中,针对较小区域计算阈值,对于不同区域的不同阈值相对于照明的变化。
在Otsu Thresholding中,不选择阈值,而是自动确定。考虑了双峰图像(两个不同的图像值)。生成的直方图包含两个峰值。因此,一般条件是选择位于两个直方图峰值中间的阈值。
我们使用传统的cv2.threshold
函数并使用cv2.THRESH_OTSU
作为额外的标志。
Syntax: cv2.threshold(source, thresholdValue, maxVal, thresholdingTechnique)
Parameters:
-> source: Input Image array (must be in Grayscale).
-> thresholdValue: Value of Threshold below and above which pixel values will change accordingly.
-> maxVal: Maximum value that can be assigned to a pixel.
-> thresholdingTechnique: The type of thresholding to be applied.
下面是解释 Otsu 阈值技术的Python代码 -
# Python program to illustrate
# Otsu thresholding type on an image
# organizing imports
import cv2
import numpy as np
# path to input image is specified and
# image is loaded with imread command
image1 = cv2.imread('input1.jpg')
# cv2.cvtColor is applied over the
# image input with applied parameters
# to convert the image in grayscale
img = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
# applying Otsu thresholding
# as an extra flag in binary
# thresholding
ret, thresh1 = cv2.threshold(img, 120, 255, cv2.THRESH_BINARY +
cv2.THRESH_OTSU)
# the window showing output image
# with the corresponding thresholding
# techniques applied to the input image
cv2.imshow('Otsu Threshold', thresh1)
# De-allocate any associated memory usage
if cv2.waitKey(0) & 0xff == 27:
cv2.destroyAllWindows()
输入:
输出:
计算接受图片包含前景和背景像素之后的两类像素,此时它确定了隔离这两类像素的理想限制,目标是它们的合并扩展无关紧要。