例子源于OpenCV官网手册:https://docs.opencv.org/4.x/db/d8e/tutorial_threshold.html
使用OpenCV函数cv::threshold执行基本阈值操作
理论:
分离出图像中与我们想要分析的对象相对应的区域。这种分离是基于对象像素和背景像素之间的强度变化。
为了将我们感兴趣的像素与其他像素区分开来,我们对每个像素强度值与一个阈值(根据要解决的问题确定)进行比较。
一旦我们正确地分离了重要的像素,我们就可以用一个确定的值来识别它们(例如,我们可以给它们赋值0(黑色),255(白色)或任何适合你需要的值)。
运行结果:
原图
分离像素后的图像:
原图:
结果1:现在我们尝试将阈值设为0。这样,我们预计最暗的像素(低于阈值)将完全变黑,而值大于阈值的像素将保持其原始值。这可以通过以下输出图像的快照来验证:
结果2:我们尝试用二进制阈值反转阈值我们的图像。我们期望比阈值更亮的像素会变暗,正如我们在下面的快照中看到的(注意从原始图像,狗狗的舌头和眼睛与图像相比特别亮,这反映在输出图像中)。
源代码:
from __future__ import print_function
import cv2 as cv
import argparse
max_value = 255
max_type = 4
max_binary_value = 255
trackbar_type = 'Type: \n 0: Binary \n 1: Binary Inverted \n 2: Truncate \n 3: To Zero \n 4: To Zero Inverted'
trackbar_value = 'Value'
window_name = 'Threshold Demo'
#等待,直到用户输入阈值,阈值类型(或直到程序退出)
#每当用户改变Trackbars的值时,Threshold_Demo函数(Java中的更新)就会被调用:
def Threshold_Demo(val):
#0: Binary
#1: Binary Inverted
#2: Threshold Truncated
#3: Threshold to Zero
#4: Threshold to Zero Inverted
threshold_type = cv.getTrackbarPos(trackbar_type, window_name)
threshold_value = cv.getTrackbarPos(trackbar_value, window_name)
_, dst = cv.threshold(src_gray, threshold_value, max_binary_value, threshold_type )
cv.imshow(window_name, dst)
parser = argparse.ArgumentParser(description='Code for Basic Thresholding Operations tutorial.')
parser.add_argument('--input', help='Path to input image.', default='stuff.jpg')
args = parser.parse_args()
#加载一个图像。如果是BGR,我们将其转换为灰度。为此,请记住我们可以使用cv::cvtColor函数:
src = cv.imread(cv.samples.findFile(args.input))
if src is None:
print('Could not open or find the image: ', args.input)
exit(0)
# Convert the image to Gray
src_gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
cv.namedWindow(window_name)#创建窗口用来展示结果
#为用户创建2个trackbars来输入用户输入:
#阈值类型:二进制,到零等…
#阈值
cv.createTrackbar(trackbar_type, window_name , 3, max_type, Threshold_Demo)
# Create Trackbar to choose Threshold value
cv.createTrackbar(trackbar_value, window_name , 0, max_value, Threshold_Demo)
# Call the function to initialize
Threshold_Demo(0)
# Wait until user finishes program
cv.waitKey()