3

【OpenCV-Python】滑动条的创建和使用(createTrackbar())

 1 year ago
source link: https://blog.51cto.com/domi/5929424
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

【OpenCV-Python】滑动条的创建和使用(createTrackbar())

精选 原创

domi+1 2022-12-12 12:30:40 博主文章分类:python ©著作权

文章标签 回调函数 滑动条 滑块 文章分类 Python 编程语言 yyds干货盘点 阅读数169

✅作者简介:热爱科研的算法开发者,Python、Matlab项目可交流、沟通、学习。

🍎个人主页:算法工程师的学习日志

今天在做项目的时候,遇到一个参数的选择,需要实时看参数变化对结果影响,查阅资料看到OpenCV的滑动条,故分享一篇文章

滑动条(Trackbar)是一种可以动态调节参数的工具,它依附于窗口而存在。

createTrackbar() 这个函数用于创建一个可以调整数值的滑动条,并将滑动条附加到指定的窗口上。

函数功能:创建trackbar并添加到指定窗口

函数原型:

intcvCreateTrackbar(   const char* trackbar_name,   const char* window_name,   int* value,   intcount,   CvTrackbarCallback on_change );

函数说明:

第一个参数表示该trackbar的名称。

第二个参数表示窗口名称,该trackbar将显示在这个窗口内。

第三个参数表示创建时滑块的位置。

第四个参数表示滑块位置的最大值,最小值固定为0。

第五个参数表示回调函数。当滑块位置有变化时,系统会调用该回调函数。

注:被创建的trackbar默认显示在指定窗口的顶端,可以通过函数cvGetTrackbarPos()来获取trackbar显示的位置信息,以及通过函数cvSetTrackbarPos()来重新设置trackbar的显示位置。

CvTrackbarCallback

函数功能:cvCreateTrackbar()函数所使用的回调函数

函数定义:

typedef void (CV_CDECL *CvTrackbarCallback)(int pos)

函数说明:

当trackbar位置被改变的时,系统会调用这个回调函数,并将参数pos设置为表示trackbar位置的数值。

在这里通过一个Canny算子参数作为例子分享。

import cv2


def CannyThreshold(lowThreshold):
detected_edges = cv2.GaussianBlur(gray, (3, 3), 0)
detected_edges = cv2.Canny(detected_edges,
lowThreshold,
lowThreshold * ratio,
apertureSize=kernel_size)
dst = cv2.bitwise_and(img, img, mask=detected_edges)
cv2.imshow('canny demo', dst)


lowThreshold = 0
max_lowThreshold = 100
ratio = 6
kernel_size = 3


img = cv2.imread('./0.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.namedWindow('canny demo')
cv2.createTrackbar('Min threshold', 'canny demo', lowThreshold, max_lowThreshold, CannyThreshold)
CannyThreshold(0)
if cv2.waitKey(0) == 27:
cv2.destroyAllWindows()
【OpenCV-Python】滑动条的创建和使用(createTrackbar())_回调函数
【OpenCV-Python】滑动条的创建和使用(createTrackbar())_回调函数_02

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK