2014-09-26 103 views
0

我有一个图像4通道,我需要覆盖它的一堆照片。在具有3个通道的图片上,叠加效果很好,但在具有Alpha通道的图片上,图片背景变为黑色。覆盖4通道图像

原始图片:http://img.blog.csdn.net/20130610074054484

叠加图片:http://imgur.com/mlVAN0A

这是做的叠加代码:

void overlayImage(const cv::Mat &background, const cv::Mat &foreground, 
       cv::Mat &output, cv::Point2i location) 
{ 
    background.copyTo(output); 

    for(int y = std::max(location.y , 0); y < background.rows; ++y) 
    { 
     int fY = y - location.y; 
     if(fY >= foreground.rows) 
      break; 

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

      double opacity = ((double)foreground.data[fY * foreground.step + fX * foreground.channels() + 3])/255.; 

      for(int c = 0; opacity > 0 && c < output.channels(); ++c) 
      { 
       unsigned char foregroundPx = foreground.data[fY * foreground.step + fX * foreground.channels() + c]; 
       unsigned char backgroundPx = background.data[y * background.step + x * background.channels() + c]; 
       output.data[y*output.step + output.channels()*x + c] = 
       backgroundPx * (1.-opacity) + foregroundPx * opacity; 
      } 
     } 
    } 
} 
+0

已经有了一个看[使用添加(混合)两个图像的OpenCV(http://docs.opencv.org/doc/tutorials/core/adding_images/adding_images.html)? – 2014-09-26 08:01:56

+0

是的,我有。不管怎样,高贵的imshow的实现不能正确显示任何透明的图像。如果我在最终图像上调用imshow(覆盖后),背景是黑色的。如果我在最终图像上调用imwrite,图像看起来不错。 – 2014-09-26 08:19:29

回答

0

这是因为你用1 - 不透明度的背景图像。如果背景图像的不透明度为0,则backgroundpixel的不透明度将为1,而不是以前的0。

您必须计算两个图像的结果不透明度fpr,两个图像也可以为0。

克劳斯

+0

我真的不明白我应该改变的代码是诚实的.. – 2014-09-26 08:32:24

+0

我在编码和解码图像在某些时候的问题是,当我打电话解码,第二个参数是CV_LOAD_IMAGE_ANYCOLOR而不是CV_LOAD_IMAGE_UNCHANGED。谢谢你,克劳斯和多比。答案现在可以结束。 – 2014-09-26 08:41:11