user2979747
user2979747

Reputation:

opencv malloc errors when passing mat refrerences

I'm currently porting matlab code to opencv under obj-c/c++ and I'm encounter a malloc problem. Everything works fine when passing a Mat, but if I pass a channel from imageChannel:

cv::Mat *imageChannel = new cv::Mat[c];
cv::split(image, imageChannel); This is my code:

it throws several malloc errors:

OpenCvTest(15537,0xb0081000) malloc: *** error for object 0x11915000: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug

Here is my Code:

+(cv::Mat)boxFilterWithImage:(cv::Mat)image r:(int)r
{
    int hei = image.rows;
    int wid = image.cols;
    int c = image.channels();
    cv::Mat imDst = cv::Mat::zeros(hei, wid, CV_32FC(c));
    cv::Mat imCum = [self cumSumWith:image dim:1];

    imCum.colRange(r, 2*r).copyTo(imDst.colRange(0, r));

    cv::Mat calc = imCum.colRange((2*r+2)-1, wid-1) - imCum.colRange(0, (wid-2*r-1)-1); 
    calc.copyTo(imDst.colRange(r+1, (wid-r)-1));

    cv::repeat(imCum.col(wid-1), 1, r, calc);
    calc -= imCum.colRange((wid-2*r)-1, wid-r-1);
    calc.copyTo(imDst.colRange((wid-r+1)-2, wid-1));

    imCum = [self cumSumWith:imDst dim:2];
    imCum.rowRange(r, 2*r).copyTo(imDst.rowRange(0, r));
    calc = imCum.rowRange((2*r+2)-1, hei-1) - imCum.rowRange(0, (hei-2*r-1)-1);
    calc.copyTo(imDst.rowRange(r+1, hei-r-1));
    cv::repeat(imCum.row(hei-1), r, 1, calc);
    calc -= imCum.rowRange((hei-2*r)-2, (hei-r-1)-1);
    calc.copyTo(imDst.rowRange(hei-r-1, hei-1));

    return imDst;
}

So does anyone has a clue on this?

EDIT: so i had the time to debug it: it seems like that it has problems with

imCum.rowRange(r, 2*r).copyTo(imDst.rowRange(0, r));

the first submatrix get released after its extracted.

Regards, Carsten

Upvotes: 1

Views: 1562

Answers (1)

Andrey  Smorodov
Andrey Smorodov

Reputation: 10852

I'm usually process channels in this way:

vector<Mat> src_arr;
cv::split(src,src_arr);
Mat tmp;
    // You can do the loop here 
MyFuncForSingleChannel(src_arr[0]);
tmp.copyTo(src_arr[0]);
MyFuncForSingleChannel(src_arr[1]);
tmp.copyTo(src_arr[1]);
MyFuncForSingleChannel(src_arr[2]);
tmp.copyTo(src_arr[2]);

cv::merge(src_arr,dst);

Upvotes: 1

Related Questions