简体   繁体   中英

C++ - Convert RGB 1-D Array to OpenCV Mat Image

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 (ie 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:

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);

The code above saves a grayscale, elongated version of my color image. I have also tried:

cv::Mat image = cv::Mat(width, height, CV_8U, (unsigned*)data);
cv::imwrite("Test.jpg", image);

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?

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.

If you want to obtain a color image, the type CV_8U is not enough. This type represents a single-channel 8-bit image. What you want is CV_8UC4 if your data is indeed an array of 32-bit integers.

cv::Mat image = cv::Mat(width, height, CV_8UC4, (unsigned*)data);

The 4th channel represents alpha value (transparency). If you want to drop it, you can ask OpenCV to convert your image to a CV_8UC3 .

image = cv2.cvtColor(image, cv2.CV_BGRA2BGR)

Also, bear in mind that OpenCV represents color values in the BGR order. Make sure that your data is in the BGR format when creating your image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM