How to pass an image to a 2D array using Matlab MEX?
Show older comments
I want to read some image to run a C++ MEX function to process this image. The image is originally stored as a Matlab 3D matrix, and then converted to a 2D matrix and each slice of the image is stored as a 1D vector. Here is some example codes below.
The MEX function:
include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
unsigned int** ubuff;
size_t col_ubuff = mxGetN(prhs[0]);
size_t row_ubuff = mxGetM(prhs[0]);
ubuff = (unsigned int **)mxCalloc(col_ubuff, row_ubuff);
for(int x = 0; x < col_ubuff; x++) {
ubuff[x] = (unsigned int *) mxCalloc(row_ubuff, sizeof(unsigned int));
}
for (int col=0; col < col_ubuff; col++) {
for (int row=0; row < row_ubuff; row++) {
ubuff[col][row] = mxGetPr(prhs[0])[row+col*row_ubuff];
}
}
unsigned int the_pixel_i_want = ubuff[16][2*32 + 2];
printf ("Debug: %d\n\n", the_pixel_i_want);
return;
}
2. The program can be compiled; however, the results of running the program is strange; for example, I have some test codes and test image with all pixels to be 188,
%%Test input image as 2D array clc; clf; clear all; close all;
volImage = 188.*ones(32,32,32);
volImageVec = reshape(volImage, 32*32, 32)';
volImageVec = uint32(volImageVec);
TestInputImage(volImageVec');
But the output sometimes be 188 and sometimes be 0. Is there a memory leak somewhere in my code? Thanks very much for your help.
Accepted Answer
More Answers (1)
Aaronne
on 15 Feb 2014
Categories
Find more on MATLAB Coder in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!