Ask Your Question

Revision history [back]

Segmentation fault when writing to subranges of Mat

Hi there,

I'm new to OpenCV a have some trouble regarding writing to a subrange of a Mat-Object.

The code below iterates a given Image. For each pixel, it takes pixel within a range of 5x5, finds the brightest pixel, and put all other pixel to 0.

I call the function multiple times. After a random number of calls the function gives me a segmentation fault or "malloc memory corruption". Sometimes I can call the function 10 times with no problems sometimes only twice, then the program stops.

I tracked down the problem to the line, where I write to the original image using the subimage.

subimage.at<uchar>(rowSubimage,colSubimage) = 0;

There is the function that drives me crazy:

void findMaxAndBlackout(Mat& image, int size){

Point centralPoint;
Size rangeSize = Size(size,size);
Mat subimage;
Rect range;

// iterate the image
for(int row = 0; row <= image.rows-size; row++){
    for(int col = 0; col <= image.cols-size; col++){
        centralPoint = Point(col,row);
        range = Rect(centralPoint, rangeSize);

            // slice submatrix and find max
        subimage = image(range);
        double max;
        minMaxLoc( subimage, NULL, &max, NULL, NULL );

            // iterate the surrounding 
        for(int rowSubimage  = 0; rowSubimage <= subimage.rows; rowSubimage++){
            for(int colSubimage = 0; colSubimage <= subimage.cols; colSubimage++){
                if(subimage.at<uchar>(rowSubimage,colSubimage) < max){
                    //this line cause the trouble
                    subimage.at<uchar>(rowSubimage,colSubimage) = 0;
                }
            }
        }
    }
}}

The Mat-Object is generated using:

Mat houghImage = imread("small_schachbrett1_cam.png", CV_LOAD_IMAGE_GRAYSCALE);

Please help me understand the problem.

If you know a better or more efficient way to achieve the same result please let me know. I am open for any improvements

Regards benniz