原文链接:http://www.juzicode.com/python-error-opencv-createtrackbar-on_change-must-be-callable/
错误提示:
OpenCV createTrackbar()创建滑动条提示TypeError: on_change must be callable
#VX公众号:桔子code / juzicode.com
import cv2
print('cv2.__version__:',cv2.__version__)
bar_name='bar'
win_name='img'
img = cv2.imread('messi5.jpg')
cv2.namedWindow(win_name)
cv2.createTrackbar(bar_name,win_name,0,255,None)
while True:
val=cv2.getTrackbarPos(bar_name,win_name)
img2 = img + val
cv2.imshow(win_name,img2)
key=cv2.waitKey(10)
if key&0xff == 27:break
cv2.destroyAllWindows()
==========运行结果:
cv2.__version__: 4.5.2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-d4a60214a2fc> in <module>
7 img = cv2.imread('messi5.jpg')
8 cv2.namedWindow(win_name)
----> 9 cv2.createTrackbar(bar_name,win_name,0,255,None)
10
11 while True:
TypeError: on_change must be callable
错误原因:
1、createTrackbar()创建滑动条时on_change 参数必须要是可以调用的函数,这里使用的却是None
解决方法:
1、将None修改为可调用的函数,比如系统的内建函数print:
#VX公众号:桔子code / juzicode.com
import cv2
print('cv2.__version__:',cv2.__version__)
bar_name='bar'
win_name='img'
img = cv2.imread('messi5.jpg')
cv2.namedWindow(win_name)
cv2.createTrackbar(bar_name,win_name,0,255,print)
while True:
val=cv2.getTrackbarPos(bar_name,win_name)
img2 = img + val
cv2.imshow(win_name,img2)
key=cv2.waitKey(10)
if key&0xff == 27:break
cv2.destroyAllWindows()
2、将None修改为可调用的函数,可以为自定义的空函数:
#VX公众号:桔子code / juzicode.com
import cv2
print('cv2.__version__:',cv2.__version__)
def fun(a):pass #定义一个什么也不做的空函数
bar_name='bar'
win_name='img'
img = cv2.imread('messi5.jpg')
cv2.namedWindow(win_name)
cv2.createTrackbar(bar_name,win_name,0,255,fun)
while True:
val=cv2.getTrackbarPos(bar_name,win_name)
img2 = img + val
cv2.imshow(win_name,img2)
key=cv2.waitKey(10)
if key&0xff == 27:break
cv2.destroyAllWindows()
扩展内容:
如果本文还没有完全解决你的疑惑,你也可以在微信公众号“桔子code”后台给我留言,欢迎一起探讨交流。