要求:有一个区域,当我手动在图像进行平移和缩放时候,绘制矩形区域要跟随图片一起绘制。这个应用场景典型就是labelme和labelImg里面放大缩小后你绘制矩形框和多边形框会跟随适应图片
main.py
from PyQt5.QtCore import QPoint, QRect, Qt
from PyQt5.QtGui import QPen
class shape(object):
def __init__(self):
self.points = [QPoint(0, 0), QPoint(100, 100)] # 图片真实区域
def calculate_points(self, point, src_w, src_h, width, height):
# 将图片位置转成绘制区域位置
print('真实图片宽src_w={},真实图片src_h={},缩放厚图片w={},缩放后h={}'.format(src_w, src_h, width, height))
new_points = []
for p in self.points:
x, y = p.x(), p.y()
x = point.x() + x * width / src_w
y = point.y() + y * height / src_h
new_points.append(QPoint(x, y))
return new_points
# point是图片左上角位置,可以根据这个计算偏移
def paint(self, painter, point, src_w, src_h, width, height):
new_points = self.calculate_points(point, src_w, src_h, width, height)
rect = QRect(new_points[0], new_points[1])
painter.setPen(QPen(Qt.red, 2, Qt.SolidLine))
painter.drawRect(rect)
shape.py
from PyQt5.QtCore import QPoint, QRect, Qt
from PyQt5.QtGui import QPen
class shape(object):
def __init__(self):
self.points = [QPoint(0, 0), QPoint(100, 100)] # 图片真实区域
def calculate_points(self, point, src_w, src_h, width, height):
# 将图片位置转成绘制区域位置
print('真实图片宽src_w={},真实图片src_h={},缩放厚图片w={},缩放后h={}'.format(src_w, src_h, width, height))
new_points = []
for p in self.points:
x, y = p.x(), p.y()
x = point.x() + x * width / src_w
y = point.y() + y * height / src_h
new_points.append(QPoint(x, y))
return new_points
# point是图片左上角位置,可以根据这个计算偏移
def paint(self, painter, point, src_w, src_h, width, height):
new_points = self.calculate_points(point, src_w, src_h, width, height)
rect = QRect(new_points[0], new_points[1])
painter.setPen(QPen(Qt.red, 2, Qt.SolidLine))
painter.drawRect(rect)
main.py和shape.py处于同一个目录即可
参考文献:
PYQT5实现图片显示、通过滚轮缩放图片、通过鼠标拖动图片移动,搞懂所有细节_python 生成可缩放可拖拽的图表_railvision的博客-CSDN博客