【问题标题】:Pyqt get pixel position and value when mouse click on the image当鼠标单击图像时,Pyqt 获取像素位置和值
【发布时间】:2011-03-31 02:11:10
【问题描述】:

我想知道如何通过鼠标单击图像 (QImge) 来选择像素并获取像素位置和值。

谢谢

【问题讨论】:

  • 你有可以运行的例子吗?

标签: python image pyqt selection pixel


【解决方案1】:

首先您必须绘制图像。你可以这样做我制作一个QLabel 小部件并调用setPixmap。在执行此操作之前,您需要将QImage 转换为QPixmap(您可以使用QPixmap.fromImage(img))。

您可以通过继承QImage 并拦截mousePressEvent 来获得鼠标点击。使用QImage.pixel() 查找像素值。

【讨论】:

  • 有没有可以在 python 中运行的简短完整示例?好像没看懂。
【解决方案2】:
self.image = QLabel()
self.image.setPixmap(QPixmap("C:\\myImg.jpg"))
self.image.setObjectName("image")
self.image.mousePressEvent = self.getPos

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

【讨论】:

    【解决方案3】:

    这个问题很老,但对于像我一样来到这里的每个人来说,这是我基于 Jareds 回答的解决方案:

    self.img = QImage('fname.png')
    pixmap = QPixmap(QPixmap.fromImage(self.img))
    img_label = QLabel()
    img_label.setPixmap(pixmap)
    img_label.mousePressEvent = self.getPixel
    
    def self.getPixel(self, event):
        x = event.pos().x()
        y = event.pos().y()
        c = self.img.pixel(x,y)  # color code (integer): 3235912
        # depending on what kind of value you like (arbitary examples)
        c_qobj = QColor(c)  # color object
        c_rgb = QColor(c).getRgb()  # 8bit RGBA: (255, 23, 0, 255)
        c_rgbf = QColor(c).getRgbf()  # RGBA float: (1.0, 0.3123, 0.0, 1.0)
        return x, y, c_rgb
    

    确保标签的大小与图像的大小相匹配,否则需要将 x 和 y 鼠标坐标转换为图像坐标。而且我想也可以直接在像素图上使用.pixel() 方法,但在我的情况下,QImage 对象似乎表现更好。

    【讨论】:

    • 如果图像是灰度格式,如何获得强度?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 2020-11-30
    • 2015-04-09
    相关资源
    最近更新 更多