OpenCV 如何进行图片修复

修复函数:

.inpaint(imageSrc, imageMask, imageDst, radius, Photo.INPAINT_TELEA);

imageSrc 是修复之前的图片
imageMask 是修复模板
imageDst 修复结果
radius 是修复半径
Photo.INPAINT_TELEA 是修复方法

准备原图片

java Opencv 图片修复 Photo_photo


我们可以看到的是在图片的右下角 “百家号/阿虹说娱乐”

我们如何把这个去除,这是我们的目的

准备修复模板

如何创建修复模板其实是使用这个函数的一个比较重点的事情
imageMask 是有要求的 要求是单通道,而且是Scalar 的值除了要修复的部分其他的全部为0
并且大小和原图片相等
我们先加载原图片图片:

=Imgcodecs.imread("D:\\360MoveData\\Users\\lxn\\Desktop\\opencv\\xf.jpg");

我们接下来通过原图片来生成模板

=Imgcodecs.imread("D:\\360MoveData\\Users\\lxn\\Desktop\\opencv\\xf.jpg");
Mat imageGray=new Mat();


Mat dts=new Mat(imageSource.size(), CvType.CV_8SC3);
//转换为灰度图
Imgproc.cvtColor(imageSource, imageGray, Imgproc.COLOR_BGR2GRAY);

//创建模板
Mat imageMask =new Mat(imageSource.size(), CvType.CV_8UC1, new Scalar(0,0,0));

//阀值化
Imgproc.threshold(imageGray, imageMask, 150, 160, Imgproc.THRESH_BINARY);

int width=imageSource.cols();
int height=imageSource.rows();
//创建模板图层
Mat imageMask1=new Mat(imageMask.size(), CvType.CV_8UC1, new Scalar(0));

//在模板图层上截取要修复的部分
Mat mat=imageMask.submat(new Rect(new Point(width-200,height-50), new Point(width,height)));

//高斯处理均衡化
Mat blurMat=new Mat();
Imgproc.GaussianBlur(mat, blurMat, new Size(5, 5), 3);

//把要修复的部分放到模板图层上
Rect rect=new Rect(new Point(width-200,height-50),mat.size());
blurMat.copyTo(imageMask1.submat(rect));

我们最终获取到的修复模板如下:

java Opencv 图片修复 Photo_opencv_02

使用修复模板修复图片

.inpaint(imageSource, imageMask1, dts, 5, Photo.INPAINT_TELEA);

修复结果:

java Opencv 图片修复 Photo_opencv_03


我们发现在有下家的"百家号/。。。" 已经不见了

总结下来就是在创建模板的时候比较麻烦
因为整个图片 中有很多和钥修复的部分RGB是一样的,所以我们要在阀值化之后的图片要进行截取,截取出来要修复的部分,然后放到黑色的模板上
最终代码:

public void testInpaint2() {

//原图
Mat imageSource=Imgcodecs.imread("D:\\360MoveData\\Users\\lxn\\Desktop\\opencv\\xf.jpg");
Mat imageGray=new Mat();


Mat dts=new Mat(imageSource.size(), CvType.CV_8SC3);
//转换为灰度图
Imgproc.cvtColor(imageSource, imageGray, Imgproc.COLOR_BGR2GRAY);
Mat imageMask =new Mat(imageSource.size(), CvType.CV_8UC1, new Scalar(0,0,0));
Imgproc.threshold(imageGray, imageMask, 150, 160, Imgproc.THRESH_BINARY);
int width=imageSource.cols();
int height=imageSource.rows();
Mat imageMask1=new Mat(imageMask.size(), CvType.CV_8UC1, new Scalar(0));
Mat mat=imageMask.submat(new Rect(new Point(width-200,height-50), new Point(width,height)));

Mat blurMat=new Mat();
Imgproc.GaussianBlur(mat, blurMat, new Size(5, 5), 3);

Rect rect=new Rect(new Point(width-200,height-50),mat.size());
blurMat.copyTo(imageMask1.submat(rect));
HighGui.imshow("修复前",imageSource);
HighGui.imshow("修复模板", imageMask1);
Photo.inpaint(imageSource, imageMask1, dts, 5, Photo.INPAINT_TELEA);
HighGui.imshow("修复结果", dts);
HighGui.waitKey(0);
}
public static void main(String[] args) throws Exception {
ResourceBundle bundle = ResourceBundle.getBundle("opencv");
String opencvDllName = bundle.getString("opencv.dllpath");
System.load(opencvDllName);
new PhotoTest().testInpaint2();
}

希望对你有所帮助