0

我是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()
4

0 回答 0