zw-test0.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #include <opencv2/opencv.hpp>
  2. #include <iostream>
  3. #include <fstream>
  4. void writeYUV420Frame(std::ofstream &file, cv::Mat &frame) {
  5. // Convert the frame from BGR to YUV
  6. cv::Mat yuv_frame;
  7. cv::cvtColor(frame, yuv_frame, cv::COLOR_BGR2YUV_I420);
  8. // Write Y plane
  9. file.write(reinterpret_cast<const char*>(yuv_frame.data), frame.rows * frame.cols);
  10. // Write U and V planes
  11. int uvHeight = frame.rows / 2;
  12. int uvWidth = frame.cols / 2;
  13. file.write(reinterpret_cast<const char*>(yuv_frame.data + frame.rows * frame.cols), uvHeight * uvWidth);
  14. file.write(reinterpret_cast<const char*>(yuv_frame.data + frame.rows * frame.cols + uvHeight * uvWidth), uvHeight * uvWidth);
  15. }
  16. int main(int argc, char** argv) {
  17. // Open the default camera
  18. cv::VideoCapture cap(0, cv::CAP_V4L2); // 改成0或合适的索引
  19. if (!cap.isOpened()) {
  20. std::cerr << "Error: Could not open camera" << std::endl;
  21. return -1;
  22. }
  23. // Set frame width and height to 1280x720
  24. cap.set(cv::CAP_PROP_FRAME_WIDTH, 1280);
  25. cap.set(cv::CAP_PROP_FRAME_HEIGHT, 720);
  26. // Open a file to write the YUV420 video
  27. std::ofstream yuv_file("output.yuv", std::ios::out | std::ios::binary);
  28. if (!yuv_file.is_open()) {
  29. std::cerr << "Error: Could not open output file" << std::endl;
  30. return -1;
  31. }
  32. // Capture frames from the camera
  33. while (true) {
  34. cv::Mat frame;
  35. cap >> frame; // Capture a new frame
  36. if (frame.empty()) {
  37. std::cerr << "Error: Could not capture frame" << std::endl;
  38. break;
  39. }
  40. // Write the frame to the YUV file
  41. writeYUV420Frame(yuv_file, frame);
  42. // Display the frame (直接显示BGR帧)
  43. cv::imshow("Webcam", frame);
  44. // Break the loop on 'q' key press
  45. if (cv::waitKey(30) >= 0) {
  46. break;
  47. }
  48. }
  49. // Clean up
  50. yuv_file.close();
  51. cap.release();
  52. cv::destroyAllWindows();
  53. return 0;
  54. }