如何获取QPixmap或QImage像素的RGB值 – Qt,PyQt

根据这个答案https://stackoverflow.com/a/769221/544721 ,我已经在抓取区域做了以下代码打印值:

import sys from PyQt4.QtGui import QPixmap, QApplication app = QApplication(sys.argv) # img is QImage type img = 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): print( "({},{}) = {}".format( x,y,(img.pixel(x,y)) ) ) 

但像素显示如下:

 (0,0) = 4285163107 (0,1) = 4285163107 (0,2) = 4285163107 (0,3) = 4285163107 (0,4) = 4285163107 (0,5) = 4285163107 

如何获得QImage RGB值(从QPixmap获得)像素? (最好是16,24,32屏幕位深度的解决scheme)?

示例输出:

 (0,0) = (0,0,0) ... (10,15) = (127,15,256) 

(针对Linux的解决scheme,用Python3编写)

Solutions Collecting From Web of "如何获取QPixmap或QImage像素的RGB值 – Qt,PyQt"

你看到的问题是,从img.pixel()返回的数字实际上是一个QRgb值,它是一个独立于格式的值。 然后,您可以将其转换为适当的表示形式:

 import sys from PyQt4.QtGui import QPixmap, QApplication, QColor app = QApplication(sys.argv) # img is QImage type img = 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) 

产量

 (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文档 :

像素的颜色可以通过将其坐标传递给pixel()函数来获取。 像素()函数返回颜色作为独立于图像格式的QRgb值。

QRgb返回的QRgb值的颜色分量可以直接提取,也可以通过QColor对象提取:

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