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
1 #include <opencv2/highgui/highgui.hpp>
2 #include <opencv2/core/core.hpp>
3 #include "lowp.h"
4 //#include <stdlib.h>
5 using namespace cv;
6
7 void medFilter(Mat &, Mat &, int);
8 int main(){
9 Mat img = imread("home.jpg",1);
10 Mat out;
11 medFilter(img,out,7);
12 namedWindow("Example");
13 imshow("Example", out);
14 waitKey(0);
15 destroyWindow("Example");
16 }
17
//lowp.h
33 void medFilter(Mat &img, Mat &out, int size){
34 Mat low(img.rows, img.cols, img.type());
35 int r = img.rows;
36 int c = img.cols;
37 const int ch = img.channels();
38 int hist[255];
39 int w = 0;
40 int *win;
41 win = new int(size*size);
42 for(int h = 0; h<255; h++){
43 hist[h] = 0;
44 }
45 for(int i = 0; i<r; i++){
46 for(int j = 0; j<c; j++){
47 for(int chi = 0; chi < ch; chi++){
48 if(i>=size/2 && i<r-size/2 && j>=size/2 && j<c-size/2){
49 for(int u = -size/2 ; u<=size/2; u++){
50 for(int v = -size/2; v<=size/2; v++){
51 win[w] = *(img.ptr<uchar>(i + u) + (j + v)*ch + chi);
52 w++;
53 }
54 }
55 w = 0;
56 *(low.ptr<uchar>(i) + j*ch + chi) = getMedian(win, hist, (size*size));
57 }else{
58 *(low.ptr<uchar>(i) + j*ch + chi) = *(img.ptr<uchar>(i) + j*ch + chi);
59 }
60 }
61 }
62 }
63 out = low;
64 }
66 uchar getMedian(int* w, int* hist, int size){
67 uchar h;
68 for(int i = 0; i<size; i++){
69 hist[w[i]] ++;
70 }
71 int sum = 0;
72 for(h = 0; h<255; h++){
73 sum += hist[h];
74 if(sum>size/2) break;
75 }
76 for(int i = 0; i<size; i++){
77 hist[w[i]] = 0;
78 }
79 return h;
80 }