Convert numpy array to PySide QPixmap

前端 未结 4 902
借酒劲吻你
借酒劲吻你 2020-12-08 16:59

I want to convert an image into a NumPy array to a PySide QPixmap, so I can display it (EDIT: in my PySide UI). I already found this tool: qimage2ndarray, but it only works

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 17:33

    One alternative is to just use PIL library.

    >>> import numpy as np
    >>> import Image
    >>> im = Image.fromarray(np.random.randint(0,256,size=(100,100,3)).astype(np.uint8))
    >>> im.show()
    

    You can look at the QPixmap constructor at http://www.pyside.org/docs/pyside/PySide/QtGui/QImage.html.

    It looks like you should be able to use a numpy array directly in the constructor:

    class PySide.QtGui.QImage(data, width, height, format)

    where the format argument is one of these: http://www.pyside.org/docs/pyside/PySide/QtGui/QImage.html#PySide.QtGui.PySide.QtGui.QImage.Format.

    So, for example you could do something like:

    >>> a = np.random.randint(0,256,size=(100,100,3)).astype(np.uint32)
    >>> b = (255 << 24 | a[:,:,0] << 16 | a[:,:,1] << 8 | a[:,:,2]).flatten() # pack RGB values
    >>> im = PySide.QtGui.QImage(b, 100, 100, PySide.QtGui.QImage.Format_RGB32)
    

    I don't have PySide installed so I haven't tested this. Chances are it won't work as is, but it might guide you in the right direction.

提交回复
热议问题