Skip to content

Instantly share code, notes, and snippets.

@sepfy
Last active March 24, 2019 05:29
Show Gist options
  • Save sepfy/abf9676f2f03dc79571a9c77746e584f to your computer and use it in GitHub Desktop.
Save sepfy/abf9676f2f03dc79571a9c77746e584f to your computer and use it in GitHub Desktop.
Share opencv image data in Linux
#include "opencv2/opencv.hpp"
// For IPC
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
using namespace std;
using namespace cv;
// 640*480 RGB image
const int buf_sz = 640*480*3;
key_t shmid;
int key = 3345678;
char *shm = NULL;
void init_shm() {
if((shmid = shmget(key, buf_sz + 1, IPC_CREAT | 0666 )) < 0 ) {
cout << "shmget failed" << endl;
exit(1);
}
if((shm = (char*)shmat(shmid, NULL, 0) ) == (char *)-1) {
cout << "shmat failed" << endl;
exit(1);
}
}
int main(int, char**)
{
init_shm();
for(;;)
{
Mat frame(480, 640, CV_8UC3);
if(*shm == 1) {
memcpy(frame.data, shm + 1, buf_sz);
imshow("frame", frame);
if(waitKey(30) >= 0) break;
*shm = 0;
}
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}
all:
g++ server.cc -lopencv_core -lopencv_highgui -lopencv_imgproc -lopencv_videoio -o server
g++ client.cc -lopencv_core -lopencv_highgui -lopencv_imgproc -lopencv_videoio -o client
#include "opencv2/opencv.hpp"
// For IPC
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
using namespace std;
using namespace cv;
// 640*480 RGB image
const int buf_sz = 640*480*3;
key_t shmid;
int key = 3345678;
char *shm = NULL;
void init_shm() {
if((shmid = shmget(key, buf_sz + 1, IPC_CREAT | 0666 )) < 0 ) {
cout << "shmget failed" << endl;
exit(1);
}
if((shm = (char*)shmat(shmid, NULL, 0) ) == (char *)-1) {
cout << "shmat failed" << endl;
exit(1);
}
}
int main(int, char**)
{
VideoCapture cap(0); // open the default camera
if(!cap.isOpened()) // check if we succeeded
return -1;
cout << "width=" << cap.get(CAP_PROP_FRAME_WIDTH) <<
", height=" << cap.get(CAP_PROP_FRAME_HEIGHT) << endl;
init_shm();
// Initialize buffer
// Buffer = [header][data]
memset(shm, 0, buf_sz + 1);
// *shm == 0, accept
// *shm == 1, pending
for(;;)
{
Mat frame;
cap >> frame;
if(*shm == 0) {
memcpy(shm + 1, frame.data, buf_sz);
*shm = 1;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment