簡體   English   中英

將 PyQt 轉換為 PIL 圖像

[英]Convert PyQt to PIL image

我在 QImage 中有一個圖像,我想在顯示它之前在 PIL 中處理它。 雖然 ImageQT 類允許我將 PIL Image 轉換為 QImage,但似乎沒有任何東西可以從 QImage 轉換為 PIL Image。

我使用以下代碼將其從 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)

在讓它工作之前,我嘗試了很多組合。

另一條路線是:

  1. 將圖像數據加載到 numpy 數組中(使用 PIL 的示例代碼
  2. 使用 numpy、scipy 或 scikits.image 操作圖像
  3. 將數據加載到 QImage 中(例如:瀏覽 scikits.image 存檔(在 1 中鏈接)並查看 qt_plugin.py 的第 45 行——抱歉,stackoverflow 還不允許我發布更多鏈接)

正如 Virgil 提到的,數據必須是 32 位(或 4 字節)對齊的,這意味着您需要記住在步驟 3 中指定步幅(如代碼段所示)。

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()

感謝 Eli Bendersky,您的代碼很有幫助。

#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()

您可以將 QImage 轉換為 Python 字符串:

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

從這個轉換到 PIL 應該很容易。

這是使用PySide2 5.x的人的答案, PySide2 5.x的官方 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM