使用 OpenCV 和 Qt 处理视频并显示在窗口中
#include "video_processing.h" #include <opencv2/dnn.hpp> #include <opencv2/opencv.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp>
VideoProcessor::VideoProcessor(QObject *parent) : QObject(parent) { m_camera = new QCamera(this); m_imageCapture = new QCameraImageCapture(m_camera, this);
connect(m_imageCapture, SIGNAL(imageAvailable(int,QVideoFrame)), this, SLOT(processFrame(int,QVideoFrame)));
m_camera->setCaptureMode(QCamera::CaptureStillImage);
m_camera->start();
}
VideoProcessor::~VideoProcessor(){ delete m_imageCapture; delete m_camera; }
void VideoProcessor::startCamera() { m_imageCapture->capture(); }
void VideoProcessor::processFrame(int requestid, const QImage &Image) { Q_UNUSED(requestid);
// Convert QVideoFrame to cv::Mat
cv::Mat img;
// Process the image using OpenCV functions
// ...
cv::Mat srcImage = QImageToCvMat(Image);
// Convert the processed image back to QImage
QImage processedImg(img.data, img.cols, img.rows, QImage::Format_RGB888);
// Emit signal with the processed image
emit frameProcessed(processedImg);
}
cv::Mat QImageToCvMat(const QImage& image) { cv::Mat mat; switch (image.format()) { case QImage::Format_RGB888: mat = cv::Mat(image.height(), image.width(), CV_8UC3, const_cast<uchar*>(image.bits()), image.bytesPerLine()); cv::cvtColor(mat, mat, cv::COLOR_RGB2BGR); // 如果需要将RGB格式转换为BGR格式 break;
case QImage::Format_Grayscale8:
mat = cv::Mat(image.height(), image.width(), CV_8UC1, const_cast<uchar*>(image.bits()), image.bytesPerLine());
break;
// 其他QImage格式的处理方式
default:
qWarning() << "Unsupported image format";
break;
}
return mat;
} // 要让Main.c读到srcImage,并在Main.c中的cv::Mat格式下的dstImage显示视频,要怎么改内容:要让Main.c读取到srcImage并显示视频,可以使用以下步骤:
// 1. 在Main.c中,包含必要的头文件:
#include <opencv2/opencv.hpp>
// 2. 在Main.c中定义一个函数,用于显示视频帧:
void displayFrame(cv::Mat frame) {
cv::imshow("Video", frame);
cv::waitKey(1);
}
// 3. 在Main.c的主函数中创建一个VideoProcessor对象,并连接frameProcessed信号到displayFrame槽函数:
int main() {
VideoProcessor processor;
QObject::connect(&processor, SIGNAL(frameProcessed(cv::Mat)), &displayFrame, SLOT(displayFrame(cv::Mat)));
// 其他代码
return 0;
}
这样,当VideoProcessor对象处理完一帧图像后,会触发frameProcessed信号,然后通过连接的槽函数displayFrame将图像显示出来。
注意:在Main.c中使用VideoProcessor对象时,需要包含相应的头文件并链接相应的库文件。此外,还需要将VideoProcessor类的定义和相关函数的实现添加到Main.c中。
原文地址: https://www.cveoy.top/t/topic/pPNb 著作权归作者所有。请勿转载和采集!