display.cpp 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #include <opencv2/opencv.hpp>
  2. #include <opencv2/imgcodecs.hpp>
  3. #include <fcntl.h>
  4. #include <sys/mman.h>
  5. #include <sys/stat.h>
  6. #include <semaphore.h>
  7. #include <unistd.h>
  8. #include <iostream>
  9. #include <string>
  10. const int WIDTH = 640;
  11. const int HEIGHT = 480;
  12. const size_t SHM_SIZE = HEIGHT * WIDTH * 3; // 假设图像为640x480,RGB格式
  13. class SharedMemoryReader {
  14. private:
  15. int camera_id;
  16. std::string shm_name;
  17. std::string sem_name;
  18. int shm_fd;
  19. void* shm_ptr;
  20. sem_t* sem;
  21. public:
  22. SharedMemoryReader(int id)
  23. : camera_id(id),
  24. shm_name("/camera_data_" + std::to_string(id)),
  25. sem_name("/camera_semaphore_" + std::to_string(id)),
  26. shm_fd(-1),
  27. shm_ptr(nullptr),
  28. sem(nullptr) {
  29. // 打开共享内存
  30. shm_fd = shm_open(shm_name.c_str(), O_RDONLY, 0666);
  31. if (shm_fd == -1) {
  32. throw std::runtime_error("Failed to open shared memory for camera " + std::to_string(camera_id));
  33. }
  34. // 将共享内存映射到进程地址空间
  35. shm_ptr = mmap(0, SHM_SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
  36. if (shm_ptr == MAP_FAILED) {
  37. throw std::runtime_error("Failed to map shared memory for camera " + std::to_string(camera_id));
  38. }
  39. // 打开信号量
  40. sem = sem_open(sem_name.c_str(), 0);
  41. if (sem == SEM_FAILED) {
  42. throw std::runtime_error("Failed to open semaphore for camera " + std::to_string(camera_id));
  43. }
  44. }
  45. ~SharedMemoryReader() {
  46. // 释放共享内存
  47. if (shm_ptr != nullptr) {
  48. munmap(shm_ptr, SHM_SIZE);
  49. }
  50. if (shm_fd != -1) {
  51. close(shm_fd);
  52. }
  53. // 关闭信号量
  54. if (sem != nullptr) {
  55. sem_close(sem);
  56. }
  57. }
  58. void read_and_display() {
  59. cv::Mat frame(HEIGHT, WIDTH, CV_8UC3); // 假设图像为 640x480 的 RGB 格式
  60. while (true) {
  61. // 等待信号量通知
  62. sem_wait(sem);
  63. // 从共享内存中读取数据
  64. std::memcpy(frame.data, shm_ptr, SHM_SIZE);
  65. static int count = 0;
  66. count++;
  67. // 显示图像
  68. // cv::imshow("Camera " + std::to_string(camera_id), frame);
  69. cv:imwrite("./test_"+ std::to_string(count)+".jpg", frame);
  70. std::cout << "Camera " << camera_id << " frame " << count << " saved.\n";
  71. // 按 ESC 键退出
  72. if (cv::waitKey(30) == 27) {
  73. break;
  74. }
  75. }
  76. }
  77. };
  78. int main() {
  79. try {
  80. // 假设读取相机 0 的共享内存
  81. SharedMemoryReader reader(0);
  82. reader.read_and_display();
  83. } catch (const std::exception& e) {
  84. std::cerr << "Error: " << e.what() << std::endl;
  85. }
  86. return 0;
  87. }