在类里使用python opencv实现鼠标区域截图
时间: 2024-05-08 12:19:56 浏览: 102
可以使用以下代码实现:
```python
import cv2
class MouseScreenShot():
def __init__(self):
self.start_x = None
self.start_y = None
self.end_x = None
self.end_y = None
self.drawing = False
def capture(self):
cv2.namedWindow('image')
cv2.setMouseCallback('image', self.draw_rect)
while True:
image = cv2.imread("test.png") # 此处为截取电脑屏幕可替换为其他图像路径
cv2.imshow('image', image)
if cv2.waitKey(1) == ord('c'):
if self.start_x is not None and self.start_y is not None and self.end_x is not None and self.end_y is not None:
x1 = min(self.start_x, self.end_x)
y1 = min(self.start_y, self.end_y)
x2 = max(self.start_x, self.end_x)
y2 = max(self.start_y, self.end_y)
roi = image[y1:y2, x1:x2]
cv2.imwrite('capture.png', roi)
break
cv2.destroyAllWindows()
def draw_rect(self, event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
self.drawing = True
self.start_x, self.start_y = x, y
self.end_x, self.end_y = x, y
elif event == cv2.EVENT_MOUSEMOVE:
if self.drawing:
self.end_x, self.end_y = x, y
elif event == cv2.EVENT_LBUTTONUP:
self.drawing = False
```
在代码中,通过使用cv2.namedWindow() 和cv2.setMouseCallback()函数,程序将窗口('image')进行注册,并将鼠标的事件与函数self.draw_rect()进行绑定,从而实现在鼠标移动时的图像显示。通过cv2.waitKey(1)监听用户的行为,当用户按下 'c' 键时,将鼠标所选区域的像素点截取并保存,最后退出程序。
阅读全文