如何获取Qt、PyQt中QPixmap或QImage像素的RGB值

14

基于这个答案 https://dev59.com/ZXVD5IYBdhLWcg3wJIIK#769221,我编写了以下代码打印抓取区域中的值:

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

如何获取从QPixmap获取的QImage像素的RGB值?(最好在16、24、32位屏幕色深下工作的解决方案)?
示例输出:
(0,0) = (0,0,0)
...
(10,15) = (127,15,256)

(适用于Linux的解决方案,使用Python3编写)
2个回答

12

你所看到的问题是由于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()函数来检索像素的颜色。pixel()函数以QRgb值的形式返回颜色,与图像的格式无关。


4
QImage.pixel返回的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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接