12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- #include <opencv2/opencv.hpp>
- #include <iostream>
- #include <fstream>
- void writeYUV420Frame(std::ofstream &file, cv::Mat &frame) {
-
- cv::Mat yuv_frame;
- cv::cvtColor(frame, yuv_frame, cv::COLOR_BGR2YUV_I420);
-
- file.write(reinterpret_cast<const char *>(yuv_frame.data), frame.rows * frame.cols);
-
- int uvHeight = frame.rows / 2;
- int uvWidth = frame.cols / 2;
- file.write(reinterpret_cast<const char *>(yuv_frame.data + frame.rows * frame.cols), uvHeight * uvWidth);
- file.write(reinterpret_cast<const char *>(yuv_frame.data + frame.rows * frame.cols + uvHeight * uvWidth),
- uvHeight * uvWidth);
- }
- int main(int argc, char **argv) {
-
- cv::VideoCapture cap(0, cv::CAP_V4L2);
- if (!cap.isOpened()) {
- std::cerr << "Error: Could not open camera" << std::endl;
- return -1;
- }
-
- cap.set(cv::CAP_PROP_FRAME_WIDTH, 1280);
- cap.set(cv::CAP_PROP_FRAME_HEIGHT, 720);
-
- std::ofstream yuv_file("output.yuv", std::ios::out | std::ios::binary);
- if (!yuv_file.is_open()) {
- std::cerr << "Error: Could not open output file" << std::endl;
- return -1;
- }
-
- while (true) {
- cv::Mat frame;
- cap >> frame;
- if (frame.empty()) {
- std::cerr << "Error: Could not capture frame" << std::endl;
- break;
- }
-
- writeYUV420Frame(yuv_file, frame);
-
- cv::imshow("Webcam", frame);
-
- if (cv::waitKey(30) >= 0) {
- break;
- }
- }
-
- yuv_file.close();
- cap.release();
- cv::destroyAllWindows();
- return 0;
- }
|