将PyQt转换为PIL图像

问题描述 投票:9回答:6

我在QImage中有一个图像,我想在显示它之前在PIL中处理它。虽然ImageQT类允许我将PIL图像转换为QImage,但似乎没有任何东西可以从QImage转换为PIL图像。

python pyqt python-imaging-library
6个回答
12
投票

我使用以下代码将它从QImage转换为PIL:

img = QImage("/tmp/example.png")
buffer = QBuffer()
buffer.open(QIODevice.ReadWrite)
img.save(buffer, "PNG")

strio = cStringIO.StringIO()
strio.write(buffer.data())
buffer.close()
strio.seek(0)
pil_im = Image.open(strio)

在开始工作之前我尝试了很多组合。


2
投票

另一条路线是:

  1. 将图像数据加载到numpy数组(使用PIL的example code
  2. 使用numpy,scipy或scikits.image操纵图像
  3. 将数据加载到QImage中(例如:浏览scikits.image存档(链接在1中)并查看qt_plugin.py的第45行 - 抱歉,stackoverflow不允许我发布更多链接)

正如Virgil所提到的,数据必须是32位(或4字节)对齐,这意味着你需要记住在步骤3中指定步幅(如代码片段所示)。


1
投票
#Code for converting grayscale QImage to PIL image

from PyQt4 import QtGui, QtCore
qimage1 = QtGui.QImage("t1.png")
bytes=qimage1.bits().asstring(qimage1.numBytes())
from PIL import Image
pilimg = Image.frombuffer("L",(qimage1.width(),qimage1.height()),bytes,'raw', "L", 0, 1)
pilimg.show()

1
投票
from PyQt4 import QtGui, QtCore
img = QtGui.QImage("greyScaleImage.png")
bytes=img.bits().asstring(img.numBytes())
from PIL import Image
pilimg = Image.frombuffer("L",(img.width(),img.height()),bytes,'raw', "L", 0, 1)
pilimg.show()

谢谢Eli Bendersky,您的代码很有帮助。


0
投票

您可以将QImage转换为Python字符串:

>>> image = QImage(256, 256, QImage.Format_ARGB32)
>>> bytes = image.bits().asstring(image.numBytes())
>>> len(bytes)
262144

从这个转换为PIL应该很容易。


0
投票

这是一个使用PySide2 5.x,qt的官方python包装的答案。他们也应该为PyQt 5.x工作

我还将QImage添加到numpy,我已将其与此一起使用。我更喜欢使用PIL依赖,主要是因为我不必跟踪颜色通道的变化。

from PySide2 import QtCore, QtGui
from PIL import Image
import io


def qimage_to_pimage(qimage: QtGui.QImage) -> Image:
    """
    Convert qimage to PIL.Image

    Code adapted from SO:
    https://stackoverflow.com/a/1756587/7330813
    """
    bio = io.BytesIO()
    bfr = QtCore.QBuffer()
    bfr.open(QtCore.QIODevice.ReadWrite)
    qimage.save(bfr, 'PNG')
    bytearr = bfr.data()
    bio.write(bytearr.data())
    bfr.close()
    bio.seek(0)
    img = Image.open(bio)
    return img

这是一个将numpy.ndarray转换为QImage的人

from PIL import Image, ImageQt
import numpy as np

def array_to_qimage(arr: np.ndarray):
    "Convert numpy array to QImage"
    img = Image.fromarray(arr)
    return ImageQt.ImageQt(img)

© www.soinside.com 2019 - 2024. All rights reserved.