当我制作QImage时,如果图像是8bit indexmode(调色板模式),我的图像会被更改为灰度

2024-10-03 04:39:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我从PIL生成一个QImage的图像对象,并将其显示在屏幕上。在

PIL具有“RGB(24位)”、“RGBA(32位)”、“p(8位索引模式(调色板模式)”、“L(8位)”、“1(1位)”图像格式可用于QImage。在

通过与它的连接,QImage还具有“Format_RGB888(24位)”、“Format_ARGB(32位)”、“Format_Indexed8(8位)”、“Format_Mono(1位)”。在

我创建了一个QImage对象,它连接到PIL图像格式。在

例如,当我从PIL-Image获取“RGB”格式时,我在QImage构造函数的第五个上放置一个参数“format_RGB888”,作为QImage“RGB”格式。在

问题是当我得到“p”时,我做一个QImage并显示出来,图像总是变为灰度。在

我指定“Format_Indexed8”,因为“p”是8位深度,QImage格式中没有其他可采用的格式。在

这是8位图像,PIL格式的“p”。在

Flag_Of_Debar.png

此图像的名称是_德巴尔.png. 在

但作为执行的结果,图像被改为它。在

enter image description here

我用PIL格式分隔代码如下。 除了“P”,没问题

为什么8位“p”模式的PIL图像变为灰度?在

我该怎么办?在

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

Tags: 图像importformatdatapilmode格式rgb
2条回答

PILPillow分叉直接有一个method of converting to a ^{}。在

from PIL import ImageQt
qimagein = ImageQt.ImageQt(im)

在这种特殊情况下,必须设置调色板:

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)

enter image description here

相关问题 更多 >