title: Mask an image in opencv
body: <p>I'm trying to split two images along a seam, and then blend them together. In this process, I need to cut out each image along the seam by applying a mask. How can I apply a mask? I tried <code>bitwise_and</code> and <code>multiply</code>ing the mask and the image, but neither worked.</p>
  
  <pre><code>int pano_width = left_template_width + right_template_width - roi_width;  
  // add zeros to the right of the left template
  Mat full_left = Mat::zeros(roi_height, pano_width, CV_32FC3);
  Mat tmp_l = full_left(Rect(0,0, left_template_width, roi_height));
  imshow("Scene mask", mask0f3);
  imshow("Cropped scene", cropped_scene);
  Mat left_masked;
  //bitwise_and(cropped_scene, mask0f3, left_masked); // full_left looks all black
  multiply(cropped_scene, mask0f3, left_masked); // full_left looks like the scene mask, but with an extra black rectangle on the right side
  left_masked.copyTo(tmp_l);
  imshow("Full left", full_left);
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/EXTlV.png" alt="enter image description here"></p>
  
  <p><img src="https://i.stack.imgur.com/jSg69.png" alt="enter image description here"></p>
  
  <p><img src="https://i.stack.imgur.com/pvGri.png" alt="enter image description here"></p>
  
  <p>I resorted to a terribly efficient, but working, hack:</p>
  
  <pre><code>void apply_mask(Mat&amp; img, Mat mask) {
      CV_Assert(img.rows == mask.rows);
      CV_Assert(img.cols == mask.cols);
      print_mat_type(img);
      print_mat_type(mask);
      for (int r = 0; r &lt; mask.rows; r++) {
          for (int c = 0; c &lt; mask.cols; c++) {
              if (mask.at&lt;uchar&gt;(r, c) == 0) {
                  img.at&lt;Vec3f&gt;(r, c) = Vec3f(0, 0, 0);
              }
          }
      }
  }
  </code></pre>