Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display a webcam stream in PyQt4 using OpenCV Camera Capture

I am using this Python script to display my webcam:

from opencv.cv import *  
from opencv.highgui import *  

import sys

cvNamedWindow("w1", CV_WINDOW_AUTOSIZE)
camera_index = 0
capture = cvCreateCameraCapture(camera_index)

def repeat():
    global capture #declare as globals since we are assigning to them now
    global camera_index
    frame = cvQueryFrame(capture)
    cvShowImage("w1", frame)
    c = cvWaitKey(10)

    if c == "q":
        sys.exit(0)

if __name__ == "__main__":
    while True:
        repeat()

It is working quite well, but I would like to set this display inside my Qt application. How can I use the IplImage OpenCV image into a Qt VideoWidget?

like image 317
Natim Avatar asked Jun 08 '10 22:06

Natim


2 Answers

It looks like we need to bind this C++ code in Python :

QImage& cvxCopyIplImage(const IplImage *pIplImage, QImage &qImage)
{
        if(!CV_IS_IMAGE(pIplImage)) return qImage;

        int w = pIplImage->width;
        int h = pIplImage->height;


        if(qImage.width() != w || qImage.height() != h)
        {
                qImage = QImage(w, h, QImage::Format_RGB32);
        }

        int x, y;
        for(x = 0; x < pIplImage->width; ++x)
        {
                for(y = 0; y < pIplImage->height; ++y)
                {
                        CvScalar color = cvGet2D(pIplImage, y, x);

                        if(pIplImage->nChannels == 1)
                        {
                                int v = color.val[0];

                                qImage.setPixel(x, y, qRgb(v,v,v));
                        }
                        else
                        {
                                int r = color.val[2];
                                int g = color.val[1];
                                int b = color.val[0];

                                qImage.setPixel(x, y, qRgb(r,g,b));
                        }
                }
        }

        if(pIplImage->origin != IPL_ORIGIN_TL)
        {
                qImage = qImage.mirrored(false, true);
        }

        return qImage;
}
like image 57
Natim Avatar answered Sep 19 '22 02:09

Natim


I used the code bellow to covert a Iplimage objet to a QImage. It took me some time to get the right formats. Iplimage is a 3-channel format with BGR channel order while QImage uses RGB channel order.

camcapture = cv.CaptureFromCAM(0)       
cv.SetCaptureProperty(camcapture,cv.CV_CAP_PROP_FRAME_WIDTH, 1280)
cv.SetCaptureProperty(camcapture,cv.CV_CAP_PROP_FRAME_HEIGHT, 720);

frame = cv.QueryFrame(camcapture)
image = QImage(frame.tostring(), frame.width, frame.height, QImage.Format_RGB888).rgbSwapped()
pixmap = QPixmap.fromImage(image)
like image 42
William Dias Avatar answered Sep 19 '22 02:09

William Dias