Segmentation fault in ~ImageCodecInitializer() while exiting main()
I am trying to implement a median filter(for practice). The program showed the output image correctly but it ended with a segmentation fault. The following error occurred just before exiting main(){}
Program received signal SIGSEGV, Segmentation fault. 0x00007ffff78bf789 in cv::ImageCodecInitializer::~ImageCodecInitializer() () from /usr/local/lib/libopencv_imgcodecs.so.3.2
//mainFile.cpp
#include <opencv2/highgui/highgui.h
#include <opencv2/core/core.hpp>
#include "lowp.h"
//#include <stdlib.h>
using namespace cv;
void medFilter(Mat &, Mat &, int);
int main(){
Mat img = imread("home.jpg",1);
Mat out;
medFilter(img,out,7);
namedWindow("Example");
imshow("Example", out);
waitKey(0);
destroyWindow("Example");
}
//lowp.h
void medFilter(Mat &img, Mat &out, int size){
Mat low(img.rows, img.cols, img.type());
int r = img.rows;
int c = img.cols;
const int ch = img.channels();
int hist[256]; //changed from int hist[255] -- as correctly suggested by LBerger
int w = 0;
int *win;
win = new int(size*size);
for(int h = 0; h<255; h++){
hist[h] = 0;
}
for(int i = 0; i<r; i++){
for(int j = 0; j<c; j++){
for(int chi = 0; chi < ch; chi++){
if(i>=size/2 && i<r-size/2 && j>=size/2 && j<c-size/2){
for(int u = -size/2 ; u<=size/2; u++){
for(int v = -size/2; v<=size/2; v++){
win[w] = *(img.ptr<uchar>(i + u) + (j + v)*ch + chi);
w++;
}
}
w = 0;
*(low.ptr<uchar>(i) + j*ch + chi) = getMedian(win, hist, (size*size));
}else{
*(low.ptr<uchar>(i) + j*ch + chi) = *(img.ptr<uchar>(i) + j*ch + chi);
}
}
}
}
out = low;
}
uchar getMedian(int* w, int* hist, int size){
uchar h;
for(int i = 0; i<size; i++){
hist[w[i]] ++;
}
int sum = 0;
for(h = 0; h<255; h++){
sum += hist[h];
if(sum>size/2) break;
}
for(int i = 0; i<size; i++){
hist[w[i]] = 0;
}
return h;
}
there is a buffer overrun somewhere in your code. now learn to use a debugger, please.
berak.. I used gdb: The program executed well till line no. 16; after which just before exiting the main function gave a dump.
good !
admittedly, this will be a hard nut.
Can you delete line number?
LBerger: Line numbers are removed.
berak- The error is happening in the destructor: cv::ImageCodecInitializer::~ImageCodecInitializer(). Which is OpenCV Library code. Cant seem to find whats going on.
no, the error is caused by a buffer overrun somewhere in your code.
hist[255] is wrong it should be hist[256] ... Now your program is not really nice Ok it is an exercise. First in your histogram you can use that is a moving window...
LBerger: hist[255] has been changed to hist[256] as you have correctly suggested. Problem still persists though.
berak: I have debugged the code. My custom function medFilter works correctly. imshow displays the output which is correct. Error is thrown at the closing curly bracket of the main() function.