I have an image in a QImage and I want to process it in PIL before I display it. While the ImageQT class lets me convert a PIL Image to a QImage, there doesn't appear to anything to go from a QImage to a PIL Image.
I convert it from QImage to PIL with this code:
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)
I tried many combinations before getting it to work.
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.
Another route would be:
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With