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.
A:
You can convert a QImage into a Python string:
>>> image = QImage(256, 256, QImage.Format_ARGB32)
>>> bytes = image.bits().asstring(image.numBytes())
>>> len(bytes)
262144
Converting from this to PIL should be easy.
Eli Bendersky
2009-11-14 06:32:03
I dont think that direct image data are compatible between QImage and PIL images. What I found out after some messing around (it bit me): Qt aligns all its lines on 32bit, which means that if the number of bytes per line for image is not divisible by 4, there's going to be crap inserted in the data.Maybe there's even more gotchas...
Virgil Dupras
2009-11-16 14:54:51
+2
A:
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 = Imagen.open(strio)
I lost a full morning searching a correct way to do this.
skuda
2009-11-18 14:59:01
+1
A:
Another route would be:
- Load the image data into a numpy array (example code using PIL)
- Manipulate the image using numpy, scipy or scikits.image
- Load the data into a QImage (example: browse the scikits.image archive (linked in 1) and look on line 45 of qt_plugin.py -- sorry, stackoverflow doesn't allow me to post more links yet)
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).
Stefan van der Walt
2009-11-19 23:07:44
A:
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()
Thanks Eli Bendersky, your code was helpful.
-Chenna
reddy
2010-08-27 21:12:46
A:
#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()
reddy
2010-08-30 23:19:29