I have defined an array char buf[], and need to convert it into Opencv Mat. Is there a way?
char buf[Max_size];
I have defined an array char buf[], and need to convert it into Opencv Mat. Is there a way?
char buf[Max_size];
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.
unsigned char*
, you need to cast to void*
in the constructor call for the overload resolution to find the proper constructor. –
Brachy 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
© 2022 - 2024 — McMap. All rights reserved.