Pyqt gets the position and value of the pixel when you click on the image

I would like to know how I can select a pixel with a click in the image (QImge) and get the position and value of the pixel.

thank

+3
source share
3 answers
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() 
+5
source

You must draw an image first. You can do this by creating a widget QLabeland calling setPixmap. You need to convert QImageto QPixmapbefore you do this (you can use QPixmap.fromImage(img)).

You can get mouse clicks by subclassing QImageand intercepting mousePressEvent. Find the pixel value with QImage.pixel().

+1

, , , , , :

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

Make sure the size of the label matches the size of the image, otherwise the x and y coordinates of the mouse must be converted to the coordinates of the image. And I think it is also possible to use the method .pixel()directly on pixmap, but the QImage object seems to work better in my case.

0
source

Source: https://habr.com/ru/post/1760129/


All Articles