Java 将具有透明度的png合并到另一个图像上

Java 将具有透明度的png合并到另一个图像上,java,opencv,Java,Opencv,我正在尝试在背景上合并具有一定透明度的png: Mat frg = Highgui.imread( "path/to/foreground/image.png" ), -1 ); Mat bkg = Highgui.imread( "path/to/background/image.png" ), -1 ); // Create mask from foreground. Mat mask = new Mat( frg.width(), frg.height(), 24 );

我正在尝试在背景上合并具有一定透明度的png:

 Mat frg = Highgui.imread( "path/to/foreground/image.png" ), -1 );    
 Mat bkg = Highgui.imread( "path/to/background/image.png" ), -1 );

 // Create mask from foreground.
 Mat mask = new Mat( frg.width(), frg.height(), 24 );
 double f[] = { 1, 1, 1, 0 };
 double e[] = { 0, 0, 0, 0 };

 for ( int y = 0; y < ( int )( frg.rows() ); ++y ) {
   for ( int x = 0; x < ( int )( frg.cols() ); ++x ) {     
     double info[] = frg.get( y, x );                 

     if ( info[3] > 0 ) {
       mask.put( y, x, e );
     } else {
       mask.put( y, x, f );
     }
   }
 } 

 // Copy foreground onto background using mask.
 frg.copyTo( bkg, mask );

 Highgui.imwrite( "path/to/result/image.png", bkg );
Mat frg=Highgui.imread(“path/to/foreground/image.png”),-1);
Mat bkg=Highgui.imread(“path/to/background/image.png”),-1);
//从前景创建遮罩。
垫罩=新垫(frg.宽度(),frg.高度(),24);
双f[]={1,1,1,0};
双e[]={0,0,0,0};
对于(int y=0;y<(int)(frg.rows());+y){
对于(int x=0;x<(int)(frg.cols());++x){
双信息[]=frg.get(y,x);
如果(信息[3]>0){
掩模放置(y,x,e);
}否则{
掩模放置(y,x,f);
}
}
} 
//使用遮罩将前景复制到背景上。
frg.copyTo(bkg,遮罩);
imwrite(“path/to/result/image.png”,bkg);
生成的图像是一种重影,显示多次重复的背景图像和损坏的前景图像


任何线索?

< P>谢谢罗萨,对于那些感兴趣的人,这里是我如何翻译成java的C++片段,由罗萨指出:

private Mat overtrayImage( Mat background, Mat foreground ) {
  // The background and the foreground are assumed to be of the same size.
  Mat destination = new Mat( background.size(), background.type() );

  for ( int y = 0; y < ( int )( background.rows() ); ++y ) {
    for ( int x = 0; x < ( int )( background.cols() ); ++x ) {     
      double b[] = background.get( y, x );
      double f[] = foreground.get( y, x );

      double alpha = f[3] / 255.0;

      double d[] = new double[3];
      for ( int k = 0; k < 3; ++k ) {
        d[k] = f[k] * alpha + b[k] * ( 1.0 - alpha );
      }

      destination.put( y, x, d );
    }
  } 

  return destination;
}
private Mat OverrayImage(Mat背景、Mat前景){
//假设背景和前景大小相同。
Mat destination=new Mat(background.size(),background.type());
对于(int y=0;y<(int)(background.rows());+y){
对于(intx=0;x<(int)(background.cols());++x){
双b[]=background.get(y,x);
双f[]=前景。获取(y,x);
双α=f[3]/255.0;
双d[]=新双d[3];
对于(int k=0;k<3;++k){
d[k]=f[k]*α+b[k]*(1.0-α);
}
目的地。放置(y,x,d);
}
} 
返回目的地;
}
请看这里: