该demo为将像素值为0标注为噪点,图片为灰度图(可自行修改为RGB),填补方式为8邻域像素均值填补,只修复噪点
#include <iostream>
#include <opencv2/opencv.hpp>
#include <stdio.h>
using namespace std;
using namespace cv;
int main() {
char buf1[100];
char buf2[100];
vector<Point2i> NeihborPos;
NeihborPos.push_back(Point2i(-1, 0));
NeihborPos.push_back(Point2i(1, 0));
NeihborPos.push_back(Point2i(0, -1));
NeihborPos.push_back(Point2i(0, 1));
NeihborPos.push_back(Point2i(-1, -1));
NeihborPos.push_back(Point2i(-1, 1));
NeihborPos.push_back(Point2i(1, -1));
NeihborPos.push_back(Point2i(1, 1));
int Neihbor_count=8;
int CurrX=0,CurrY=0;
for (int i=1;i<8;++i){
sprintf(buf1,"/home/yangjunfeng/workspace_lj/workspace/clion_project/disp_new/disp_%d.png",i);
sprintf(buf2,"/home/yangjunfeng/workspace_lj/workspace/clion_project/disp_new2/disp_%d.png",i);
Mat src=imread(buf1,CV_LOAD_IMAGE_GRAYSCALE);
Mat dst = Mat::zeros(src.size(), CV_8UC1);
for(int i = 0; i < src.rows; ++i)
{
int bad_c_count=0;
vector<Point2i> temp_local;
uchar* s_data = src.ptr<uchar>(i);
uchar* d_data = dst.ptr<uchar>(i);
for(int j = 0; j < src.cols; ++j)
{
//temp_local.push_back(Point2i(j,i));
if(s_data[j] != 0) d_data[j]=s_data[j];
else{
temp_local.push_back(Point2i(j,i));
bad_c_count++;
int pixel_sum=0;
int nerbor_suit=0;
for(int k=0;k<Neihbor_count;++k){
CurrX=temp_local.at(bad_c_count-1).x+NeihborPos.at(k).x;
CurrY=temp_local.at(bad_c_count-1).y+NeihborPos.at(k).y;
if (CurrX>=0&&CurrX<src.cols&&CurrY>=0&&CurrY<src.rows&&src.at<uchar>(CurrY, CurrX)!=0){
pixel_sum+=src.at<uchar>(CurrY, CurrX);
nerbor_suit++;
}
}
//cout<<"pixel_sum:"<<pixel_sum<<endl<<"nerbor_suit:"<<nerbor_suit<<endl;
//float kkk=pixel_sum/nerbor_suit;
//cout<<kkk<<endl;
if (nerbor_suit!=0)
d_data[j]=int(pixel_sum/nerbor_suit);
//d_data[j]=255;
}
}
}
imwrite(buf2,dst);
}
std::cout << "Hello, World!" << std::endl;
return 0;
}
原图:
修正后: