参考原文和实现效果见下帖:
https://blog.csdn.net/jkjj2015/article/details/87160291
效果如下:
该博主用的是Java,我这仿写了C#的,代码如下:
private void ReduceBackGround(Image tempImage)
{
Mat src = tempImage.Mat;
CvInvoke.CvtColor(src, src,ColorConversion.Bgr2Gray);
src.ConvertTo(src,DepthType.Cv32F, 1.0 / 255);
Mat dst3=ReduceBackGroundAlgorithm(src,0);
CvInvoke.GaussianBlur(dst3, dst3, new Size(1, 1), 0, 0,BorderType.Default); //Size(width, heigth),width,heigth参数可调,两个参数相同,默认值1,调节范围1-9(需为奇数);
//dst3 = ColorGradation(dst3);
CvInvoke.AdaptiveThreshold(dst3,dst3,255,0,0,31,13);//去除背景色后再进一步二值化,C参数可调,默认值30,调节范围1-50;
this.imageBox2.Image = dst3;
}
private Mat ImageSharp(Mat src,int nAmount)
{
Mat dst= new Mat();
double sigma = 3;
// int threshold = 1;
float amount = nAmount / 100.0f;
Mat imgBlurred=new Mat();
CvInvoke.GaussianBlur(src, imgBlurred, new Size(7,7), sigma, sigma,BorderType.Default);
Mat temp_sub= new Mat();
//Mat temp_abs= new Mat();
CvInvoke.Subtract(src,imgBlurred,temp_sub);
// Core.convertScaleAbs(temp_sub,temp_abs);
// Mat lowContrastMask = new Mat();
//Imgproc.threshold(temp_abs,lowContrastMask,threshold,255,1);
//Mat temp_gen= new Mat();
CvInvoke.AddWeighted(src,1,temp_sub,amount,0,dst);
// dst = src+temp_sub*amount;
//src.copyTo(dst, lowContrastMask);
return dst;
}
private Mat ReduceBackGroundAlgorithm(Mat src,int flag) {
Mat gauss = new Mat();
Mat dst2 = new Mat();
Mat dst3 = new Mat();
if (flag==1) {
CvInvoke.GaussianBlur(src, gauss, new Size(31, 31), 0, 0,BorderType.Default);
}
else
{
CvInvoke.Blur(src, gauss, new Size(101,101),new Point(0,0));
}
CvInvoke.Divide(src, gauss, dst2);
dst2=ImageSharp(dst2, 101);
//Imgproc.GaussianBlur(dst2, dst2, new Size(3,3), 0,0,4);//
dst2.ConvertTo(dst3,DepthType.Cv8U,255);
return dst3;
}
初开博客,目的是交流与合作,本人QQ:273651820。