【发布时间】:2026-01-28 04:10:02
【问题描述】:
所以我可以通过这个简单的代码使用带有 imshow 的 OpenCV 查看我的网络摄像头流
int main(int, char**)
{
VideoCapture cap(0);
Mat edges;
namedWindow("webcam", 1);
while (true)
{
Mat frame;
cap >> frame;
imshow("webcam", frame);
if (waitKey(30) >= 0) break;
}
return 0;
}
现在我想要在 QT 上的 Widget 中的 QImage 中显示来自 OpenCV 的图像 这是从 cv::Mat 到 QImage 的转换
QImage Mat2QImage(cv::Mat const& src)
{
cv::Mat temp;
cvtColor(src, temp, CV_BGR2RGB);
QImage dest((const uchar *)temp.data, temp.cols, temp.rows, temp.step, QImage::Format_RGB888);
dest.bits();
// of QImage::QImage ( const uchar * data, int width, int height, Format format )
return dest;
}
以及在 QT 中使用 QImage 显示图像的小代码
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QImage myImage;
myImage.load("a.png");
QLabel myLabel;
myLabel.setPixmap(QPixmap::fromImage(myImage));
myLabel.show();
return a.exec();
}
我试图以这种方式组合它们,但没有运气
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
VideoCapture cap(0);
QImage myImage;
QLabel myLabel;
while (true)
{
Mat frame;
cap >> frame; // get a new frame from camera
myImage = Mat2QImage(frame);
myLabel.setPixmap(QPixmap::fromImage(myImage));
}
myLabel.show();
return a.exec();
【问题讨论】:
-
这不是它的工作方式。你进入一个无限循环:你怎么能看到任何东西,因为
myLabel.show()是在循环之后? -
从设备流式传输以及对图像数据的任何处理都应在单独的线程中完成。如果你迟早要做你正在做的事情,你将不得不重写你的代码。查看我制作的关于 OpenCV 与 Qt 集成的几个视频:youtube.com/… 请注意,您也可以使用自定义的
QThread,并且您不必坚持我在教程中使用的 Worker 模式。