Pylon5 SDK搭配OpenCV使用入門


本文假設已經安裝了Basler官網提供的Pylon

目前最新的版本是5.0.5,如果上述鏈接打不開,請直接所有Basler官網下載,需要注意的是在安裝Pylon5時要選擇Developer模式,這樣才會安裝關於pylon5 SDK開發包,安裝完可以到安裝路徑下找到,軟件也會自動將一些路徑自動添加到系統環境變量。

使用Pylon5 SDK開發與使用OpenCV開發一些功能流程一樣,無非是引入包目錄(include)和庫包含目錄(lib),本文使用的OpenCV版本為2.4.9.。。關於工程如何配置,我不想說話,只扔出兩張屬性表。
Pylon.props

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ImportGroup Label="PropertySheets" />
  <PropertyGroup Label="UserMacros" />
  <PropertyGroup />
  <ItemDefinitionGroup>
    <ClCompile>
      <AdditionalIncludeDirectories>$(PYLON_DEV_DIR)\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
    </ClCompile>
    <Link>
      <AdditionalLibraryDirectories>$(PYLON_DEV_DIR)\lib\win32;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
    </Link>
  </ItemDefinitionGroup>
  <ItemGroup />
</Project>

OpenCVConsole.props

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ImportGroup Label="PropertySheets" />
  <PropertyGroup Label="UserMacros" />
  <PropertyGroup>
    <IncludePath>$(OPENCV_ROOT)\include;$(IncludePath)</IncludePath>
    <LibraryPath Condition="'$(Platform)'=='Win32'">$(OPENCV_ROOT)\x86\vc12\lib;$(LibraryPath)</LibraryPath>
    <LibraryPath Condition="'$(Platform)'=='X64'">$(OPENCV_ROOT)\x64\vc12\lib;$(LibraryPath)</LibraryPath>
  </PropertyGroup>
  <ItemDefinitionGroup>
    <Link Condition="'$(Configuration)'=='Debug'">
      <AdditionalDependencies>opencv_calib3d249d.lib;opencv_contrib249d.lib;opencv_core249d.lib;opencv_features2d249d.lib;opencv_flann249d.lib;opencv_gpu249d.lib;opencv_highgui249d.lib;opencv_imgproc249d.lib;opencv_legacy249d.lib;opencv_ml249d.lib;opencv_nonfree249d.lib;opencv_objdetect249d.lib;opencv_ocl249d.lib;opencv_photo249d.lib;opencv_stitching249d.lib;opencv_superres249d.lib;opencv_ts249d.lib;opencv_video249d.lib;opencv_videostab249d.lib;%(AdditionalDependencies)</AdditionalDependencies>
    </Link>
    <Link Condition="'$(Configuration)'=='Release'">
      <AdditionalDependencies>opencv_calib3d249.lib;opencv_contrib249.lib;opencv_core249.lib;opencv_features2d249.lib;opencv_flann249.lib;opencv_gpu249.lib;opencv_highgui249.lib;opencv_imgproc249.lib;opencv_legacy249.lib;opencv_ml249.lib;opencv_nonfree249.lib;opencv_objdetect249.lib;opencv_ocl249.lib;opencv_photo249.lib;opencv_stitching249.lib;opencv_superres249.lib;opencv_ts249.lib;opencv_video249.lib;opencv_videostab249.lib;%(AdditionalDependencies)</AdditionalDependencies>
    </Link>
    <ClCompile>
      <PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
    </ClCompile>
  </ItemDefinitionGroup>
  <ItemGroup />
</Project>

注意根據本機的庫安裝地址可能要修改上面的屬性表文件,只需要到屬性管理器窗口添加現有屬性表就好了。如果沒有屬性窗口,請到VS視圖菜單中打開。

使用Pylon5 SDK搭配OpenCV采集圖像程序流程如下:

下面是完整的源代碼,該工程使用Basler piA2400-17gc GigE 相機測試成功。

//定義是否保存圖片
#define saveImages 1
//定義是否記錄視頻
#define recordVideo 1

// 加載OpenCV API
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/video/video.hpp>

//加載PYLON API.
#include <pylon/PylonIncludes.h>

#include<iostream>

#ifdef PYLON_WIN_BUILD
#include <pylon/PylonGUI.h>    
#endif

//命名空間.
using namespace Pylon;
using namespace cv;
using namespace std;
//定義抓取的圖像數
static const uint32_t c_countOfImagesToGrab = 10;

void main()
{

    //Pylon自動初始化和終止
    Pylon::PylonAutoInitTerm autoInitTerm;
    try
    {
        //創建相機對象(以最先識別的相機)
        CInstantCamera camera(CTlFactory::GetInstance().CreateFirstDevice());
        // 打印相機的名稱
        std::cout << "Using device " << camera.GetDeviceInfo().GetModelName() << endl;
        //獲取相機節點映射以獲得相機參數
        GenApi::INodeMap& nodemap = camera.GetNodeMap();
        //打開相機
        camera.Open();
        //獲取相機成像寬度和高度
        GenApi::CIntegerPtr width = nodemap.GetNode("Width");
        GenApi::CIntegerPtr height = nodemap.GetNode("Height");

        //設置相機最大緩沖區,默認為10
        camera.MaxNumBuffer = 5;
        // 新建pylon ImageFormatConverter對象.
        CImageFormatConverter formatConverter;
        //確定輸出像素格式
        formatConverter.OutputPixelFormat = PixelType_BGR8packed;
        // 創建一個Pylonlmage后續將用來創建OpenCV images
        CPylonImage pylonImage;

        //聲明一個整形變量用來計數抓取的圖像,以及創建文件名索引
        int grabbedlmages = 0;

        // 新建一個OpenCV video creator對象.
        VideoWriter cvVideoCreator;
        //新建一個OpenCV image對象.

        Mat openCvImage;
        // 視頻文件名

        std::string videoFileName = "openCvVideo.avi";
        // 定義視頻幀大小
        cv::Size frameSize = Size((int)width->GetValue(), (int)height->GetValue());

        //設置視頻編碼類型和幀率,有三種選擇
        // 幀率必須小於等於相機成像幀率
        cvVideoCreator.open(videoFileName, CV_FOURCC('D', 'I', 'V','X'), 10, frameSize, true);
        //cvVideoCreator.open(videoFileName, CV_F0URCC('M','P',,4','2’), 20, frameSize, true);
        //cvVideoCreator.open(videoFileName, CV_FOURCC('M', '3', 'P', 'G'), 20, frameSize, true);


        // 開始抓取c_countOfImagesToGrab images.
        //相機默認設置連續抓取模式
        camera.StartGrabbing(c_countOfImagesToGrab, GrabStrategy_LatestImageOnly);

        //抓取結果數據指針
        CGrabResultPtr ptrGrabResult;

        // 當c_countOfImagesToGrab images獲取恢復成功時,Camera.StopGrabbing() 
        //被RetrieveResult()方法自動調用停止抓取
    
        while (camera.IsGrabbing())

        {
            // 等待接收和恢復圖像,超時時間設置為5000 ms.
            camera.RetrieveResult(5000, ptrGrabResult, TimeoutHandling_ThrowException);

            //如果圖像抓取成功
            if (ptrGrabResult->GrabSucceeded())
            {
                // 獲取圖像數據
                cout <<"SizeX: "<<ptrGrabResult->GetWidth()<<endl;
                cout <<"SizeY: "<<ptrGrabResult->GetHeight()<<endl;

                //將抓取的緩沖數據轉化成pylon image.
                formatConverter.Convert(pylonImage, ptrGrabResult);

                // 將 pylon image轉成OpenCV image.
                openCvImage = cv::Mat(ptrGrabResult->GetHeight(), ptrGrabResult->GetWidth(), CV_8UC3, (uint8_t *) pylonImage.GetBuffer());

                //如果需要保存圖片
                if (saveImages)
                {
                   std::ostringstream s;
                    // 按索引定義文件名存儲圖片
                   s << "image_" << grabbedlmages << ".jpg";
                   std::string imageName(s.str());
                    //保存OpenCV image.
                   imwrite(imageName, openCvImage);
                   grabbedlmages++;
                }

                //如果需要記錄視頻
                if (recordVideo)
                {
            
                    cvVideoCreator.write(openCvImage);
                }

                //新建OpenCV display window.
                namedWindow("OpenCV Display Window", CV_WINDOW_NORMAL); // other options: CV_AUTOSIZE, CV_FREERATIO
                //顯示及時影像.
                imshow("OpenCV Display Window", openCvImage);

                // Define a timeout for customer's input in
                // '0' means indefinite, i.e. the next image will be displayed after closing the window.
                // '1' means live stream
                waitKey(0);

            }

        }            

    }
    catch (GenICam::GenericException &e)
    {
        // Error handling.
        cerr << "An exception occurred." << endl
            << e.GetDescription() << endl;
    }
    return;
}

參考文檔:
Application_Note_Build_pylon_C++_Apps_with_Free_Visual_Studio_IDE
Getting_Started_with_pylon5_and_OpenCV


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM