问题
I have a data (unsigned char*) with RGB 16 bits format R:5 G:6 B:5
How can I set this data to IplImage format?
I can start with:
unsigned char* data = ...data...;
IplImage *img = cvCreateImage(cvSize(800,480), IPL_DEPTH_8U, 3); // Should it be 16?
cvSetData(img,data,800*2); // Here is where I am not sure
回答1:
You are going to need to convert from IPL_DEPTH_16U
(single-channel) to IPL_DEPTH_8U
(three-channel).
Below is some code I wrote up quickly (this should work, but I don't have a 565 image handy to test it with, so I would try this on a few test images first...)
#include <opencv2/core/core.hpp>
#include <iostream>
using namespace std;
using namespace cv;
#define RED_MASK 0xF800
#define GREEN_MASK 0x07E0
#define BLUE_MASK 0x001F
int main(int argc, char* argv[])
{
IplImage *rgb565Image = cvCreateImage(cvSize(800, 480), IPL_DEPTH_16U, 1);
IplImage *rgb888Image = cvCreateImage(cvSize(800, 480), IPL_DEPTH_8U, 3);
unsigned short* rgb565Data = (unsigned short*)rgb565Image->imageData;
int rgb565Step = rgb565Image->widthStep / sizeof(unsigned short);
uchar* rgb888Data = (uchar*)rgb888Image->imageData;
float factor5Bit = 255.0 / 31.0;
float factor6Bit = 255.0 / 63.0;
for(int i = 0; i < rgb565Image->height; i++)
{
for(int j = 0; j < rgb565Image->width; j++)
{
unsigned short rgb565 = rgb565Data[i*rgb565Step + j];
uchar r5 = (rgb565 & RED_MASK) >> 11;
uchar g6 = (rgb565 & GREEN_MASK) >> 5;
uchar b5 = (rgb565 & BLUE_MASK);
// round answer to closest intensity in 8-bit space...
uchar r8 = floor((r5 * factor5Bit) + 0.5);
uchar g8 = floor((g6 * factor6Bit) + 0.5);
uchar b8 = floor((b5 * factor5Bit) + 0.5);
rgb888Data[i*rgb888Image->widthStep + j] = r8;
rgb888Data[i*rgb888Image->widthStep + (j + 1)] = g8;
rgb888Data[i*rgb888Image->widthStep + (j + 2)] = b8;
}
}
return 0;
}
You can probably make this faster using a lookup table for the conversion, but what I have should be good for instructive uses.
Also, have a look at this SO post for further discussion of this topic.
来源:https://stackoverflow.com/questions/8687739/opencv-with-rgb-16bits