【OpenCV入门学习--python】使用cv::threshold函数执行阈值

例子源于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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值