我正在尝试实现中值过滤器(用于练习)。该程序正确显示输出图像,但它以分段错误结束。在退出main(){}之前发生以下错误。即:完成main中的每一行代码后。
gdb的结果:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff78bf789 in cv::ImageCodecInitializer::~ImageCodecInitializer() ()
from /usr/local/lib/libopencv_imgcodecs.so.3.2
//Code:
//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;
int hist[256];
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;
}