繁体   English   中英

当鼠标点击图像时,Pyqt获取像素位置和值

[英]Pyqt get pixel position and value when mouse click on the image

我想知道如何在图像中单击鼠标(QImge)来选择像素,并获得像素位置和值。

谢谢

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() 

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

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

这个问题已经过时了,但对于像我这样来到这里的每个人来说,这是基于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对象似乎表现得更好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM