当我制作QImage时,如果图像是8位索引模式(调色板模式),结果是我的图像变为灰度

时间:2018-06-28 00:55:30

标签: python pyqt pyside pillow

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

PIL具有“ RGB(24位)”,“ RGBA(32位)”,“ P(8位索引模式(调色板模式))”,“ L(8位)” QImage可以使用“,” 1(1-bit)“图像格式。

与其连接的QImage还具有“ Format_RGB888(24位)”,“ Format_ARGB(32位)”,“ Format_Indexed8(8位)”,“ Format_Mono(1位)”

我制作了一个QImage与PIL图像格式有关的对象。

例如,当我从PIL图像中获取“ RGB”格式时,我将QImage构造函数的第五个参数作为“ Image_RGB888”形式设置为“ Format_RGB888”。

问题是当我得到“ P”时,我做了一个QImage并显示它,图像总是变为灰度。

我之所以指定“ Format_Indexed8”,是因为“ P”是8位深度,并且没有其他QImage格式的可采用格式。

这是PIL的8位图像“ P”格式。

Flag_Of_Debar.png

此图片的名称为Flag_Of_Debar.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()

2 个答案:

答案 0 :(得分:1)

Pillow的{​​{1}}分支直接具有method of converting to a QImage

PIL

答案 1 :(得分:1)

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

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