title: C++ - Convert RGB 1-D Array to OpenCV Mat Image
body: <p>I'm using C++ and I have a void* array of image data. I've determined that it's an array of RGB pixel values, and I have information about the width and height of the resulting image. Each pixel value is an integer of interleaved R, G, and B integers (i.e. 123456 = R:12, G:34, B:56). I need to convert this array to an OpenCV Mat image. I've found many examples of this online, but none have been successful for me. Here is an abbreviated version of the code that has come closest to working for me:</p>
  
  <pre><code>cv::Mat image = cv::Mat(width*height*4, 1, CV_8U, (unsigned*)data);
  cv::Mat reshaped = image.reshape(0, height);
  cv::imwrite("Test.jpg", reshaped);
  </code></pre>
  
  <p>The code above saves a grayscale, elongated version of my color image. I have also tried:</p>
  
  <pre><code>cv::Mat image = cv::Mat(width, height, CV_8U, (unsigned*)data);
  cv::imwrite("Test.jpg", image);
  </code></pre>
  
  <p>The code above saves a chopped-up, grayscale version of my color image. Anything else I've tried (CV_16U, CV_32F, (byte*)data, etc.) has just returned a black image. What am I doing wrong?</p>
  
  <p>Alternatively, I'm only using OpenCV because I can't find an easier way of saving an image from an array using C++ without using a for loop. I've been successful in saving a PPM image by looping through all of the pixels and saving them individually, but now I need something more efficient. If there's a different way to save images from an array, I would be happy to use that instead.</p>