一、效果展示

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.highgui.HighGui;
  5. import org.opencv.imgcodecs.Imgcodecs;
  6. /**
  7. * @author :张音乐
  8. * @date :Created in 2021/4/26 下午3:07
  9. * @description:图片合成
  10. * @email: zhangyule1993@sina.com
  11. * @version: 1.0
  12. */
  13. public class ImageSynthesis {
  14. static {
  15. System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
  16. }
  17. public static void main(String[] args) {
  18. // 加载图片矩阵
  19. String filePath = "D:\\upload\\background.jpg";
  20. Mat background = Imgcodecs.imread(filePath);
  21. // Mat resized = new Mat(background.height(), background.height(), background.type());
  22. // Imgproc.resize(background, resized, resized.size(), 0.7, 0.7, Imgproc.INTER_CUBIC);
  23. // HighGui.imshow("background", resized);
  24. String imgPath = "D:\\upload\\dog.jpg";
  25. Mat img = Imgcodecs.imread(imgPath);
  26. int imgRows = img.rows();
  27. int imgCols = img.cols();
  28. // HighGui.imshow("img", imgResized);
  29. //
  30. // Mat imgResized = new Mat(img.height(), img.height(), img.type());
  31. // Imgproc.resize(img, imgResized, imgResized.size(), 0.4, 0.4, Imgproc.INTER_CUBIC);
  32. // 灰度
  33. // Mat gray = new Mat();
  34. // Imgproc.cvtColor(imgResized, gray, Imgproc.COLOR_BGRA2GRAY);
  35. // 高斯模糊
  36. // Imgproc.GaussianBlur(gray, gray, new Size(3, 3), 0);
  37. // 二值化
  38. // Mat thresh = new Mat();
  39. // threshold(gray, thresh, 0, 255, Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU);
  40. // Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(3, 3));
  41. // 膨胀操作
  42. // Mat hiMask = new Mat();
  43. // Imgproc.dilate(thresh, hiMask, kernel);
  44. for(int i = 0; i < imgRows; i++) {
  45. for(int j = 0; j < imgCols; j++) {
  46. background.put(200 + i,400 + j, img.get(i, j));
  47. }
  48. }
  49. HighGui.imshow("结果", background);
  50. HighGui.waitKey(0);
  51. // 释放所有的窗体资源
  52. HighGui.destroyAllWindows();
  53. }
  54. }