//QImage图像转换为halcon格式图像,
HObject CImageFormatConvertion::QImage2HObject(QImage qImage)
{
HObject hImage;
int width, height;
try
{
GenEmptyObj(&hImage);
width = qImage.width();
height = qImage.height();
if (qImage.bits() == NULL || width <= 0 || height <= 0)
{
MessageBox(NULL, TEXT("qImage is null !"), TEXT("MSG"), MB_OK);
return hImage ;
}
qDebug("qImage.format()--:%d", qImage.format());
//只转化 Format_Indexed8 Format_RGB32 Format_RGB888 格式图像
if(QImage::Format_Indexed8 == qImage.format())//灰度图像
{
uchar *dataGray = new uchar[width*height];
for(int i=0; i<height; i++)
{
memcpy(dataGray+width*i,qImage.bits()+qImage.bytesPerLine()*i,width);
}
GenImage1(&hImage,"byte",(Hlong)width,(Hlong)height,(Hlong)dataGray);
delete[] dataGray;
}
else if(QImage::Format_RGB32 == qImage.format())//RGB32图像
{
uchar *dataR = new uchar[width*height];
uchar *dataG = new uchar[width*height];
uchar *dataB = new uchar[width*height];
uchar *data = qImage.bits();
for(int i=0; i<height; i++)
{
int lineNum = i*qImage.bytesPerLine();
for(int j=0;j<width; j++)
{
dataB[i*width+j] = data[lineNum+j*4];
dataG[i*width+j] = data[lineNum+j*4+1];
dataR[i*width+j] = data[lineNum+j*4+2];
}
}
GenImage3(&hImage,"byte",(Hlong)width,(Hlong)height,(Hlong)dataR,(Hlong)dataG,(Hlong)dataB);
delete[] dataR;
delete[] dataG;
delete[] dataB;
}
else if(QImage::Format_RGB888 == qImage.format())//24位图像
{
uchar *dataR = new uchar[width*height];
uchar *dataG = new uchar[width*height];
uchar *dataB = new uchar[width*height];
uchar *data = qImage.bits();
for(int i=0; i<height; i++)
{
int lineNum = i*qImage.bytesPerLine();
for(int j=0;j<width; j++)
{
dataR[i*width+j] = data[lineNum+j*3];
dataG[i*width+j] = data[lineNum+j*3+1];
dataB[i*width+j] = data[lineNum+j*3+2];
}
}
GenImage3(&hImage,"byte",(Hlong)width,(Hlong)height,(Hlong)dataR,(Hlong)dataG,(Hlong)dataB);
delete[] dataR;
delete[] dataG;
delete[] dataB;
}
else
{
MessageBox(NULL, TEXT("image format is wrong!"), TEXT("MSG"), MB_OK);
}
}catch(HException)
{
}
return hImage;
} |