I recently found myself having to do a few interesting conversions in C++ to pass images between different formats and/ or libraries, including OpenCV, MATLAB, and some unusual custom formats. I'm going to post some code snippets here that do some of these conversions as I suspect they may be useful for others.
Keep in mind that, generally, image data is always stored in one long array, and you have a pointer to the beginning of that array. So, the question is, as you increment your way through the array contents, in what order are you traversing the image's data? E.g. are the first three elements the RGB values of the first pixel in the top left corner of the image? Or are they the R components of the first three pixels moving right along the top row of the image? Or something else entirely?