注:此博客原本由本人于2013-7-10发表于http://blog.sina.com.cn/s/blog_87ce045d0101f61r.html,现在新浪博客不再使用。此博客为第二版,附上了主函数的源码。
最近在做一个字符识别项目,用的是德国产Basler工业摄像头。它的显示采集图像的例程中,定义了一个指针,指向图像的某像素,通过对指针的操作来显示图像。我需要对采集的图像进行基于opencv的处理,而opencv函数能处理的数据类型却是Mat型。怎么转换呢?
首先是第一种方法,定义一个指针变量din,将原指针赋给din,然后操作din,构建出一个完整的Mat。代码如下:for(int j=0; j<FrameHeight; j++){
uchar* out= Image.ptr<uchar>(j);
for(int i=0; i<FrameWidth; i++){
out[i]= din[j*FrameWidth+i];
}
}
主函数完整代码如下,加上了Basler摄像头的初始化相关函数:
int main(int argc, char* argv[]) // 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; // The parameter MaxNumBuffer can be used to control the count of buffers // allocated for grabbing. The default value of this parameter is 10. camera.MaxNumBuffer = 5; <span style="white-space:pre"> </span>Mat Image(cv::Size(FrameWidth,FrameHeight),CV_8UC1);<span style="white-space:pre"> </span> // 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. CPylonImage Img; while(1) { camera.StartGrabbing( 1); // 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. Img.AttachGrabResultBuffer(ptrGrabResult); //将摄像头采集的图像转换为Mat数据格式 uchar* din = (uchar *)(Img.GetBuffer()); for(int j=0; j<FrameHeight; j++){ uchar* out= Image.ptr<uchar>(j); for(int i=0; i<FrameWidth; i++){ out[i]= din[j*FrameWidth+i]; } } } else { cout << "Error: " << ptrGrabResult->GetErrorCode() << " " << ptrGrabResult->GetErrorDescription(); } } }