【问题标题】:Coordinates of an image PyQt图像 PyQt 的坐标
【发布时间】:2020-12-02 08:06:55
【问题描述】:

我正在制作一个应用程序,我需要在鼠标点击时提取图像的坐标。 图片的分辨率为 1920x1080,我的笔记本电脑屏幕的分辨率为 1366x768

我在这里面临两个问题。 1)图像在我的笔记本电脑上以裁剪的方式显示。 2) 每当我单击鼠标按钮时,它都会给我笔记本电脑屏幕的坐标,而不是图像的坐标。

我严格来说不必调整图像大小,其次,在我的最终项目中,图像不会占据整个屏幕,它只会占据屏幕的一部分。我正在寻找一种方法来显示整个图像以及获取相对于图像的坐标。

from PyQt4 import QtGui, QtCore
import sys


class Window(QtGui.QLabel):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.setPixmap(QtGui.QPixmap('image.jpg'))
        self.mousePressEvent = self.getPos

    def getPos(self , event):
        x = event.pos().x()
        y = event.pos().y()
        self.point = (x, y)
        print(self.point)


if __name__ == "__main__":
    app = QtGui.QApplication([])
    w = Window()
    w.showMaximized()
    sys.exit(app.exec_())

这是一张图片,可以让您了解我的最终项目。

【问题讨论】:

  • 嗯。我不明白。 1.你说“在我的最终项目中,图像不会占据整个屏幕”,那你为什么抱怨裁剪的图像? 2. mousePressEvent.pos() always 相对于小部件,而不是相对于屏幕,我不明白你为什么说它给你屏幕坐标,因为它没有。跨度>
  • @musicamante 我分享了一张图片,可以让您了解我的最终项目。
  • @musicamante 1. 我的意思是图像不应该看起来好像被裁剪了。我需要完整的图像,但该图像不会占据整个屏幕,因为该图像会显示一些附加信息(就像上图一样)。 2. 我希望图像左上角的坐标为 (0, 0) 和右下角的坐标为 (1920, 1080),也许mousePressEvent.pos() 不是在这里使用的正确函数,但我想我现在已经说得够清楚了。
  • 所以你希望图像被缩放。它应该保持比例吗?
  • @musicamante 是的,应该。

标签: python pyqt pyqt4


【解决方案1】:

您应该使用 QGraphicsView 而不是使用 QLabel,因为它具有易于缩放和易于处理坐标的优点

from PyQt5 import QtCore, QtGui, QtWidgets


class GraphicsView(QtWidgets.QGraphicsView):
    def __init__(self, parent=None):
        super().__init__(parent)
        scene = QtWidgets.QGraphicsScene(self)
        self.setScene(scene)

        self._pixmap_item = QtWidgets.QGraphicsPixmapItem()
        scene.addItem(self.pixmap_item)

    @property
    def pixmap_item(self):
        return self._pixmap_item

    def setPixmap(self, pixmap):
        self.pixmap_item.setPixmap(pixmap)

    def resizeEvent(self, event):
        self.fitInView(self.pixmap_item, QtCore.Qt.KeepAspectRatio)
        super().resizeEvent(event)

    def mousePressEvent(self, event):
        if self.pixmap_item is self.itemAt(event.pos()):
            sp = self.mapToScene(event.pos())
            lp = self.pixmap_item.mapFromScene(sp).toPoint()
            print(lp)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = GraphicsView()
    w.setPixmap(QtGui.QPixmap("image.jpg"))
    w.showMaximized()
    sys.exit(app.exec_())

【讨论】:

  • 它可以正常工作还是视频/相机也可以?如果不是,那么我必须做出哪些改变?
  • 通常我不会回答与我的答案无关的问题,但我认为他们会回答(有一些限制),例如此代码:github.com/eyllanesc/QtExamples/tree/master/others/… 与您想要的类似。我不会继续回答不表明我当前代码有问题的其他类型的问题
  • 我要添加一些建议,因为该程序可能会多次使用setPixmap()。在setPixmap 中(在为项目设置像素图之后)最好添加self.setSceneRect(self.pixmap_item.sceneBoundingRect()) 和另一个对self.fitInView(self.pixmap_item, QtCore.Qt.KeepAspectRatio) 的调用。另外,为了避免默认的图形视图边框,self.setFrameShape(0)也可以添加到__init__中。
猜你喜欢
  • 1970-01-01
  • 2011-11-18
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 2015-08-10
  • 2023-04-01
  • 1970-01-01
相关资源
最近更新 更多