6

I have defined an array char buf[], and need to convert it into Opencv Mat. Is there a way?

char buf[Max_size];
Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160
Electra
  • 71
  • 1
  • 1
  • 3
  • it would be better if you give some details. Why you want this? what is the data? where you are going to use the output cv::Mat – Humam Helfawi May 09 '16 at 13:45
  • In my server, I am receiving an image in bytes from a client and store them in array of char buf[]. then I want to send buf[] to be processed by a function SURF which only accepts Mat variable. In the solution you provided, do I have to put that line inside a for loop? – Electra May 09 '16 at 14:02
  • No you do not need to put it in a loop – Humam Helfawi May 10 '16 at 05:35

2 Answers2

9

There is nothing that called: "Converting char array to cv::Mat". cv::Mat is a container that represents an image in the memory. It may own the data and may not. If you want to create a cv::Mat to represent an image that its bitmap data in some char array, you may use the following code. This is assuming that you know the rows and the columns of the image.

cv::Mat my_mat(rows,cols,CV_8UC1,&buf[0]); //in case of BGR image use CV_8UC3

Keep in mind that cv::Mat in this case does not hold the ownership of the data. You have delete your data manually. However, since it is a stack array, you do not need to anything.

Sneaky Polar Bear
  • 1,611
  • 2
  • 17
  • 29
Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160
  • 2
    For anyone else googling; if your data is `unsigned char*`, you need to cast to `void*` in the constructor call for the overload resolution to find the proper constructor. – oarfish Jan 05 '18 at 11:11
3

I think that Humams's answer is correct, however, here is a complete C++ example on how to get an image from an unsigned char array.

    #include <opencv2/opencv.hpp>  

    unsigned char img_data[] = {
        // first row, 4 colored pixels
        0, 0, 0,
        255, 0, 0,
        0, 0, 0 ,
        0, 255, 0,

        // second row, 4 colored pixels
        0, 0, 255,
        0, 0, 0,
        255, 0, 255,
        0, 0, 0
    };

    // get a correct pointer to the data
    unsigned char * img_data_ptr = (unsigned char*) &img_data;

    cv::Mat img(2, 4, CV_8UC3, img_data_ptr);
    cv::cvtColor(img, img, cv::COLOR_BGR2RGB);
    cv::imwrite("/out/myimage.png", img);

The example is dockerized at https://github.com/FilipSivak/opencv-minimal