坐标不会通过python中的mousecallback函数传递到主循环

时间:2018-09-21 15:08:59

标签: python python-3.x opencv3.3

我是python的新手,我想学习python。下面的代码与我用C ++编写的代码相同。该代码在C ++中可以正常工作,但在python中则不能。 我担心的是,当我按住鼠标左键时,它应该在图像上画一个圆,但事实并非如此。 任何帮助将不胜感激。

代码:

import cv2
import numpy as np

class mouse_state:
    def __init__(self):
        self.position = [-1,-1]
        self.left_button_held = False
        self.left_button_clicked = False

    def new_iteration():
        left_button_clicked = False


def mouse_callback(event,x,y,flag,param):
    param = mouse_state()

    if event==cv2.EVENT_LBUTTONDOWN:
        param.position = (x,y)
        param.left_button_held = True
        print('LMB Down @ ',param.position)
    elif event==cv2.EVENT_LBUTTONUP:
        param.position = (x,y)
        param.left_button_held = False
        param.left_button_clicked = True
        print('LMB Up @ ',param.position)
    elif ((flag==cv2.EVENT_FLAG_LBUTTON) & (event==cv2.EVENT_MOUSEMOVE)):
        param.position = (x,y)
        print('LMB Held, Mouse Moved To',param.position)

cap = cv2.VideoCapture(0)
windowName = 'Feed'
cv2.namedWindow(windowName)
ms = mouse_state()
cv2.setMouseCallback(windowName,mouse_callback,ms)

while 1:
    ret, frame = cap.read()
    (height, width) = (frame.shape[0], frame.shape[1])

    if (ms.left_button_clicked==True | ms.left_button_held==True):
        cv2.circle(frame,ms.position,3,(0,0,255))
        cv2.circle(frame,ms.position,10,(255,0,0),2)
        print('Current Position ',ms.position)

    ms.new_iteration

    cv2.imshow(windowName,frame)
    w = cv2.waitKey(1) & 0xFF
    if w == ord('q'):
        break

cv2.destroyAllWindows()

0 个答案:

没有答案