Convert PyQt to PIL image
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).
#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()
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.