用qt+opencv, 写一个电脑录屏的示例代码, 视频格式 h264
时间: 2024-06-10 17:08:27 浏览: 145
Qt+OpenCv制作简单录屏.rar
很高兴回答您的问题!以下是示例代码:
```cpp
#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <opencv2/core.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget w;
// create a vertical layout to add the video widget
QVBoxLayout *layout = new QVBoxLayout(&w);
// open the default camera and check if it is available
cv::VideoCapture cap;
if (!cap.open(0)) {
std::cerr << "Cannot open camera." << std::endl;
return 1;
}
// set the codec for the output video
int codec = cv::VideoWriter::fourcc('H', '2', '6', '4');
// get the frame size from the camera
int frame_width = static_cast<int>(cap.get(cv::CAP_PROP_FRAME_WIDTH));
int frame_height = static_cast<int>(cap.get(cv::CAP_PROP_FRAME_HEIGHT));
// create a video writer to save the recorded video
cv::VideoWriter writer("output.avi", codec, 30, cv::Size(frame_width, frame_height), true);
// start the loop to capture and record frames
cv::Mat frame;
while (true) {
// capture a frame from the camera
cap >> frame;
// check if the frame is valid
if (frame.empty()) {
std::cerr << "Cannot capture frame." << std::endl;
break;
}
// record the frame to the output video
writer.write(frame);
// convert the frame to a QImage
cv::Mat rgb;
cv::cvtColor(frame, rgb, cv::COLOR_BGR2RGB);
QImage qimg(rgb.data, rgb.cols, rgb.rows, rgb.step, QImage::Format_RGB888);
// create a QLabel to display the image
QLabel *label = new QLabel(&w);
label->setPixmap(QPixmap::fromImage(qimg));
// add the label to the layout
layout->addWidget(label);
// update the widget to show the new label
w.update();
// wait for a key press or 10 ms
if (cv::waitKey(10) >= 0)
break;
}
// release the resources and exit
writer.release();
cap.release();
w.show();
return a.exec();
}
```
希望这能够帮助您解决问题。如果您还有其他问题,请随时问我!
阅读全文