Python错误集锦:OpenCV创建进度条createTrackbar()后拖动进度条提示TypeError: fun() takes 0 positional arguments but 1 was given

原文链接:http://www.juzicode.com/archives/6453

 

错误提示:

OpenCV用创建进度条createTrackbar()能显示图像,拖动进度条时提示TypeError: fun() takes 0 positional arguments but 1 was given

#VX公众号:桔子code / juzicode.com
import cv2
print('cv2.__version__:',cv2.__version__)

bar_name='bar'
win_name='img'
img = cv2.imread('messi5.jpg')

def fun():
    val=cv2.getTrackbarPos(bar_name,win_name)
    img2 = img + val
    cv2.imshow(win_name,img2)

cv2.namedWindow(win_name)
cv2.createTrackbar(bar_name,win_name,0,255,fun)
cv2.imshow(win_name,img)
cv2.waitKey(0)
cv2.destroyAllWindows()
==========运行结果:
cv2.__version__: 4.5.2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
TypeError: fun() takes 0 positional arguments but 1 was given
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
TypeError: fun() takes 0 positional arguments but 1 was given

 

错误原因:

1、createTrackbar()调用的回调函数必须至少带一个入参,即使该入参不使用。

 

解决方法:

1、回调函数增加一个入参a:

==========运行结果:
#VX公众号:桔子code / juzicode.com
import cv2
print('cv2.__version__:',cv2.__version__)

bar_name='bar'
win_name='img'
img = cv2.imread('messi5.jpg')

#def fun():
def fun(a): #增加一个入参,即使不使用该入参
    val=cv2.getTrackbarPos(bar_name,win_name)
    img2 = img + val
    cv2.imshow(win_name,img2)

cv2.namedWindow(win_name)
cv2.createTrackbar(bar_name,win_name,0,255,fun)
cv2.imshow(win_name,img)
cv2.waitKey(0)
cv2.destroyAllWindows()

扩展内容:

  1. Opencv-Python教程

 


 

如果本文还没有完全解决你的疑惑,你也可以在微信公众号“桔子code”后台给我留言,欢迎一起探讨交流。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注