Can I write a cv::Mat as JPEG data to a named pipe?

我的梦境 提交于 2020-01-04 07:51:22

问题


I need to write my image data in JPEG form to a named pipe (created with mkfifo) in Linux.

But I couldn't find a way to get this working. I can write with imwrite to a plain file, but not to this FIFO.

Code:

img = cv::Mat(cv::Size(videoWidth, videoHeight), CV_8UC3, videoBuffer);
cv::namedWindow("Display window", cv::WINDOW_NORMAL);
cv::imshow("Display window", img); // Show our image inside it.            
cv::imwrite("image.jpg", img);

How can I use a named pipe instead of a file?


回答1:


I found the solution for this.

//using namespace cv; // do not use opencv namespace, because of the write method

// open named pipe
if ((fifo = open(outPipe.c_str(), O_WRONLY)) < 0) {
    printf("Fifo error: %s\n", strerror(errno));
    return 1;
}

cv::Mat img = cv::Mat(cv::Size(videoWidth, videoHeight), CV_8UC3, videoBuffer); // videoBuffer directly from libav transcode to memory      
cv::namedWindow("Display window", cv::WINDOW_NORMAL); // Create a window for display.
cv::imshow("Display window", img); // Show our image inside it.            

// encode image to jpeg
std::vector<uchar> buff; //buffer for coding
std::vector<int> param(2);
param[0] = cv::IMWRITE_JPEG_QUALITY;
param[1] = 95; //default(95) 0-100
cv::imencode(".jpg", img, buff, param);
printf("Image data size: %lu bytes (%d kB)\n", buff.size(), (int) (buff.size() / 1024));

// write encoded image to pipe/fifo
if (write(fifo, buff.data(), buff.size()) < 0) {
    printf("Error write image data to fifo!\n");
}

close(fifo);
  1. Open the named pipe (waits until a reader is present)

  2. Read the data in opencv mat

  3. Encode the opencv mat image in jpeg format

  4. Write the encoded data to pipe



来源:https://stackoverflow.com/questions/36064471/can-i-write-a-cvmat-as-jpeg-data-to-a-named-pipe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!