一、展示效果

image.pngimage.pngimage.png

二、完整代码

  1. package com.biubiu.example;
  2. import org.opencv.core.Core;
  3. import org.opencv.core.Mat;
  4. import org.opencv.core.Scalar;
  5. import org.opencv.core.Size;
  6. import org.opencv.highgui.HighGui;
  7. import org.opencv.imgcodecs.Imgcodecs;
  8. import org.opencv.imgproc.Imgproc;
  9. /**
  10. * @author :张音乐
  11. * @date :Created in 2021/4/26 下午3:52
  12. * @description:替换图片的背景图片
  13. * @email: zhangyule1993@sina.com
  14. * @version: 1.0
  15. */
  16. public class ImageBackgroundImage {
  17. static {
  18. System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
  19. }
  20. public static void main(String[] args) {
  21. String backPath = "D:\\upload\\back.jpg";
  22. Mat back = Imgcodecs.imread(backPath);
  23. Mat resized = new Mat(back.height(), back.height(), back.type());
  24. Imgproc.resize(back, resized, resized.size(), 0.7, 0.7, Imgproc.INTER_CUBIC);
  25. String imgPath = "D:\\upload\\green_pic.jpg";
  26. Mat img = Imgcodecs.imread(imgPath);
  27. Scalar lowerb = new Scalar(new double[] { 0, 0, 0 });
  28. // RGB 三个值, R和B接近255, 扣到的图越好, 但是 容易产生边缘。
  29. Scalar upperb = new Scalar(new double[] { 254, 255, 254 });
  30. // 转换为hsv图像
  31. Mat hsv = new Mat();
  32. Imgproc.cvtColor(img, hsv, Imgproc.COLOR_BGR2HSV);
  33. // 高斯模糊
  34. Mat thresh = new Mat();
  35. Imgproc.GaussianBlur(hsv, thresh, new Size(1, 1), 0);
  36. // HighGui.imshow("thresh", thresh);
  37. // 二值化
  38. Mat mask = new Mat();
  39. Core.inRange(thresh, lowerb, upperb, mask);
  40. // 形态学开, 膨胀处理
  41. Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(1, 1));
  42. Mat hiMask = new Mat();
  43. Imgproc.dilate(mask, hiMask, kernel);
  44. // HighGui.imshow("hiMask", hiMask);
  45. // 遍历, 抠图
  46. for(int i = 0; i < img.rows(); i++) {
  47. for(int j = 0; j < img.cols(); j++) {
  48. // 去除白点的。
  49. if(hiMask.get(i, j)[0] != 0) {
  50. back.put(i, j, img.get(i, j));
  51. }
  52. }
  53. }
  54. HighGui.imshow("img", back);
  55. HighGui.waitKey(0);
  56. // 释放所有的窗体资源
  57. HighGui.destroyAllWindows();
  58. }
  59. }