123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- #include <opencv2/opencv.hpp>
- #include <opencv2/imgcodecs.hpp>
- #include <fcntl.h>
- #include <sys/mman.h>
- #include <sys/stat.h>
- #include <semaphore.h>
- #include <unistd.h>
- #include <iostream>
- #include <string>
- const int WIDTH = 640;
- const int HEIGHT = 480;
- const size_t SHM_SIZE = HEIGHT * WIDTH * 3; // 假设图像为640x480,RGB格式
- class SharedMemoryReader {
- private:
- int camera_id;
- std::string shm_name;
- std::string sem_name;
- int shm_fd;
- void* shm_ptr;
- sem_t* sem;
- public:
- SharedMemoryReader(int id)
- : camera_id(id),
- shm_name("/camera_data_" + std::to_string(id)),
- sem_name("/camera_semaphore_" + std::to_string(id)),
- shm_fd(-1),
- shm_ptr(nullptr),
- sem(nullptr) {
- // 打开共享内存
- shm_fd = shm_open(shm_name.c_str(), O_RDONLY, 0666);
- if (shm_fd == -1) {
- throw std::runtime_error("Failed to open shared memory for camera " + std::to_string(camera_id));
- }
- // 将共享内存映射到进程地址空间
- shm_ptr = mmap(0, SHM_SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
- if (shm_ptr == MAP_FAILED) {
- throw std::runtime_error("Failed to map shared memory for camera " + std::to_string(camera_id));
- }
- // 打开信号量
- sem = sem_open(sem_name.c_str(), 0);
- if (sem == SEM_FAILED) {
- throw std::runtime_error("Failed to open semaphore for camera " + std::to_string(camera_id));
- }
- }
- ~SharedMemoryReader() {
- // 释放共享内存
- if (shm_ptr != nullptr) {
- munmap(shm_ptr, SHM_SIZE);
- }
- if (shm_fd != -1) {
- close(shm_fd);
- }
- // 关闭信号量
- if (sem != nullptr) {
- sem_close(sem);
- }
- }
- void read_and_display() {
- cv::Mat frame(HEIGHT, WIDTH, CV_8UC3); // 假设图像为 640x480 的 RGB 格式
- while (true) {
- // 等待信号量通知
- sem_wait(sem);
- // 从共享内存中读取数据
- std::memcpy(frame.data, shm_ptr, SHM_SIZE);
- static int count = 0;
- count++;
- // 显示图像
- // cv::imshow("Camera " + std::to_string(camera_id), frame);
- cv:imwrite("./test_"+ std::to_string(count)+".jpg", frame);
- std::cout << "Camera " << camera_id << " frame " << count << " saved.\n";
- // 按 ESC 键退出
- if (cv::waitKey(30) == 27) {
- break;
- }
- }
- }
- };
- int main() {
- try {
- // 假设读取相机 0 的共享内存
- SharedMemoryReader reader(0);
- reader.read_and_display();
- } catch (const std::exception& e) {
- std::cerr << "Error: " << e.what() << std::endl;
- }
- return 0;
- }
|