2017-09-17 155 views
0

我想寫一個圖像覆蓋在另一個圖像頂部的透明矩形圖像的功能,但它沒有分層的圖像只是刪除了我重疊和透明度貫穿整個圖像。這是我的代碼。Java OpenCV將圖像小到透明的大圖像

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

+0

務必發佈您的圖片和結果。 – zindarod

+0

@Zindarod對不起,編輯。 – Jake

+0

這裏的問題是複製後,覆蓋圖像中的Alpha通道覆蓋目標圖像中的Alpha通道。 – zindarod

回答

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