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

时间:2014-01-12 21:49:54

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

生成的图像是一种重影,显示背景图像重复多次,前景图像以损坏的方式重复显示。

任何线索?

1 个答案:

答案 0 :(得分:1)

感谢Rosa,对于那些感兴趣的人,以下是我将Rosa指出的C ++片段翻译成Java的方式:

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