You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.2 KiB
C++

#include <iostream>
#include <opencv2/opencv.hpp>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
// 打开视频文件
cv::VideoCapture cap("1.mp4");
if (!cap.isOpened()) {
std::cerr << "Failed to open video file" << std::endl;
return 1;
}
// 获取视频帧率
double fps = cap.get(cv::CAP_PROP_FPS);
std::cout << "Original FPS: " << fps << std::endl;
// 获取图像尺寸
int width = cap.get(cv::CAP_PROP_FRAME_WIDTH);
int height = cap.get(cv::CAP_PROP_FRAME_HEIGHT);
int type = CV_8UC3; // 假设图像类型为 8 位 3 通道彩色图像
// 计算图像数据的大小
size_t imageDataSize = width * height * CV_ELEM_SIZE(type);
// 创建共享内存
int shmFd = shm_open("/video_shm", O_CREAT | O_RDWR, 0666);
if (shmFd == -1) {
std::cerr << "Failed to create shared memory" << std::endl;
return 1;
}
size_t shmSize = sizeof(int) * 3 + imageDataSize + sizeof(double); // 计算共享内存大小
ftruncate(shmFd, shmSize);
void* sharedMemory = mmap(NULL, shmSize, PROT_READ | PROT_WRITE, MAP_SHARED, shmFd, 0);
if (sharedMemory == MAP_FAILED) {
std::cerr << "Failed to map shared memory" << std::endl;
return 1;
}
// 获取共享内存指针
char* dataPtr = static_cast<char*>(sharedMemory);
// 逐帧读取并发送
cv::Mat frame;
while (cap.read(frame)) {
// 将图像尺寸复制到共享内存
memcpy(dataPtr, &width, sizeof(int));
dataPtr += sizeof(int);
memcpy(dataPtr, &height, sizeof(int));
dataPtr += sizeof(int);
memcpy(dataPtr, &type, sizeof(int));
dataPtr += sizeof(int);
// 将图像数据复制到共享内存
memcpy(dataPtr, frame.data, imageDataSize);
dataPtr += imageDataSize;
// 将帧率信息复制到共享内存
memcpy(dataPtr, &fps, sizeof(double));
// 等待接收方读取共享内存
usleep(1000);
// 打印帧率
std::cout << "Sent FPS: " << fps << std::endl;
}
// 关闭共享内存
munmap(sharedMemory, shmSize);
close(shmFd);
shm_unlink("/video_shm");
return 0;
}