python-OpenCV使用滑动条动态控制参数

用opencv时,你一定遇到过手动调参的场景,是不是很麻烦?
我觉得麻烦,用opencv里面自带的滑动条动态控制参数,岂不是很香?

1.创建滑动条

cv2.createTrackbar('Threshold', 'image', 0, 255, updateThreshold)

功能:
绑定滑动条和窗口,定义滚动条的数值。

第一个参数是滑动条的名字,
第二个参数是滑动条被放置的窗口的名字,
第三个参数是滑动条默认值,
第四个参数时滑动条的最大值,
第五个参数时回调函数,每次滑动都会调用回调函数

2. 设置滑动条默认值(其实比较鸡肋,因为在创建滑动条的时候就可以设置默认值了)

cv2.setTrackbarPos('Threshold', 'image', 80)

第一个参数是滑动条的名字,
第二个参数是滑动条被放置的窗口的名字,
第三个参数是滑动条默认值;

3. 获取滑动条的值

threshold = cv2.getTrackbarPos('Threshold', 'image')

第一个参数是滑动条的名字,
第二个参数是滑动条被放置的窗口的名字,

4. 设计回调函数

每次修改滑动条的值后,就会触发回调函数的执行。
回调函数是灵魂,不多说了,看我的例子吧。

5. 完整例子

import cv2

threshold = 80
img_path = r"C:\Users\admin\Desktop\1.jpg"
img = cv2.imread(img_path)
img1 = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
img2 = img1.copy()

# 创建回调函数
def updateThreshold(x):

	# global一定要有的,这样才能修改全局变量
    global threshold, img1, img2
    
    # 得到阈值
    threshold = cv2.getTrackbarPos('Threshold', 'image')
    ret, img1 = cv2.threshold(img2, threshold, 255, 0)
    print("threshold:",threshold)

# 创建窗口和滑动条
cv2.namedWindow('image',cv2.WINDOW_NORMAL)
cv2.createTrackbar('Threshold', 'image', 0, 255, updateThreshold)

# 设置滑动条默认值
cv2.setTrackbarPos('Threshold', 'image', 80)

# 不断刷新显示
while (True):
    cv2.imshow('image', img1)
    if cv2.waitKey(1) == ord('q'):
        break

cv2.destroyAllWindows()

你可能感兴趣的:(opencv,opencv,python,计算机视觉)