Basler相机采集的彩色图像转换到opencv中Mat的问题

之前使用的都是黑白相机,采集的也是灰度图像,直接用pylon中的示例代码就可以完成图像的转换。

// Create an instant camera object with the camera device found first.
CInstantCamera camera( CTlFactory::GetInstance().CreateFirstDevice());

// Print the model name of the camera.
cout << "Using device " << camera.GetDeviceInfo().GetModelName() << endl;

// Start the grabbing of c_countOfImagesToGrab images.
// The camera device is parameterized with a default configuration which
// sets up free-running continuous acquisition.
camera.StartGrabbing( c_countOfImagesToGrab);

// This smart pointer will receive the grab result data.
CGrabResultPtr ptrGrabResult;

// Camera.StopGrabbing() is called automatically by the RetrieveResult() method
// when c_countOfImagesToGrab images have been retrieved.
while ( camera.IsGrabbing())
{
    // Wait for an image and then retrieve it. A timeout of 5000 ms is used.
    camera.RetrieveResult( 5000, ptrGrabResult, TimeoutHandling_ThrowException);

    // Image grabbed successfully?
    if (ptrGrabResult->GrabSucceeded())
    {
        // Access the image data.
	int w=ptrGrabResult->GetWidth();
	int h=ptrGrabResult->GetHeight();
        const uint8_t *pImageBuffer = (uint8_t *) ptrGrabResult->GetBuffer();
        Mat img =Mat(cv::Size(w, h), CV_8U, (void*)pImageBuffer, cv::Mat::AUTO_STEP);

    }
}

因为是灰度图像,所以使用CV_8U单通道即可。若相机为彩色相机时,将程序中代码改成CV_8UC3则会出现如下图像

Basler相机采集的彩色图像转换到opencv中Mat的问题_第1张图片


但其实这图片应该是这样的(彩色的删掉了,就那灰度图代替一下吧)

Basler相机采集的彩色图像转换到opencv中Mat的问题_第2张图片


最后查到解决方法,使用转换:

CImageFormatConverter fc;

fc.OutputPixelFormat = PixelType_BGR8packed;

CPylonImage image;

if (ptrGrabResult->GrabSucceeded())
{
fc.Convert(image, ptrGrabResult);
Mat cv_img = cv::Mat(ptrGrabResult->GetHeight(), ptrGrabResult->GetWidth(), CV_8UC3,(uint8_t*)image.GetBuffer());
imshow(src_window,cv_img);  // display the image in OpenCV image window
waitKey(1);
}


你可能感兴趣的:(1,-,相机连接)