TypeError:函数只接受3个参数(给定1个),python



我试图为轮廓创建一个轨迹条,但当我运行代码时,我得到了这个错误:

TypeError: thresh_callback() takes exactly 3 arguments (1 given)

代码:

def thresh_callback(thresh,blur,img):
    edges = cv.Canny(blur,thresh,thresh*2)
    drawing = np.zeros(img.shape,np.uint8)     # Image to draw the contours
    contours,hierarchy = cv.findContours(edges,cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE)
    for cnt in contours:
        color = np.random.randint(0,255,(3)).tolist()  # Select a random color
        cv.drawContours(drawing,[cnt],0,color,2)
        cv.imshow('output',drawing)
    cv.imshow('input',img)
def Pics():
    vc = cv.VideoCapture(2)
    retVal, frame = vc.read();
    while True :
        if frame is not None:
            imgray = cv.cvtColor(frame,cv.COLOR_BGR2GRAY)
            blur = cv.GaussianBlur(imgray,(5,5),0)
            thresh = 100
            max_thresh = 255
            cv.createTrackbar('canny thresh:','input',thresh,max_thresh,thresh_callback)
            thresh_callback(thresh,blur,frame)
        rval, frame = vc.read()
        if cv.waitKey() & 0xFF == 27:
            break
    cv1.DestroyAllWindows()

您正在将thresh_callback传递到cv.createTrackbar,而正是在其中的某个位置,您的函数只使用一个参数进行调用。我假设您仍然希望使用您在代码中确定的blurframe,因此尝试使用functools.partial为您设置这些:

import functools
...
        partialed_callback = functools.partial(thresh_callback, blur=blur, img=frame)
        cv.createTrackbar('canny thresh:','input',thresh,max_thresh,partialed_callback)

这将创建一个已设置blurframe的函数版本,因此将使用循环中定义的frameblur以及createTrackbar中提供的thresh来调用thresh_callback函数。

此外,您可能不希望在调用cv.createTrackbar之后的线路中调用thresh_callback(thresh,blur,frame),因为这意味着它会被调用两次,第二次总是使用thresh=100

您正在将函数thresh_callback作为回调传递给cv.createTrackbar(方法。看起来这个方法需要一个单参数函数来调用某个事件。

相关内容

最新更新