OpenNI RGB image to OpenCV BGR IplImage conversion?
Pergunta
The image which one can get from OpenNI Image Meta Data is arranged as an RGB image. I would like to convert it to OpenCV IplImage which by default assumes the data to be stored as BGR. I use the following code:
XnUInt8 * pImage = new XnUInt8 [640*480*3];
memcpy(pImage,imageMD.Data(),640*480*3*sizeof(XnUInt8));
XnUInt8 temp;
for(size_t row=0; row<480; row++){
for(size_t col=0;col<3*640; col+=3){
size_t index = row*3*640+col;
temp = pImage[index];
pImage[index] = pImage[index+2];
pImage[index+2] = temp;
}
}
img->imageData = (char*) pImage;
What is the best way (fastest) in C/C++ to perform this conversion such that RGB image becomes BGR (in IplImage format)?
Solução
Is it not easy to use the color conversion function of OpenCV?
imgColor->imageData = (char*) pImage;
cvCvtColor( imgColor, imgColor, CV_BGR2RGB);
Outras dicas
There are some interesting references out there.
For instance, the QImage to IplImage convertion shown here, that also converts RGB to BGR:
static IplImage* qImage2IplImage(const QImage& qImage)
{
int width = qImage.width();
int height = qImage.height();
// Creates a iplImage with 3 channels
IplImage *img = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
char * imgBuffer = img->imageData;
//Remove alpha channel
int jump = (qImage.hasAlphaChannel()) ? 4 : 3;
for (int y=0;y<img->height;y++)
{
QByteArray a((const char*)qImage.scanLine(y), qImage.bytesPerLine());
for (int i=0; i<a.size(); i+=jump)
{
//Swap from RGB to BGR
imgBuffer[2] = a[i];
imgBuffer[1] = a[i+1];
imgBuffer[0] = a[i+2];
imgBuffer+=3;
}
}
return img;
}
There are several posts here besides this one that show how to iterate on IplImage data.
There might be more than that (if the encoding is not openni_wrapper::Image::RGB). A good example can be found in the openni_image.cpp file where they use in line 170 the function fillRGB.