zw-test0.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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),
  15. uvHeight * uvWidth);
  16. }
  17. int main(int argc, char **argv) {
  18. // Open the default camera
  19. cv::VideoCapture cap(0, cv::CAP_V4L2); // 改成0或合适的索引 /dev/video0
  20. if (!cap.isOpened()) {
  21. std::cerr << "Error: Could not open camera" << std::endl;
  22. return -1;
  23. }
  24. // Set frame width and height to 1280x720
  25. cap.set(cv::CAP_PROP_FRAME_WIDTH, 1280);
  26. cap.set(cv::CAP_PROP_FRAME_HEIGHT, 720);
  27. // Open a file to write the YUV420 video
  28. std::ofstream yuv_file("output.yuv", std::ios::out | std::ios::binary);
  29. if (!yuv_file.is_open()) {
  30. std::cerr << "Error: Could not open output file" << std::endl;
  31. return -1;
  32. }
  33. // Capture frames from the camera
  34. while (true) {
  35. cv::Mat frame;
  36. cap >> frame; // Capture a new frame
  37. if (frame.empty()) {
  38. std::cerr << "Error: Could not capture frame" << std::endl;
  39. break;
  40. }
  41. // Write the frame to the YUV file
  42. writeYUV420Frame(yuv_file, frame);
  43. // Display the frame (直接显示BGR帧)
  44. cv::imshow("Webcam", frame);
  45. // Break the loop on 'q' key press
  46. if (cv::waitKey(30) >= 0) {
  47. break;
  48. }
  49. }
  50. // Clean up
  51. yuv_file.close();
  52. cap.release();
  53. cv::destroyAllWindows();
  54. return 0;
  55. }