我在 PyQt 中有一个灰度图像,想要获取特定像素的颜色。灰度图像使用最多包含 256 个条目的颜色表。
from PyQt4 import QtGui
def test():
image = QtGui.QImage(100, 100, QtGui.QImage.Format_Indexed8)
image.load("d:/1.bmp")
print image.pixel(1, 1)
print image.pixelIndex(1, 1)
image.setColorTable(list([i] for i in range(256)))
print image.colorTable()
import sys
app = QtGui.QApplication(sys.argv)
window = test()
sys.exit(app.exec_())
我有以下问题:
image.colorTable()
返回一个 256 乘以数字 4294967295L(即 2^32-1)的列表,尽管我刚刚将颜色表设置为 0 到 255。image.pixelIndex(1, 1)
给出消息“QImage::pixelIndex: 不适用于 32-bpp 图像(无调色板)”,尽管格式设置为 Indexed8 (并且 isGrayscale() 返回 true)。image.pixel(1, 1)
返回 4278190080(当我将格式设置为 Format_RGB32 时也是如此)。这是什么颜色? (它应该是黑色的。)
根据 ekhumoro 的答案新代码:
from PyQt4 import QtGui
def test():
image = QtGui.QImage(100, 100, QtGui.QImage.Format_Indexed8)
image.load("d:/1.bmp")
image2 = image.convertToFormat(QtGui.QImage.Format_Indexed8)
print "format:", image2.format()
print "pixel color:", QtGui.qGray(image2.pixel(1, 1))
image2.setColorTable(list([QtGui.qRgb(i, i, i)] for i in range(256)))
print "color table:", image2.colorTable()
import sys
app = QtGui.QApplication(sys.argv)
window = test()
sys.exit(app.exec_())
最佳答案
docs for QImage拥有您问题的所有答案:
来自
setColorTable()
的条目:Sets the color table used to translate color indexes to QRgb values, to the specified colors. When the image is used, the color table must be large enough to have entries for all the pixel/index values present in the image, otherwise the results are undefined.
来自
load()
的条目:The loader attempts to read the image using the specified format, e.g., PNG or JPG. If format is not specified (which is the default), the loader probes the file for a header to guess the file format.
因此,您传递给
QImage
构造函数的格式是无关紧要的,我预测print image.format()
将输出一个值 > 3。此外,查看在pixelIndex()
的条目处我看到了这个:If position is not valid, or if the image is not a paletted image (depth() > 8), the results are undefined.
来自
pixel()
的条目:QRgb QImage::pixel(int x, int y) const.
因此,该函数返回一个
QRgb
类型的值,文档对此进行了描述:An ARGB quadruplet on the format #AARRGGBB, equivalent to an unsigned int.
Qt 提供了一些函数来提取
QRgb
值的各个组成部分。其中之一是qGray
,其描述如下:Returns a gray value (0 to 255) from the given ARGB quadruplet rgb.
(注意:这些函数位于全局命名空间中,因此在 PyQt 中,您可以在
QtGui
模块中找到它们)。
关于python - 灰度图像颜色表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38798570/