11

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

4

6 回答 6

13

我使用以下代码将其从 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)

在让它发挥作用之前,我尝试了很多组合。

于 2009-11-18T14:59:01.577 回答
2

另一条路线是:

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

As Virgil mentions, the data must be 32-bit (or 4-byte) aligned, which means you need to remember to specify the strides in step 3 (as shown in the snippet).

于 2009-11-19T23:07:44.883 回答
2
from PyQt5 import QtGui
from PIL import Image

img = QtGui.QImage(width, height, QImage.Format_RGBA8888)
data = img.constBits().asstring(img.byteCount())
pilimg = Image.frombuffer('RGBA', (img.width(), img.height()), data, 'raw', 'RGBA', 0, 1)
from PyQt4 import QtGui
from PIL import Image

img = QtGui.QImage("greyScaleImage.png")
bytes = img.bits().asstring(img.numBytes())
pilimg = Image.frombuffer('L', (img.width(), img.height()), bytes, 'raw', 'L', 0, 1)
pilimg.show()

Thanks Eli Bendersky, your code was helpful.

于 2010-08-27T21:12:46.570 回答
2
#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()
于 2010-08-30T23:19:29.723 回答
0

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

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

从此转换为 PIL 应该很容易。

于 2009-11-14T06:32:03.450 回答
0

Here is an answer for those using PySide2 5.x, the official python wrappings for qt. They should also work for PyQt 5.x

I also added to QImage to numpy that I've used in conjunction with this one. I prefer to use PIL dependency, mainly because I don't have to track color channel changes.

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

Here is one to convert numpy.ndarray to 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)

于 2019-04-30T01:38:52.620 回答