How to get RGB values of QPixmap or QImage pixel - Qt, PyQt How to get RGB values of QPixmap or QImage pixel - Qt, PyQt linux linux

How to get RGB values of QPixmap or QImage pixel - Qt, PyQt


The issue you are seeing is that the number being returned from img.pixel() is actually a QRgb value that is a format independent value. You can then convert it into the proper representation as such:

import sysfrom PyQt4.QtGui import QPixmap, QApplication, QColorapp = QApplication(sys.argv)# img is QImage typeimg = QPixmap.grabWindow(        QApplication.desktop().winId(),        x=00,        y=100,        height=20,        width=20,        ).toImage()for x in range(0,20):    for y in range(0,20):        c = img.pixel(x,y)        colors = QColor(c).getRgbF()        print "(%s,%s) = %s" % (x, y, colors)

Output

(0,0) = (0.60784313725490191, 0.6588235294117647, 0.70980392156862748, 1.0)(0,1) = (0.60784313725490191, 0.6588235294117647, 0.70980392156862748, 1.0)(0,2) = (0.61176470588235299, 0.6588235294117647, 0.71372549019607845, 1.0)(0,3) = (0.61176470588235299, 0.66274509803921566, 0.71372549019607845, 1.0)

QImage docs:

The color of a pixel can be retrieved by passing its coordinates to the pixel() function. The pixel() function returns the color as a QRgb value indepedent of the image's format.


The color components of the QRgb value returned by QImage.pixel can either be extracted directly, or via a QColor object:

>>> from PyQt4 import QtGui>>> rgb = 4285163107>>> QtGui.qRed(rgb), QtGui.qGreen(rgb), QtGui.qBlue(rgb)(106, 102, 99)>>> QtGui.QColor(rgb).getRgb()[:-1](106, 102, 99)