pyqt5 graphicsView 加载显示图片,并可以进行修改图片放缩尺度,在图片上鼠标框选红色矩形,矩形可以进行修改尺寸,并返回矩形在图片上的坐标
时间: 2024-02-23 14:58:36 浏览: 167
好的,这是一个比较复杂的问题,需要结合PyQt5中的GraphicsView、QPixmap、QGraphicsRectItem等类来实现。下面是一个简单的实现示例代码,供参考:
```python
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class ImageView(QGraphicsView):
def __init__(self, parent=None):
super(ImageView, self).__init__(parent)
self.image = QPixmap("test.jpg") # 加载图片
self.scene = QGraphicsScene(self)
self.setScene(self.scene)
# 显示图片
self.pixmap_item = QGraphicsPixmapItem(self.image)
self.scene.addItem(self.pixmap_item)
# 设置图片缩放
self.setDragMode(QGraphicsView.ScrollHandDrag)
self.setRenderHint(QPainter.Antialiasing)
self.setRenderHint(QPainter.SmoothPixmapTransform)
self.setRenderHint(QPainter.HighQualityAntialiasing)
self.setInteractive(True)
self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
# 鼠标框选矩形
self.rect_item = QGraphicsRectItem()
self.rect_item.setPen(QPen(Qt.red))
self.rect_item.setBrush(QBrush(Qt.red, Qt.Dense4Pattern))
self.rect_item.setZValue(1)
self.scene.addItem(self.rect_item)
# 信号槽连接
self.selectionChanged.connect(self.on_selection_changed)
self.rect_item.mousePressEvent = self.on_rect_mouse_press
self.rect_item.mouseMoveEvent = self.on_rect_mouse_move
self.rect_item.mouseReleaseEvent = self.on_rect_mouse_release
def on_selection_changed(self):
# 获取当前选中的区域
items = self.scene.selectedItems()
if len(items) == 1 and isinstance(items[0], QGraphicsRectItem):
self.rect_item.setRect(items[0].rect())
else:
self.rect_item.setRect(QRectF())
def on_rect_mouse_press(self, event):
# 记录鼠标按下时的位置
self.last_pos = self.mapToScene(event.pos())
def on_rect_mouse_move(self, event):
# 计算矩形大小
pos = self.mapToScene(event.pos())
rect = QRectF(self.last_pos, pos).normalized()
self.rect_item.setRect(rect)
def on_rect_mouse_release(self, event):
# 计算矩形在图片上的坐标
rect = self.rect_item.rect()
scale = self.transform().m11()
rect = QRectF(rect.left() / scale, rect.top() / scale,
rect.width() / scale, rect.height() / scale)
rect = rect.intersected(QRectF(QPointF(0, 0), self.image.size()))
print(rect)
if __name__ == '__main__':
app = QApplication(sys.argv)
view = ImageView()
view.show()
sys.exit(app.exec_())
```
这段代码实现了以下功能:
1. 加载图片并显示在GraphicsView中;
2. 支持鼠标拖动来放缩图片;
3. 支持鼠标框选红色矩形,并且可以修改矩形的尺寸;
4. 计算矩形在图片上的坐标,并输出到控制台。
需要注意的是,代码中矩形的坐标是相对于图片的,如果需要得到绝对坐标,还需要考虑图片在GraphicsView中的位置和缩放比例。
阅读全文