PILの画像を表示する

2016/07/28

Python2.7.10, PySide1.2.2

ポイント

pil_img = pil_img.convert('RGBA')
imBytes = pil_img.tostring('raw', 'RGBA')
qt_img = QtGui.QImage(imBytes,pil_img.size[0],pil_img.size[1],QtGui.QImage.Format_ARGB32)

でも、なぜかRGBがBGRで表示されるorz

(情報があったので今度試すー)
http://code.tiblab.net/python/pyside/pil_image

サンプル

# -*- coding: utf-8 -*-

import sys
from PySide import QtGui
from PIL import Image
import numpy as np

class Window(QtGui.QMainWindow):
    def __init__(self, *argv, **keywords ):
        super(Window,self).__init__(*argv,**keywords)
        view = QtGui.QGraphicsView(self)
        self.setCentralWidget(view)
        scene = QtGui.QGraphicsScene(self)

        #read image
        pil_img = Image.open('c://test.png')
        pil_img = pil_img.convert('RGBA')
        #RGB => BGR
        data = np.array(pil_img)
        red, green, blue, alpha = data.T
        data = np.array([blue, green, red, alpha])
        data = data.transpose()
        pil_img = Image.fromarray(data)
        #pil => qt
        imBytes = pil_img.tostring('raw', 'RGBA')
        qt_img = QtGui.QImage(imBytes,pil_img.size[0],pil_img.size[1],QtGui.QImage.Format_ARGB32)

        pixmap = QtGui.QPixmap.fromImage(qt_img)
        item = QtGui.QGraphicsPixmapItem(pixmap)
        scene.addItem(item)
        view.setScene(scene)

    def resizeEvent(self,event):
        print('resize')

def main():
    app = QtGui.QApplication(sys.argv)
    w = Window()
    w.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()