[PyQt] QImage displays arbitrary data

Felix Endres ftmp-cldg at 256bit.org
Wed May 27 13:04:25 BST 2009


Hello all,
I am using the python wrapper for opencv, and want to display an
opencv image (Swig wrapped CvMat) in a PyQt Widget. To achieve
this I create a QImage and wrap it in a Widget-Subclass. The
shown Image has correct size but the data shown is corrupted.

I create the QImage, with the constructors:
QImage.__init__ (self, str data, int width, int height, Format format) or
QImage.__init__ (self, str data, int width, int height, int bytesPerLine,
Format format)

CvMat has a string property imageData, which contains the data. From the 
OpenCv Docs: the usual data layout of a color image is: b0 g0 r0 b1 g1 r1
...
I know blue and red are switched, but nevertheless it should display
the image correctly except for the colors.

I have attached a minimal example "debug.py". A screenshot of
the two Windows (left opencv-highgui, right qt) is also attached.

Any help is appreciated,

Felix
-------------- next part --------------
A non-text attachment was scrubbed...
Name: screenshot.png
Type: image/png
Size: 29322 bytes
Desc: not available
Url : http://www.riverbankcomputing.com/pipermail/pyqt/attachments/20090527/aae70437/screenshot-0001.png
-------------- next part --------------
from PyQt4 import QtGui
from PyQt4 import QtCore
from opencv.cv import *
from opencv.highgui import *
import sys

class ImageViewWidget(QtGui.QWidget):
    def __init__(self, qimage):
        QtGui.QWidget.__init__(self)
        self.image = qimage

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.drawImage(0,0,self.image)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv) 
    img = cvCreateImage(cvSize(320, 200), IPL_DEPTH_8U, 3)
    cvSet(img, (128,0,0))
    cvLine(img, cvPoint(5,5), cvPoint(315,195), (0,0,255), 5)
    cvLine(img, cvPoint(315,5), cvPoint(5,195), (0,255,0), 3)
    
    cvNamedWindow("a")
    cvShowImage("a", img)
    qimg = QtGui.QImage(img.imageData,
                        img.width, 
                        img.height, 
                        img.step,
                        QtGui.QImage.Format_RGB888)
    ivw = ImageViewWidget(qimg)
    ivw.show()
    app.exec_()


More information about the PyQt mailing list