Convert char array to Opencv Mat
Asked Answered
G

2

6

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

char buf[Max_size];
Gumbotil answered 9/5, 2016 at 13:36 Comment(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::MatGlottis
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?Gumbotil
No you do not need to put it in a loopGlottis
G
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.

Glottis answered 9/5, 2016 at 13:43 Comment(1)
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.Brachy
R
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

Ruthenian answered 21/4, 2020 at 7:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.