我正在将QGraphicsItem
转换为位于QGraphicsScene
位置的光栅化遮罩。我使用这些遮罩对视频进行进一步处理(取遮罩内的平均强度)。为了实现这一点,我在一个QImage
上一个接一个地绘制场景中的每个项目,该项目的大小刚好足以包围该项目。一切正常,但场景中的项目消失了。这是因为当我在QImage
上绘制笔时,我正在从项目中移除笔。完成后,我将原始笔放回原处,但这些项目不会重新出现在场景中。
如何“刷新”场景以使项目重新出现,或者,如何防止项目完全消失
我真的找不到任何人遇到这个问题。所以也许我只是在做一些根本错误的事情。欢迎提出任何建议
这是我的密码:
class MyThread(QtCore.QThread):
def __init__(self, scene):
super().__init__()
self.scene = scene
def run(self):
for item in self.scene.items():
# Render the ROI item to create a rasterized mask.
qimage = self.qimage_from_shape_item(item)
# do some stuff
@staticmethod
def qimage_from_shape_item(item: QtWidgets.QAbstractGraphicsShapeItem) -> QtGui.QImage:
# Get items pen and brush to set back later.
pen = item.pen()
brush = item.brush()
# Remove pen, set brush to white.
item.setPen(QtGui.QPen(QtCore.Qt.NoPen))
item.setBrush(QtCore.Qt.white)
# Determine the bounding box in pixel coordinates.
top = int(item.scenePos().y() + item.boundingRect().top())
left = int(item.scenePos().x() + item.boundingRect().left())
bottom = int(item.scenePos().y() + item.boundingRect().bottom()) + 1
right = int(item.scenePos().x() + item.boundingRect().right()) + 1
size = QtCore.QSize(right - left, bottom - top)
# Initialize qimage, use 8-bit grayscale.
qimage = QtGui.QImage(size, QtGui.QImage.Format_Grayscale8)
qimage.fill(QtCore.Qt.transparent)
painter = QtGui.QPainter(qimage)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
# Offset the painter to paint item in its correct pixel location.
painter.translate(item.scenePos().x() - left, item.scenePos().y() - top)
# Paint the item.
item.paint(painter, QtWidgets.QStyleOptionGraphicsItem())
# Set the pen and brush back.
item.setPen(pen)
item.setBrush(brush)
# Set the pixel coordinate offset of the item to the QImage.
qimage.setOffset(QtCore.QPoint(left, top))
return qimage
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
widget = QtWidgets.QWidget()
layout = QtWidgets.QVBoxLayout(widget)
view = QtWidgets.QGraphicsView()
layout.addWidget(view)
scene = QtWidgets.QGraphicsScene()
view.setScene(scene)
thread = MyThread(scene)
view.setFixedSize(400, 300)
scene.setSceneRect(0, 0, 400, 300)
rect_item = QtWidgets.QGraphicsRectItem()
p = QtCore.QPointF(123.4, 56.78)
rect_item.setPos(p)
r = QtCore.QRectF(0., 0., 161.8, 100.)
rect_item.setRect(r)
scene.addItem(rect_item)
button = QtWidgets.QPushButton("Get masks")
layout.addWidget(button)
button.clicked.connect(thread.start)
widget.show()
sys.exit(app.exec_())
问题是“只能在主线程上创建和使用GUI小部件”,请参阅this SO answer here中的更多信息
我解决这个问题的方法是将GUI交互部分(即来自_shape_item()的qimage_)从线程中取出,并在主循环中处理它。我想我直接使用这些项目还是不太好,尽管暂时设置NoPen没有任何可见的闪烁效果
另一种可能是使用QGraphicsScene::render;但是,我不知道如何在不与场景中的其他项目交互的情况下逐个渲染项目
相关问题 更多 >
编程相关推荐