Java OpenCV将小图像层叠到具有透明度

时间:2017-09-17 15:24:24

标签: 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

1 个答案:

答案 0 :(得分:0)

找到了完全符合我需要的功能。

 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);
      }
  } 
}