我从 PIL
制作 QImage
的图像对象并将其显示在屏幕上。
PIL
具有“RGB(24 位)”、“RGBA(32 位)”、“P(8 位索引模式(调色板模式))”、“L(8 -bit)","1(1-bit)"图像格式可用于 QImage
。
与它相连,QImage
还具有“Format_RGB888(24位)”,“Format_ARGB(32位)”,“Format_Indexed8(8位)”,“Format_Mono(1-位)”。
我创建了一个与 PIL 图像格式连接的 QImage
对象。
例如,当我从 PIL Image 获取“RGB”格式时,我将参数“Format_RGB888”放在 QImage
构造函数的第五个参数上作为 QImage“RGB”格式。
问题是当我得到“P”时,我制作一个QImage
并显示它,图像总是更改为灰度。
我指定“Format_Indexed8”是因为“P”是8位深度,并且QImage
格式中没有其他可采用的格式。
这是 8 位图像,PIL 的“P”格式。
此图像的名称是 Flag_Of_Debar.png。
但是执行的结果是,图像变成了它。
我按 PIL 格式分隔代码,如下所示。 除了“P”之外,没问题
为什么8位“P”模式的PIL-Image要改为灰度?
我应该做什么?
from PySide import QtGui,QtCore
import os,sys
from PIL import Image
import numpy as np
import io
def main():
app = QtGui.QApplication(sys.argv)
directory = os.path.join(os.getcwd(),"\\icons\\")
filename = QtGui.QFileDialog().getOpenFileName(None,"select icon",directory,"(*.png *.jpg *.bmp *.gif)","(*.png *.jpg *.bmp *.gif)")[0]
im = Image.open(filename)
print(im.mode)
data = np.array(im)
img_buffer = io.BytesIO()
im.save(img_buffer,"BMP")
if im.mode == "RGB":
qimagein = QtGui.QImage(data.data, data.shape[1], data.shape[0], data.strides[0], QtGui.QImage.Format_RGB888)
elif im.mode == "RGBA":
qimagein = QtGui.QImage(data.data, data.shape[1], data.shape[0], data.strides[0], QtGui.QImage.Format_ARGB32)
#for avoiding RGB BGR change problem
qimagein.loadFromData(img_buffer.getvalue(), "BMP")
elif im.mode == "1":
qimagein = QtGui.QImage(data.data, data.shape[1], data.shape[0], data.strides[0], QtGui.QImage.Format_Mono)
elif im.mode == "L":
qimagein = QtGui.QImage(data.data, data.shape[1], data.shape[0], data.strides[0], QtGui.QImage.Format_Indexed8)
elif im.mode == "P":
qimagein = QtGui.QImage(data.data, data.shape[1], data.shape[0], data.strides[0], QtGui.QImage.Format_Indexed8)
w = QtGui.QLabel()
pix = QtGui.QPixmap.fromImage(qimagein)
w.setPixmap(pix)
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
最佳答案
在这种特殊情况下,您必须设置调色板:
elif im.mode == "P":
qimagein = QtGui.QImage(data.data, data.shape[1], data.shape[0], data.strides[0], QtGui.QImage.Format_Indexed8)
pal = im.getpalette()
l = [QtGui.qRgb(*pal[3*i:3*(i+1)]) for i in range(256)]
qimagein.setColorTable(l)
关于python - 当我制作 QImage 时,如果图像是 8 位索引模式(调色板模式),我的图像将更改为灰度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51073292/