【发布时间】:2020-06-16 02:26:55
【问题描述】:
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 上使用鼠标回调函数来设置图片的 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()
【问题讨论】:
-
这个例子对你有用吗?
-
尽管第一段代码被从上下文中删除(因此不是 minimal reproducible example),事实上有一个
__init__并且所有其他功能比onMouse有self作为第一个参数表明所有这些都是类定义的一部分......这可以解释为什么试图引用onMouse好像它是独立的是行不通的。 -
@DanMašek 你是对的。我的问题已通过将 self 添加到 onMouse 来解决。
标签: python opencv pyqt signals