pyqt5 graphicsView 加载显示图片,在图片上鼠标框选红色矩形并返回矩形在图片上的坐标
时间: 2023-12-22 07:05:44 浏览: 107
下面是一个使用 PyQt5 的 QGraphicsView 实现了在图片上鼠标框选红色矩形并返回矩形在图片上的坐标的示例:
```python
import sys
from PyQt5.QtCore import Qt, QRectF
from PyQt5.QtGui import QPixmap, QPainter, QBrush, QColor
from PyQt5.QtWidgets import QApplication, QGraphicsView, QGraphicsScene, QGraphicsPixmapItem
class ImageViewer(QGraphicsView):
def __init__(self, parent=None):
super().__init__(parent)
self.setScene(QGraphicsScene(self))
self.image_item = QGraphicsPixmapItem()
self.select_rect_item = SelectRectItem()
self.scene().addItem(self.image_item)
self.scene().addItem(self.select_rect_item)
self.start_point = None
self.end_point = None
self.rect_on_image = None
def set_image(self, image):
pixmap = QPixmap.fromImage(image)
self.image_item.setPixmap(pixmap)
self.setSceneRect(pixmap.rect())
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.start_point = self.mapToScene(event.pos())
self.select_rect_item.set_rect(QRectF(self.start_point, QSizeF()))
self.select_rect_item.setVisible(True)
event.accept()
else:
super().mousePressEvent(event)
def mouseMoveEvent(self, event):
if self.start_point is not None:
self.end_point = self.mapToScene(event.pos())
rect = QRectF(self.start_point, self.end_point).normalized()
self.select_rect_item.set_rect(rect)
event.accept()
else:
super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
self.end_point = self.mapToScene(event.pos())
rect = QRectF(self.start_point, self.end_point).normalized()
self.rect_on_image = rect.intersected(self.image_item.boundingRect())
x, y, w, h = self.rect_on_image.getRect()
print("Selected rectangle on image: ({}, {}, {}, {})".format(x, y, w, h))
self.select_rect_item.setVisible(False)
event.accept()
else:
super().mouseReleaseEvent(event)
class SelectRectItem(QGraphicsPixmapItem):
def __init__(self):
super().__init__()
self.setVisible(False)
self.setZValue(1)
self.setOpacity(0.5)
self.setBrush(QBrush(QColor(255, 0, 0)))
def set_rect(self, rect):
self.setRect(rect)
if __name__ == '__main__':
app = QApplication(sys.argv)
viewer = ImageViewer()
image = QPixmap('image.jpg').toImage()
viewer.set_image(image)
viewer.show()
sys.exit(app.exec_())
```
这个示例程序实现了一个名为 ImageViewer 的类,继承自 QGraphicsView。该类可以用于显示图片,并在图片上鼠标框选红色矩形,返回矩形在图片上的坐标。
其中,`SelectRectItem` 类继承自 `QGraphicsPixmapItem`,用于显示鼠标框选的红色矩形。`ImageViewer` 类的 `mousePressEvent`、`mouseMoveEvent` 和 `mouseReleaseEvent` 方法分别处理鼠标按下、移动和释放事件,实现了在图片上鼠标框选红色矩形的功能。`ImageViewer` 类的 `set_image` 方法用于设置要显示的图片。
在程序运行时,可以通过 `viewer.set_image(image)` 方法设置要显示的图片,然后在该图片上用鼠标框选红色矩形,程序会输出矩形在图片上的坐标。
阅读全文