title: Merging channels in OpenCV
body: <p>I need to create a 'red' image from a grayscale image. I am using this code:</p>
  
  <pre><code>void build_red(const cv::Mat&amp; in, cv::Mat&amp; out) {
      out = Mat::zeros(in.rows, in.cols, CV_8UC1);
  
      Mat zeros = Mat::zeros(in.rows, in.cols, CV_8UC1);
      Mat tmp;
      in.convertTo(tmp, CV_8UC1);
  
      vector&lt;Mat&gt; ch;
      ch.push_back(zeros);
      ch.push_back(zeros);
      ch.push_back(tmp);
  
      cout &lt;&lt; "Using " &lt;&lt; ch.size() &lt;&lt; " channels" &lt;&lt; endl;
      merge(ch, out);
  } // build_red
  </code></pre>
  
  <p>With some explanations:</p>
  
  <pre><code>void build_red(const cv::Mat&amp; in, cv::Mat&amp; out) {
  </code></pre>
  
  <p>in is the input matrix, out the output.</p>
  
  <pre><code>out = Mat::zeros(in.rows, in.cols, CV_8UC1);
  </code></pre>
  
  <p>allocate some space for out (may be useless, but part of my attempts)</p>
  
  <pre><code>    Mat zeros = Mat::zeros(in.rows, in.cols, CV_8UC1);
      Mat tmp;
      in.convertTo(tmp, CV_8UC1);
  </code></pre>
  
  <p>Create an empty matrix with the same size and convert the input image to single-channel uchar.</p>
  
  <pre><code>    vector&lt;Mat&gt; ch;
      ch.push_back(zeros);
      ch.push_back(zeros);
      ch.push_back(tmp);
  
      cout &lt;&lt; "Using " &lt;&lt; ch.size() &lt;&lt; " channels" &lt;&lt; endl;
      merge(ch, out);
  </code></pre>
  
  <p>Create a vector with three channels, then merge them into 'out'.</p>
  
  <p>However, when I run the code I get the following message:</p>
  
  <pre><code>     Using 3 channels
  </code></pre>
  
  <p>and the following exception:</p>
  
  <pre><code>OpenCV Error: Bad number of channels (Source image must have 1, 3 or 4 channels) 
  in cvConvertImage, file /[...]/libs/OpenCV-2.4.0/modules/highgui/src/utils.cpp, 
  line 611
  terminate called after throwing an instance of 'cv::Exception'
  what():  /[...]/libs/OpenCV-2.4.0/modules/highgui/src/utils.cpp:611: 
  error: (-15) Source image must have 1, 3 or 4 channels in function cvConvertImage
  </code></pre>
  
  <p>Could you please help me? From my inexperienced point of view, the type of the images is the same and the number of channels is correct.</p>