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。我查看了mousecallback函数的示例代码,该示例代码正常工作。然后,如上所述,我用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