堡盟相机支持Mono8、Mono12、BGR8等多种像素格式(PixelFormat)——每种格式需对应相应的OpenCV格式。与堡盟相机像素格式对应的OpenCV矩阵类型如下表所示。
从如下示例可以看出,可直接处理像素格式的图像,无需转换,非常简单。
示例:Mono8
pDevice->GetRemoteNode("PixelFormat")->SetString("Mono8"); BGAPI2::Buffer * pBufferFilled = pDataStream->GetFilledBuffer(1000); if (pBufferFilled->GetPixelFormat() == "Mono8") { cv::Mat* imOriginal = new cv::Mat((int)pBufferFilled->GetHeight(), (int)pBufferFilled->GetWidth(), CV_8UC1, (char *)pBufferFilled->GetMemPtr(); cv::imwrite("cv_Mono8_image.png", *imOriginal); delete imOriginal; } pBufferFilled->QueueBuffer();
示例:BGR8
OpenCV中标准的颜色像素格式为BGR,每个颜色通道为8位(CV_8UC3)。相机中与之对应的像素格式设为BGR8(也可以设为BGR8Packed)。
pDevice->GetRemoteNode("PixelFormat")->SetString("BGR8"); BGAPI2::Buffer * pBufferFilled = pDataStream->GetFilledBuffer(1000); if ((pBufferFilled->GetPixelFormat() == "BGR8") || (pBufferFilled->GetPixelFormat() == "BGR8Packed")) { cv::Mat* imOriginal = new cv::Mat((int)pBufferFilled->GetHeight(), (int)pBufferFilled->GetWidth(), CV_8UC3, (char *)pBufferFilled->GetMemPtr(); cv::imwrite("cv_BGR8_image.png", *imOriginal); delete imOriginal; } pBufferFilled->QueueBuffer();
将像素格式转换为16位OpenCV矩阵
某些相机支持12位像素格式(Mono12、RGB12)。将数据储存在16位OpenCV矩阵类型中会导致输出图像比预期暗很多。为了将12位像素格式转换成16位OpenCV矩阵,堡盟GAPI缓冲区中的数据需要通过OpenCV ConvertTo()函数平移4位(或乘以16)。
同样地,Mono10等10位像素格式可以通过将数据平移2位(或乘以64)进行转换。
警告:由于一个指针刚被传输到堡盟GAPI缓冲区的数据中,初始数据已经被更改。
pDevice->GetRemoteNode("PixelFormat")->SetString("Mono12"); BGAPI2::Buffer * pBufferFilled = pDataStream->GetFilledBuffer(1000); if (pBufferFilled->GetPixelFormat() == "Mono12") { cv::Mat* imOriginal = new cv::Mat((int)pBufferFilled->GetHeight(), (int)pBufferFilled->GetWidth(), CV_16UC1, (char *)pBufferFilled->GetMemPtr(); imOriginal.ConvertTo(imOriginal, Emgu.CV.CvEnum.DepthType.Cv16U, 64.0); cv::imwrite("cv_Mono12_as_Mono16_image.png", *imOriginal); delete imOriginal; } pBufferFilled->QueueBuffer();