Convert Mat to char array (and vice-versa)
Hi,
I tried converting a grayscale, single channel Mat (type: 8UC1) to a char[] array but somewhere it crashes. I am using android ndk and I'm coding in c++ in one of the native classes. I only get fatal signal 11 as error (probably refers to wrong memory access?).
Here's the code I am using:
unsigned char buffer[height * width];
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
uchar& uxy = myMat.at<uchar>(j, i);
int color = (int) uxy;
buffer[j * width + i] = color;
}
}
I want to use a byte[] buffer to store the image (mat) and I need to access it's elements like this: y * width + x (where y=row index, x=column index). Because I don't have a byte[] structure in Android native, I decided to use a char[] array.
Is there any faster option? And I also want to convert the byte[] array (in my case, char[] array) back to a Mat. Thanks!
Edit:
Converting back code (untested!):
Mat convertToMat(unsigned char *buffer) {
Mat tmp(width, height, CV_8UC1);
for (int x = 0; x < height; x++) {
for (int y = 0; y < width; y++) {
int value = (int) buffer[x * width + y];
tmp.at<int>(y, x) = value;
}
}
return tmp;
}
myMat = convertToMat(buffer);
I don't really see what you are trying to do with casting it from/to int. Do you know that an int is 4 bytes? Further I would suggest you to find the "somewhere" it crashes with a debugger.