Pyqt get pixel position and value when mouse click on the image
Asked Answered
S

3

9

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

Thanks

Slimy answered 17/8, 2010 at 16:5 Comment(1)
Do you have any example that can run?Lac
A
16
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() 
Anagnorisis answered 1/6, 2011 at 9:54 Comment(0)
D
4

This question is old but for everybody getting here, like me, this is my solution based on Jareds answer:

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 mouse coords need to be transformed to image coords. And I guess it's also possible to use the .pixel() method directly on a pixmap as well, but the QImage object seems to perform better in my case.

Descartes answered 12/3, 2018 at 13:4 Comment(1)
What if the image was in gray-scale format, how can I get the intensity?Stores
I
2

First you have to draw the image. You can do this my making a QLabel widget and call setPixmap. You need to convert your QImage to QPixmap before doing this (you can use QPixmap.fromImage(img)).

You can get mouse clicks by subclassing the QImage and intercepting mousePressEvent. Look up the pixel value with QImage.pixel().

Ilianailine answered 22/8, 2010 at 21:28 Comment(1)
Is there any short complete example that can be run in python? I don't seem to comprehend.Lac

© 2022 - 2024 — McMap. All rights reserved.