Java OpenCV 将小图像分层到具有透明度的大图像上

标签 java opencv mat

我正在尝试编写一个函数,将一个图像覆盖在另一个图像之上的具有透明度的矩形上,但是它不会对图像进行分层,它只是删除了我覆盖的部分,并且透明度穿过整个图像。这是我的代码。

public static void overlayImage(String imagePath, String overlayPath, int x, int y, int width, int height) {
    Mat overlay = Imgcodecs.imread(overlayPath, Imgcodecs.IMREAD_UNCHANGED);
    Mat image = Imgcodecs.imread(imagePath, Imgcodecs.IMREAD_UNCHANGED);

    Rectangle rect = new Rectangle(x, y, width, height);
    Imgproc.resize(overlay, overlay, rect.size());
    Mat submat = image.submat(new Rect(rect.x, rect.y, overlay.cols(), overlay.rows()));
    overlay.copyTo(submat);
    Imgcodecs.imwrite(imagePath, image);
}

编辑:以下是一些示例图片: 之前:

enter image description here

之后:

enter image description here

最佳答案

发现这个函数完全符合我的需要。

 public static void overlayImage(Mat background,Mat foreground,Mat output, Point location){

  background.copyTo(output);

  for(int y = (int) Math.max(location.y , 0); y < background.rows(); ++y){

   int fY = (int) (y - location.y);

   if(fY >= foreground.rows())
          break;

      for(int x = (int) Math.max(location.x, 0); x < background.cols(); ++x){
          int fX = (int) (x - location.x);
          if(fX >= foreground.cols()){
           break;
          }

           double opacity;
           double[] finalPixelValue = new double[4];

           opacity = foreground.get(fY , fX)[3];

           finalPixelValue[0] = background.get(y, x)[0];
           finalPixelValue[1] = background.get(y, x)[1];
           finalPixelValue[2] = background.get(y, x)[2];
           finalPixelValue[3] = background.get(y, x)[3];

           for(int c = 0;  c < output.channels(); ++c){
               if(opacity > 0){
                   double foregroundPx =  foreground.get(fY, fX)[c];
                   double backgroundPx =  background.get(y, x)[c];

                   float fOpacity = (float) (opacity / 255);
                   finalPixelValue[c] = ((backgroundPx * ( 1.0 - fOpacity)) + (foregroundPx * fOpacity));
                   if(c==3){
                       finalPixelValue[c] = foreground.get(fY,fX)[3];
                   }
               }
           }
           output.put(y, x,finalPixelValue);
      }
  } 
}

关于Java OpenCV 将小图像分层到具有透明度的大图像上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46265726/

相关文章:

android - Android OpenCV MatToBitmap导致黑色图像

java - 为什么PatriciaTrie中无法访问 `floorEntry`等方法?

opencv - 从视频中聚类人脸

覆盖单元格数据时 MATLAB matfile 的大小会增加

opencv - Mat OpenCV 矩形 ROI : access violation

c++ - 静态 OpenCV 库中 undefined reference

java - 有没有一种方法可以将文件加载到java中的多个类中,而不必每次都调用它们?

java - 如何检测 JFace 对话框(或其他模式组件)何时在 Eclipse RAP 应用程序中打开?

java - 如何将 if else 语句中的每个系统输出存储到一个解决方案字符串中

python - 如何从 OpenCV 中已标记的图像中获取区域属性?