Linux 如何获取 QPixmap 或 QImage 像素的 RGB 值 - Qt、PyQt
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9134597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get RGB values of QPixmap or QImage pixel - Qt, PyQt
提问by Grzegorz Wierzowiecki
Based on this answer https://stackoverflow.com/a/769221/544721, I've made following code printing values in grabbed region:
基于这个答案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)) ) )
But pixels are displayed like this:
但像素显示如下:
(0,0) = 4285163107
(0,1) = 4285163107
(0,2) = 4285163107
(0,3) = 4285163107
(0,4) = 4285163107
(0,5) = 4285163107
How to get RGB values of QImage
(obtained from QPixmap
) pixels ? (preferably, solution working in 16,24,32 screen bit depths) ?
如何获得QImage
(从QPixmap
)像素的RGB 值?(最好是在 16,24,32 屏幕位深度下工作的解决方案)?
Example output:
示例输出:
(0,0) = (0,0,0)
...
(10,15) = (127,15,256)
(Solution for Linux, written in Python3)
(Linux 解决方案,用 Python3 编写)
采纳答案by jdi
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:
您看到的问题是从 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)
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)
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.
可以通过将其坐标传递给 pixel() 函数来检索像素的颜色。pixel() 函数将颜色作为与图像格式无关的 QRgb 值返回。
回答by ekhumoro
The color components of the QRgb
value returned by QImage.pixel
can either be extracted directly, or via a QColor
object:
QRgb
返回值的颜色分量QImage.pixel
可以直接提取,也可以通过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)