如何使用OpenCv在Qt GUI应用程序中显示网络摄像头源?

时间:2013-08-01 12:32:06

标签: linux qt opencv webcam

我需要在Qt GUI应用程序中显示网络摄像头Feed。我如何使用OpenCv做到这一点?从早上起,我一直在为此烦恼。如果有人可以展示示例代码,我会非常感激。

1 个答案:

答案 0 :(得分:3)

这对我有用:

QImage MatToQImage(const Mat& mat)
{
    // 8-bits unsigned, NO. OF CHANNELS=1
    if(mat.type()==CV_8UC1)
    {
        // Set the color table (used to translate colour indexes to qRgb values)
        QVector<QRgb> colorTable;
        for (int i=0; i<256; i++)
            colorTable.push_back(qRgb(i,i,i));
        // Copy input Mat
        const uchar *qImageBuffer = (const uchar*)mat.data;
        // Create QImage with same dimensions as input Mat
        QImage img(qImageBuffer, mat.cols, mat.rows, mat.step, QImage::Format_Indexed8);
        img.setColorTable(colorTable);
        return img;
    }
    // 8-bits unsigned, NO. OF CHANNELS=3
    if(mat.type()==CV_8UC3)
    {
        // Copy input Mat
        const uchar *qImageBuffer = (const uchar*)mat.data;
        // Create QImage with same dimensions as input Mat
        QImage img(qImageBuffer, mat.cols, mat.rows, mat.step, QImage::Format_RGB888);
        return img.rgbSwapped();
    }
    else
    {
        qDebug() << "ERROR: Mat could not be converted to QImage.";
        return QImage();
    }
} // MatToQImage()
....
// Then use it in main code as follows
// Display frame in main window
frameLabel->setPixmap(QPixmap::fromImage(frame));
....