Segmentation fault (core dumped) image processing c++/opencv
I want to apply a smooth to an image,for that purpose I create the function "sum" Here's my code
double sum(cv::Mat img, int startedX, int startedY, int w) {
double res = 0;
std::cout << "startedX= " << startedX<< "/ startedY= " << startedY<< std::endl;
for (int i = startedX - ((w - 1) / 2); i < startedX + ((w + 1) / 2); i++) {
std::cout << "i= " << i << std::endl;
for (int j = startedY - ((w - 1) / 2) ; j < startedY + ((w + 1) / 2); j++) {std::cout << " j= " <<j<< std::endl;
if ((i >= 0 && i < img.size().width) && (j >= 0 && j < img.size().height)) {
res += img.at<float>(i,j); }}}
return res;}
This is a portion of my main function where the program crashes :
for (int k = 0; k < imgSource.size().width; k++) {
for (int l = 0; l < imgSource.size().height; l++) {
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
k= 0 l= 0 wmax= 1
startedX= 0/ startedY= 0
i= 0
j= 0
k= 0 l= 1 wmax= 1
Segmentation fault (core dumped)
method at is at<float>(row,col)
don't reinvent the wheel: if you want to apply a custom smooth kernel, do it with the already optimized OpenCV functions. And always remember that per pixel loops are a terrible idea
After several tests I found that the call to the function "sum" is done only once independently of indexes(rows,cols) for example when I try :
it returns a value and when I try :
it returns the result of the first and crashes after any suggestions please ?
As @LorenaGdL said you should use opencv function to make a convolution. Except if your problem is an exercice about loop.
@choukri el please follow the guidance given ... you are reinventing the sole purpose of libraries like OpenCV, which is supplying general computer vision functionality. Smoothing is need in almost all cases, so it already exists and it would be stupid to create your own pixel wise operations...
okay I will see these libraries, thank you for your advices and your replies @LorenaGdL@LBerger@StevenPuttemans