python - setMouseCallback onmouse 未定义
问题描述
def __init__(self):
super(FindWindow, self).__init__()
uic.loadUi('D:/Python/Projects/Sensor/roi.ui', self)
self.init_ui()
def init_ui(self):
self.pushButton_roi.clicked.connect(self.open_picture)
def onMouse(event, x, y, flags, param):
global drawing, ix, iy
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
ix, iy = x, y
elif event == cv2.EVENT_MOUSEMOVE:
if drawing:
cv2.rectangle(param, (ix, iy), (x, y), (0, 0, 0), -1)
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
cv2.rectangle(param, (ix, iy), (x, y), (0, 0, 0), -1)
def open_picture(self, what):
img = cv2.imread(file_directory)
temp = what
print(temp)
cv2.namedWindow('paint')
cv2.setMouseCallback('paint', onMouse, param=img)
while True:
cv2.imshow('paint', img)
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
我正在尝试在 pyqt 上使用 mousecallback 函数来设置图片的 ROI。我查看了鼠标回调函数的示例代码,示例代码没有问题。然后,我用 pyqt 实现了它,如上所示,现在它给了我一个错误,如下所示。
Traceback (most recent call last):
File "D:/Python/Projects/Sensor/one_detect_main.py", line 49, in open_picture
cv2.setMouseCallback('paint', onMouse, param=img)
NameError: name 'onMouse' is not defined
我不知道示例代码和我的代码之间有什么区别。这是示例代码:
import numpy as np
import cv2
from random import shuffle
import math
mode, drawing = True, False
ix, iy = -1, -1
B = [i for i in range(256)]
G = [i for i in range(256)]
R = [i for i in range(256)]
def onMouse(event, x, y, flags, param):
global ix, iy, drawing, mode, B, G, R
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
ix, iy = x, y
shuffle(B), shuffle(G), shuffle(R)
elif event == cv2.EVENT_MOUSEMOVE:
if drawing:
if mode:
cv2.rectangle(param, (ix, iy), (x, y), (B[0], G[0], R[0]), -1)
else:
r = (ix-x) ** 2 + (iy-y)**2
r = int(math.sqrt(r))
cv2.circle(param, (ix, iy), r, (B[0], G[0], R[0]), -1)
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
if mode:
cv2.rectangle(param, (ix, iy), (x, y), (B[0], G[0], R[0]), -1)
else:
r = (ix-x)**2 + (iy-y)**2
r = int(math.sqrt(r))
cv2.circle(param, (ix, iy), r, (B[0], G[0], R[0]), -1)
def mouseBrush():
global mode
img = np.zeros((512, 512, 3), np.uint8)
cv2.namedWindow('paint')
cv2.setMouseCallback('paint', onMouse, param=img)
while True:
cv2.imshow('paint', img)
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
elif k == ord('m'):
mode = not mode
cv2.destroyAllWindows()
mouseBrush()
解决方案
从示例代码中,onMouse 是他们定义的一个函数,它接收一个事件和其他参数。通过使用 mouseCallBack 函数,只要鼠标做某事,onMouse 就会被调用。
def onMouse(event, x, y, flags, param):
# handle the event here
另外,请注意在 onMouse 内部他们正在处理不同的事件
if event == cv2.EVENT_LBUTTONDOWN:
# do something
elif event == cv2.EVENT_MOUSEMOVE:
# do something
推荐阅读
- python - 使用 Boto3 以有效的方式将项目行添加到 DynamoDB
- macos - 通过 brew 安装时 gcc 配置选项的权衡
- django - Django中的强制模型字段
- python - Code Wars 中的数组交换和反转问题
- python - Python Google Cloud Function 不会安装 Pandas
- java - java Stack作业将数字放在堆栈上
- javascript - 如何左连接两个外部 JSON url
- linux - 无法连接到在 droplet 中运行的 neo4j,但使用 lynx 导航到 localhost:7474 有效,配置了 ufw 和数字海洋防火墙
- java - Java 和 MySQL - “无法识别的语句”
- python - 如何在 Flask 中处理意外的 url 参数