我想使用网络摄像头通过命名管道将视频帧流从父进程发送到子进程。父级显示发送的帧,而子级显示接收的帧。我使用openCV 2.4.12在UBuntu 14.04上访问和显示视频帧。然而,它只发送一帧并冻结。我不知道是什么原因造成了这个问题。如果我发送一个图像,但当我尝试发送流时,这个代码在第一帧就冻结了,那么这个代码工作得很好。
这是代码:
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
using namespace cv;
using namespace std;
void ChildProcess(void); /* child process prototype */
void ParentProcess(void); /* parent process prototype */
int main()
{
pid_t pid;
pid = fork();
if (pid == 0)
ChildProcess();
else
ParentProcess();
}
void ChildProcess(void)
{
int fd2 = open("/home/eelab/vidpipe",O_RDONLY);
for(;;)
{
int rows = 480;
int cols = 640;
int nchan = 3;
int totalbytes = rows*cols*nchan;
int buflen = cols*nchan;
int ret;
//int fd1 = open("/dev/xillybus_read_32",O_RDONLY);
uchar buf[buflen];
uchar datarray[totalbytes];
Mat img(rows,cols,CV_8UC3);
int j;
int k = 0;
int num = totalbytes/buflen;
int bread = 0;
while(bread<totalbytes)
{
ret=read(fd2,buf,buflen);
for ( j = 0 ; j<= (ret-1);j++ )
{
datarray[j+k] = buf[j];
}
k = k+ret;
bread = bread+ret;
}
img.data = datarray;
namedWindow( "Received image", WINDOW_AUTOSIZE );
imshow( "Received image", img );
waitKey(0);
}
close(fd2);
}
void ParentProcess(void)
{
int check;
int fd;
int totalbytes;
int buflen;
int count = 0;
fd = open("/home/eelab/vidpipe",O_WRONLY);
if (fd < 1)
{
perror("open error");
}
VideoCapture cap(0);
for(;;)
{
Mat frame;
cap >> frame;
totalbytes = frame.total()*frame.elemSize();
buflen = (frame.cols*3);
uchar *framepointer = frame.data;
int bwritten = 0;
int ret;
uchar* buf;
buf = framepointer;
int num = totalbytes/buflen;
while(bwritten<totalbytes)
{
ret = write(fd,buf,buflen);
write(fd,NULL,0);
buf = buf + ret;
bwritten = bwritten+ret;
}
namedWindow( "Sent image", WINDOW_AUTOSIZE );
imshow( "Sent image", frame );
waitKey(0);
}
close(fd);
}
请帮忙,我怎样才能得到源源不断的水流?
waitKey(0);
将阻止该过程,直到按下某个键为止。如果您更改为waitKey(1);
,它将在>= 1 ms
之后自动进行。如果速度不够快(例如,你的fps很高),你应该切换到不同的GUI库(例如Qt)。