Basler相机Bayer格式转Qt RGB888

【推荐养成的习惯】

1、函数返回bool

2、函数内优先判断参数是否存在可用

3、使用try  catch

【正题】

无论什么品牌的相机,Bayer转RGB都涉及到插值(参考官网解释),因此建议使用官方SDK里的函数进行转换。针对Basler相机,代码如下:

bool BaslerCamera::toQImage(const CGrabResultPtr& ptrGrabResult, QImage& OutImage)    //输出型参数用&修饰,因为它是要被改变的。
{    
    if (ptrGrabResult ==NULL)    //判断是否存在
    {
        return false;
    }
    try
    {
        int width = static_cast<int>(ptrGrabResult->GetWidth());
        int height = static_cast<int>(ptrGrabResult->GetHeight());
        if (ptrGrabResult->GetPixelType() == Pylon::PixelType_Mono8)
        {
            uchar* buffer = (uchar*)ptrGrabResult->GetBuffer();
            OutImage = QImage(buffer, width, height, QImage::Format_Grayscale8).copy();//深拷贝,防止 QPixmap::fromImage(img)访问冲突
        }
        else //bayer格式等
        {
            try
            {
                CImageFormatConverter   fc;
                fc.OutputPixelFormat = PixelType_RGB8packed;//通过官方函数先转为 RGB8
                //fc.InconvertibleEdgeHandling = InconvertibleEdgeHandling_SetZero;   //默认右、下边缘补0
                fc.InconvertibleEdgeHandling = InconvertibleEdgeHandling_Extend;  //推荐设置,否则右、下有黑边
                CPylonImage tempImg, copyImg;
                
                //方式一:
                //fc.Convert(tempImg, ptrGrabResult);            
                //uchar* buffer = (uchar*)tempImg.GetBuffer();

                //方式二:
                tempImg.AttachGrabResultBuffer(ptrGrabResult);
                fc.Convert(copyImg, tempImg);                //此函数可能失败,因此放到try中            
                uchar* buffer = (uchar*)copyImg.GetBuffer();
                
                OutImage = QImage(buffer, width, height, QImage::Format_RGB888).copy();
            }
            catch (const Pylon::GenericException& e)
            {
                qDebug() << "官方函数格式转换失败" + QString(e.GetDescription());
                return false;
            }
        }
    }
    catch (const Pylon::GenericException& e)
    {
        qDebug() << "失败" + QString(e.GetDescription());
        return false;
    }    

    return true;
}    

【注意】

ptrGrabResult的转换、获取(先清空再存数据)会有访问冲突,注意这两个位置要加锁。

【多余的话】

官方有下图函数,但是貌似没用。因此使用 CImageFormatConverter

 

posted @ 2022-09-02 18:25  夕西行  阅读(637)  评论(0编辑  收藏  举报