Tag Archives: QImage

Python – OpenCV IplImage To PyQt QImage

This is a quick post which will hopefully save someone some time. I spent far too long trying to figure this out.
If you’re using Qt and OpenCV with python and want to show an opencv iplimage within a Qt Widget here’s a quick hack to convert the iplimage to a qimage.


class IplQImage(QtGui.QImage):
"""A class for converting iplimages to qimages"""

     def __init__(self,iplimage):
         #Rough-n-ready but it works dammit
         alpha = cv.CreateMat(iplimage.height,iplimage.width, cv.CV_8UC1)
         cv.Rectangle(alpha,(0,0),(iplimage.width,iplimage.height),cv.ScalarAll(255),-1)
         rgba = cv.CreateMat(iplimage.height,iplimage.width, cv.CV_8UC4)
         cv.Set(rgba, (1,2,3,4))
         cv.MixChannels([iplimage, alpha],[rgba], [
         (0, 0), # rgba[0] -> bgr[2]
         (1, 1), # rgba[1] -> bgr[1]
         (2, 2), # rgba[2] -> bgr[0]
         (3, 3) # rgba[3] -> alpha[0]
         ])
         self.__imagedata = rgba.tostring()
         super(IplQImage,self).__init__(self.__imagedata, iplimage.width,iplimage.height, QtGui.QImage.Format_RGB32)

All in all it’s fairly straight forward, an example case is something like the following:


#Create a 3 channel RGB iplimage (could be from a webcam ect.)
iplimage = cv.CreateMat(iplimage.height,iplimage.width, cv.CV_8UC3)
#Turn it into a qimage
qimage = IplQImage(iplimage)

It works by sub-classing QImage and overloading the constructor with a new one that accepts an IplImage, this then has an extra alapha channel added (to make it compatible with the QImage pixel packing) and finally the __init__ method of the superclass (QImage) is called with the data from the iplimage passed into it as a string.

The important part is:


self.__imagedata = rgba.tostring()

This keeps a reference to the image data so it doesn’t go out of scope when the __init__ returns. (the QImage constructor that accepts image data doesn’t keep a local reference to the data, so you have to make sure it isn’t lost.[at least i think that’s right])