Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert char array to Opencv Mat

Tags:

char

opencv

mat

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

char buf[Max_size];
like image 251
Electra Avatar asked Dec 24 '22 06:12

Electra


2 Answers

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.

like image 140
Humam Helfawi Avatar answered Jan 05 '23 11:01

Humam Helfawi


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

like image 43
Filip Sivák Avatar answered Jan 05 '23 11:01

Filip Sivák