目标:
首先导入需要的库,包括opencv-python库
import cv2 as cv
接下来是trackbar的回调函数,这里什么都不需要做pass就可以了
def nothing(x):
pass
然后设置一些全局参数,方便对经常改动参数进行修改:
track_win_name = "trackbar window"
pic_path = "wechat.png"
读取图片,并将图片进行灰度化,并给窗口起个名字,方便后面使用:
img = cv.imread(pic_path, 1)
img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.namedWindow(track_win_name)
接下来是代码的重点部分,使用函数cv.crateTrackbar(para1, para2, para3, para4, para5)创建两个trackbar,分别对应阈值的最小值和最大值,其中参数的详尽含义如下:
# create trackbars for threshold change
cv.createTrackbar('thres_min', track_win_name, 0, 255, nothing)
cv.createTrackbar('thres_max', track_win_name, 255, 255, nothing)
然后是一个while循环,根据滑块的移动动态刷新图像结果,按下esc键退出窗口。
while(1):
# your code is here
k = cv.waitKey(1) & 0xFF
if k == 27:
break
cv.destroyAllWindows()
最后是循环体中的主要代码:
thres_min = cv.getTrackbarPos('thres_min', track_win_name)
thres_max = cv.getTrackbarPos('thres_max', track_win_name)
ret, img_after_interaction = cv.threshold(img, thres_min, thres_max, cv.THRESH_BINARY)
cv.imshow(track_win_name, img_after_interaction)
读取trackbar当前位置对应的数值,并将其作为参数传入到阈值函数中,然后用opencv显示调整后的图像结果。
import cv2 as cv
def nothing(x):
pass
# settings
track_win_name = "trackbar window"
pic_path = "wechat.png"
# read picture
img = cv.imread(pic_path, 1)
img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.namedWindow(track_win_name)
# create trackbars for threshold change
cv.createTrackbar('thres_min', track_win_name, 0, 255, nothing)
cv.createTrackbar('thres_max', track_win_name, 255, 255, nothing)
# dynamic update
while(1):
# get current positions of four trackbars
thres_min = cv.getTrackbarPos('thres_min', track_win_name)
thres_max = cv.getTrackbarPos('thres_max', track_win_name)
ret, img_after_interaction = cv.threshold(img, thres_min, thres_max, cv.THRESH_BINARY)
cv.imshow(track_win_name, img_after_interaction)
k = cv.waitKey(1) & 0xFF
if k == 27:
break
cv.destroyAllWindows()