2

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?

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
RamG
  • 71
  • 5

1 Answers1

5

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

RamG
  • 71
  • 5