Advertisement
Guest User

overlayImage

a guest
Jul 30th, 2013
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. void overlayImage(const cv::Mat &background, const cv::Mat &foreground,
  2.   cv::Mat &output, cv::Point2i location)
  3. {
  4.   background.copyTo(output);
  5.  
  6.  
  7.   // start at the row indicated by location, or at row 0 if location.y is negative.
  8.   for(int y = std::max(location.y , 0); y < background.rows; ++y)
  9.   {
  10.     int fY = y - location.y; // because of the translation
  11.  
  12.     // we are done of we have processed all rows of the foreground image.
  13.     if(fY >= foreground.rows)
  14.       break;
  15.  
  16.     // start at the column indicated by location,
  17.  
  18.     // or at column 0 if location.x is negative.
  19.     for(int x = std::max(location.x, 0); x < background.cols; ++x)
  20.     {
  21.       int fX = x - location.x; // because of the translation.
  22.  
  23.       // we are done with this row if the column is outside of the foreground image.
  24.       if(fX >= foreground.cols)
  25.         break;
  26.  
  27.       // determine the opacity of the foregrond pixel, using its fourth (alpha) channel.
  28.       double opacity =
  29.         ((double)foreground.data[fY * foreground.step + fX * foreground.channels() + 3])
  30.  
  31.         / 255.;
  32.  
  33.  
  34.       // and now combine the background and foreground pixel, using the opacity,
  35.  
  36.       // but only if opacity > 0.
  37.       for(int c = 0; opacity > 0 && c < output.channels(); ++c)
  38.       {
  39.         unsigned char foregroundPx =
  40.           foreground.data[fY * foreground.step + fX * foreground.channels() + c];
  41.         unsigned char backgroundPx =
  42.           background.data[y * background.step + x * background.channels() + c];
  43.         output.data[y*output.step + output.channels()*x + c] =
  44.           backgroundPx * (1.-opacity) + foregroundPx * opacity;
  45.       }
  46.     }
  47.   }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement