Segmentation fault (core dumped)

I have a loop for in which I try to call a function sum
1
2
3
4
5
6
7
8
9
10
11
12
float sum(cv::Mat img, int startedY, int startedX, int w) {
std::cout << "started x=" <<startedX << "started y=" <<startedY<< std::endl;
    float res = 0.0f;

for (int j = startedY - ((w - 1) / 2) ; j < startedY + ((w + 1) / 2); j++)
    for (int i = startedX - ((w - 1) / 2); i < startedX + ((w + 1) / 2); i++) {
         {
            if ((i >= 0 && i < img.size().width) && (j >= 0  && j < img.size().height)) {
                res += img.at<float>(j,i);
            }}}
    return res;
}

1
2
3
4
5
6
for (int l = 0; l < imgSource.size().height; l++){
          for (int k = 0; k < imgSource.size().width; k++){
        if( (k >= 0 && k < imgSource.size().width) && (l >= 0  && l < imgSource.size().height) ) {
      std::cout << "k= "<<k <<"  l= "<<l<< " wmax= "<< wmax<<std::endl; 
      newImgMax.at<float>(k,l) =(float)sum(imgMax,k,l, wmax) / (wmax * wmax);
       }}}


for k=0 and l=0 the program works fine and returns a value but for k=0 and l=1 the call of the function(sum(imgMax,0,1,1)) doesn't pass,it crashes and shows a segmentation fault core dumped.This is my output
1
2
3
4
5
6
k= 0  l= 0 wmax= 1
startedX= 0/ startedY= 0
i= 0
j= 0
k= 0  l= 1 wmax= 1
Segmentation fault (core dumped)

After several tests I found that the function "sum" is called only once independently of indexes(rows,cols),for example when I try :

std::cout << " (1,0)= " <<sum(imgMax,1, 0, wmax) <<std::endl;

it returns a value and when I try :

1
2
std::cout << " (2,3)= " <<sum(imgMax,2, 3, wmax) <<std::endl;
std::cout << " (1,0)= " <<sum(imgMax,1, 0, wmax) <<std::endl;


it returns the result of the first and crashes after any suggestions please ?
You need to provide a minimal snip that reproduces your issue.


I think that you are confusing the meaning of your coordinates.
When you access a matrix you'll to m.at<type>( row, column ); or
m.at<type>(y, x); where y = total_rows-row

in `sum()' you ask for started{Y,X} but treat it as if it where the center of an square.
In your call to the function you make `k' to signify `y' but traverse the `width'


I think that you may implement this as
1
2
3
4
cv::Mat roi = image(
/*here a row range, or a rectangle*/
);
cv::sum( roi ) / roi.size().area();
but considering that you are going to do it a lot of ranges, you better do a matrix that stores the sum from (K,L) to (0,0), then to get the sum in the range you'll do sum(right, bottom) - sum(left, bottom) - sum(right, top) + sum (left, top)
Now I'm sure the function is called once,the problem is not about rows or colomns here's another example :

1
2
3
std::cout << " (4,1)= " <<sum(imgMax,4, 1, wmax) <<std::endl;
std::cout << " (2,3)= " <<sum(imgMax,2, 3, wmax) <<std::endl;
std::cout << " (1,0)= " <<sum(imgMax,1, 0, wmax) <<std::endl;


it returns the value of the first call and crashes after
Topic archived. No new replies allowed.