Ask Your Question

Revision history [back]

I supplied earlier in this topic a way to work with the old pvapi like we do in our research group.

Basically you would like to use this code snippet to connect to the camera and perform the correct openCV functionality in the provided part of the code. Have fun experimenting with it and feel free to contact me if it goes wrong.

Tough this snippet is for windows, I already adapted it on my own system to linux, which is fairly simple by removing the stdafx header and some windows specific commands if they are there with their linux counterparts.

Also I suggest everyone to replace the C-style API with the newer C++ API, I will see if I can dig up a clean C++ version of this snippet

SNIPPET WINDOWS C-CODE OPENCV

/**********************************************************************************
* Copyright (C) 2008 Metron Hong Kong Limited.  All Rights Reserved.
*
* Reproduction or disclosure of this file or its contents is granted without 
* prior written consent of Metron Hong Kong Limited.
***
* Code name: CaptureSaveMono.cpp
* Written by: Antonio Yu, Chief Consultant
* Date: 1 May, 2008
* Version: 1.0
* 
* Adapted by Stijn De Beugher on 2/04/2012
* Tested in combination with a AVT MANTA 201 MonoChrome camera
***
* Adapted by Steven Puttemans on 03/05/2013 
* Changed compatibility to windows environments
**********************************************************************************/

#include <PvApi.h>
#include <cxcore.h>
#include <cv.h>
#include <highgui.h>
#include <string.h>
#include <iostream>
#include <time.h>

// Added this library in order to be windows compatible
#include <io.h>

using namespace std;

// camera's data type definition
typedef struct 
{
    unsigned long   UID;
    tPvHandle       Handle;
    tPvFrame        Frame;

} tCamera;

#define CH_MONO 1   // Single channel for mono images

int main(int argc, char* argv[])
{
    string input = "";
    string output_folder = "";
    int maxframecounter  = 100;
    string extension = ".pgm";  
    tCamera myCamera;
    tPvCameraInfo   cameraInfo;
    unsigned long   frameSize;
    tPvErr  Errcode;

    cout << "Frame capturing configured, starting the actual capture." << endl;

    // Initialize the API
    if(!PvInitialize())
    { 
        // Wait for the response from a camera after the initialization of the driver
        ////////////////////////////////////////////////////////////        
        clock_t startT, endT;
        startT = clock();
        float start = float(startT/CLOCKS_PER_SEC); 
        while(PvCameraCount() == 0)
        {           
            endT = clock();
            float end = float(endT/CLOCKS_PER_SEC); 
            if(end>(start+5))
            {               
                break;
            }
        }

        /////////////////////////////////////////////////////////////
        unsigned long numCams = PvCameraList(&cameraInfo, 1, NULL);
        cout << "numcams = \t" << numCams << endl;      
        if (numCams == 1)
        {
            // Get the camera ID
            myCamera.UID = cameraInfo.UniqueId;
            cout << "Camera ID =  \t " << myCamera.UID << endl;     

            // Open the camera
            if(!PvCameraOpen(myCamera.UID, ePvAccessMaster, &(myCamera.Handle)))
            {
                // Get the image size of every capture
                Errcode = PvAttrUint32Get(myCamera.Handle, "TotalBytesPerFrame", &frameSize);
                if (Errcode != ePvErrSuccess)
                    throw Errcode;

                cout << "Frame size = \t" << frameSize << endl;

                // Allocate a buffer to store the image
                memset(&myCamera.Frame, 0, sizeof(tPvFrame));
                myCamera.Frame.ImageBufferSize = frameSize;
                myCamera.Frame.ImageBuffer = new char[frameSize];

                // Get the width & height of the image
                tPvUint32 width, height;
                PvAttrUint32Get(myCamera.Handle, "Width", &width);
                PvAttrUint32Get(myCamera.Handle, "Height", &height);

                cout << "Frame width = \t" << width << endl;
                cout << "Frame height = \t" << height << endl;

                // Start the camera
                PvCaptureStart(myCamera.Handle);

                // Set the camera to capture continuously
                Errcode = PvAttrEnumSet(myCamera.Handle, "AcquisitionMode", "Continuous");
                if (Errcode != ePvErrSuccess)
                    throw Errcode;

                cout <<"start the acquisition" << endl;
                Errcode = PvCommandRun(myCamera.Handle, "AcquisitionStart");
                if (Errcode != ePvErrSuccess)
                    throw Errcode;

                Errcode = PvAttrEnumSet(myCamera.Handle, "FrameStartTriggerMode", "Freerun");
                if (Errcode != ePvErrSuccess)
                    throw Errcode;

                int framecounter = 0;
                for(framecounter =0;framecounter<maxframecounter;framecounter++)
                {                   
                    cout << "\r"<< framecounter << flush;                               

                    if(!PvCaptureQueueFrame(myCamera.Handle, &(myCamera.Frame), NULL))
                    {   
                        while(PvCaptureWaitForFrameDone(myCamera.Handle, &(myCamera.Frame), 100) == ePvErrTimeout)
                        {
                        }

                        /////////////////////////////////////////
                        // Here comes the OpenCV part          //
                        // Trying to convert to C++ interface  //
                        /////////////////////////////////////////

                        // Create an image header (mono image)
                        IplImage *image = cvCreateImageHeader(cvSize((int)width, (int)height), IPL_DEPTH_8U, CH_MONO);

                        // Set the width for each image
                        image->widthStep = (int)width;
                        image->imageData = (char *)myCamera.Frame.ImageBuffer;  // Points the image to the buffer of the camera

                        // Create a unique blueprint for the name!
                        time_t t = time(0);   // get time now
                        struct tm * now = localtime( & t );
                        stringstream date;
                        date << (now->tm_year + 1900) << (now->tm_mon + 1) << now->tm_mday << now->tm_hour << now->tm_min << now->tm_sec;

                        stringstream filename;
                        filename << output_folder << "frame_" << date.str() << "_" << framecounter << extension;

                        // Show the image in a window
                        cvShowImage("View window", image); cvWaitKey(10);

                        // Save the image & release the image
                        cvSaveImage(filename.str().c_str(), image);
                        cvReleaseImageHeader(&image);   
                    }
                }

                // Stop the acquisition & free the camera
                Errcode = PvCommandRun(myCamera.Handle, "AcquisitionStop");
                if (Errcode != ePvErrSuccess)
                    throw Errcode;

                PvCaptureEnd(myCamera.Handle);
                PvCameraClose(myCamera.Handle);

                cout << endl << "finished" << endl;
            }
            else
                cout << "open camera error" << endl;
        }
        else
            cout << "camera not found" << endl;         
    }
    else
        cout << "failed to initialise the API" << endl;     

    return 0;
}

I supplied earlier in this topic a way to work with the old pvapi like we do in our research group.

Basically you would like to use this code snippet to connect to the camera and perform the correct openCV functionality in the provided part of the code. Have fun experimenting with it and feel free to contact me if it goes wrong.

Tough this snippet is for windows, I already adapted it on my own system to linux, which is fairly simple by removing the stdafx header and some windows specific commands if they are there with their linux counterparts.

Also I suggest everyone to replace the C-style API with the newer C++ API, I will see if I can dig up a clean C++ version of this snippet

SNIPPET WINDOWS C-CODE OPENCV

/**********************************************************************************
* Copyright (C) 2008 Metron Hong Kong Limited.  All Rights Reserved.
*
* Reproduction or disclosure of this file or its contents is granted without 
* prior written consent of Metron Hong Kong Limited.
***
* Code name: CaptureSaveMono.cpp
* Written by: Antonio Yu, Chief Consultant
* Date: 1 May, 2008
* Version: 1.0
* 
* Adapted by Stijn De Beugher on 2/04/2012
* Tested in combination with a AVT MANTA 201 MonoChrome camera
***
* Adapted by Steven Puttemans on 03/05/2013 
* Changed compatibility to windows environments
**********************************************************************************/

#include <PvApi.h>
#include <cxcore.h>
#include <cv.h>
#include <highgui.h>
#include <string.h>
#include <iostream>
#include <time.h>

// Added this library in order to be windows compatible
#include <io.h>

using namespace std;

// camera's data type definition
typedef struct 
{
    unsigned long   UID;
    tPvHandle       Handle;
    tPvFrame        Frame;

} tCamera;

#define CH_MONO 1   // Single channel for mono images

int main(int argc, char* argv[])
{
    string input = "";
    string output_folder = "";
    int maxframecounter  = 100;
    string extension = ".pgm";  
    tCamera myCamera;
    tPvCameraInfo   cameraInfo;
    unsigned long   frameSize;
    tPvErr  Errcode;

    cout << "Frame capturing configured, starting the actual capture." << endl;

    // Initialize the API
    if(!PvInitialize())
    { 
        // Wait for the response from a camera after the initialization of the driver
        ////////////////////////////////////////////////////////////        
        clock_t startT, endT;
        startT = clock();
        float start = float(startT/CLOCKS_PER_SEC); 
        while(PvCameraCount() == 0)
        {           
            endT = clock();
            float end = float(endT/CLOCKS_PER_SEC); 
            if(end>(start+5))
            {               
                break;
            }
        }

        /////////////////////////////////////////////////////////////
        unsigned long numCams = PvCameraList(&cameraInfo, 1, NULL);
        cout << "numcams = \t" << numCams << endl;      
        if (numCams == 1)
        {
            // Get the camera ID
            myCamera.UID = cameraInfo.UniqueId;
            cout << "Camera ID =  \t " << myCamera.UID << endl;     

            // Open the camera
            if(!PvCameraOpen(myCamera.UID, ePvAccessMaster, &(myCamera.Handle)))
            {
                // Get the image size of every capture
                Errcode = PvAttrUint32Get(myCamera.Handle, "TotalBytesPerFrame", &frameSize);
                if (Errcode != ePvErrSuccess)
                    throw Errcode;

                cout << "Frame size = \t" << frameSize << endl;

                // Allocate a buffer to store the image
                memset(&myCamera.Frame, 0, sizeof(tPvFrame));
                myCamera.Frame.ImageBufferSize = frameSize;
                myCamera.Frame.ImageBuffer = new char[frameSize];

                // Get the width & height of the image
                tPvUint32 width, height;
                PvAttrUint32Get(myCamera.Handle, "Width", &width);
                PvAttrUint32Get(myCamera.Handle, "Height", &height);

                cout << "Frame width = \t" << width << endl;
                cout << "Frame height = \t" << height << endl;

                // Start the camera
                PvCaptureStart(myCamera.Handle);

                // Set the camera to capture continuously
                Errcode = PvAttrEnumSet(myCamera.Handle, "AcquisitionMode", "Continuous");
                if (Errcode != ePvErrSuccess)
                    throw Errcode;

                cout <<"start the acquisition" << endl;
                Errcode = PvCommandRun(myCamera.Handle, "AcquisitionStart");
                if (Errcode != ePvErrSuccess)
                    throw Errcode;

                Errcode = PvAttrEnumSet(myCamera.Handle, "FrameStartTriggerMode", "Freerun");
                if (Errcode != ePvErrSuccess)
                    throw Errcode;

                int framecounter = 0;
                for(framecounter =0;framecounter<maxframecounter;framecounter++)
                {                   
                    cout << "\r"<< framecounter << flush;                               

                    if(!PvCaptureQueueFrame(myCamera.Handle, &(myCamera.Frame), NULL))
                    {   
                        while(PvCaptureWaitForFrameDone(myCamera.Handle, &(myCamera.Frame), 100) == ePvErrTimeout)
                        {
                        }

                        /////////////////////////////////////////
                        // Here comes the OpenCV part          //
                        // Trying to convert to C++ interface  //
                        /////////////////////////////////////////

                        // Create an image header (mono image)
                        IplImage *image = cvCreateImageHeader(cvSize((int)width, (int)height), IPL_DEPTH_8U, CH_MONO);

                        // Set the width for each image
                        image->widthStep = (int)width;
                        image->imageData = (char *)myCamera.Frame.ImageBuffer;  // Points the image to the buffer of the camera

                        // Create a unique blueprint for the name!
                        time_t t = time(0);   // get time now
                        struct tm * now = localtime( & t );
                        stringstream date;
                        date << (now->tm_year + 1900) << (now->tm_mon + 1) << now->tm_mday << now->tm_hour << now->tm_min << now->tm_sec;

                        stringstream filename;
                        filename << output_folder << "frame_" << date.str() << "_" << framecounter << extension;

                        // Show the image in a window
                        cvShowImage("View window", image); cvWaitKey(10);

                        // Save the image & release the image
                        cvSaveImage(filename.str().c_str(), image);
                        cvReleaseImageHeader(&image);   
                    }
                }

                // Stop the acquisition & free the camera
                Errcode = PvCommandRun(myCamera.Handle, "AcquisitionStop");
                if (Errcode != ePvErrSuccess)
                    throw Errcode;

                PvCaptureEnd(myCamera.Handle);
                PvCameraClose(myCamera.Handle);

                cout << endl << "finished" << endl;
            }
            else
                cout << "open camera error" << endl;
        }
        else
            cout << "camera not found" << endl;         
    }
    else
        cout << "failed to initialise the API" << endl;     

    return 0;
}

SNIPPET LINUX C++-CODE OPENCV

/**********************************************************************************
* Copyright (C) 2008 Metron Hong Kong Limited.  All Rights Reserved.
*
* Reproduction or disclosure of this file or its contents is granted without
* prior written consent of Metron Hong Kong Limited.
***
* Code name: CaptureSaveMono.cpp
* Written by: Antonio Yu, Chief Consultant
* Date: 1 May, 2008
* Version: 1.0
*
* Adapted by Steven Puttemans on 25/01/2014
* Made working with Linux and C++ environment
**********************************************************************************/
// Link to the AVT technologies camera library for AVT Manta
#include "PvApi.h"

// Link to the necessary OpenCV libraries
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

// Functionality to provide extra output
#include <string.h>
#include <iostream>
#include <time.h>

using namespace std;
using namespace cv;

// camera's data type definition
typedef struct
{
    unsigned long   UID;
    tPvHandle       Handle;
    tPvFrame        Frame;

} tCamera;

#define CH_MONO 1   // Single channel for mono images

int main(int argc, char* argv[])
{
    tCamera         myCamera;
    tPvCameraInfo   cameraInfo;
    unsigned long   frameSize;
    tPvErr          Errcode;

    int counter = 0;

    if( argc == 1 ){
        cout << "This script will stream data from an AVT MANTA GigE camera using OpenCV C++ style interface." << endl;
            cout << "capture_manta.exe <resolution width> <resolution heigth>" << endl;
        return 0;
    }

    // Initialize the API
    if(!PvInitialize())
    {
        // Wait for the response from a camera after the initialization of the driver
        // This is done by checking if camera's are found yet
        ////////////////////////////////////////////////////////////
        while(PvCameraCount() == 0)
        {
            waitKey(15);
        }

        //debug
        cout << "Camera count successfully finished." << endl;

        /////////////////////////////////////////////////////////////
        if ( PvCameraList(&cameraInfo, 1, NULL) == 1)
        {
            // Get the camera ID
            myCamera.UID = cameraInfo.UniqueId;

            // Open the camera
            if( !PvCameraOpen(myCamera.UID, ePvAccessMaster, &(myCamera.Handle)) )
            {
                //debug
                cout << "Camera opened succesfully." << endl;

                // Get the image size of every capture
                PvAttrUint32Get(myCamera.Handle, "TotalBytesPerFrame", &frameSize);

                // Allocate a buffer to store the image
                memset(&myCamera.Frame, 0, sizeof(tPvFrame));
                myCamera.Frame.ImageBufferSize = frameSize;
                myCamera.Frame.ImageBuffer = new char[frameSize];

                // Set maximum camera parameters - camera specific
                int max_width = 1624;
                int max_heigth = 1234;

                int center_x = max_width / 2;
                int center_y = max_heigth / 2;

                int frame_width = atoi(argv[1]);
                int frame_heigth = atoi(argv[2]);

                // Set the manta camera parameters to get wanted frame size retrieved
                PvAttrUint32Set(myCamera.Handle, "RegionX", center_x - (frame_width / 2) );
                PvAttrUint32Set(myCamera.Handle, "RegionY", center_y - (frame_heigth / 2));
                PvAttrUint32Set(myCamera.Handle, "Width", frame_width);
                PvAttrUint32Set(myCamera.Handle, "Height", frame_heigth);

                // Start the camera
                PvCaptureStart(myCamera.Handle);

                // Set the camera to capture continuously
                PvAttrEnumSet(myCamera.Handle, "AcquisitionMode", "Continuous");
                PvCommandRun(myCamera.Handle, "AcquisitionStart");
                PvAttrEnumSet(myCamera.Handle, "FrameStartTriggerMode", "Freerun");

                // Create infinite loop - break out when condition is met
                for(;;)
                {
                    if(!PvCaptureQueueFrame(myCamera.Handle, &(myCamera.Frame), NULL))
                    {
                        double time = (double)getTickCount();

                        while(PvCaptureWaitForFrameDone(myCamera.Handle, &(myCamera.Frame), 100) == ePvErrTimeout)
                        {
                        }

                        ////////////////////////////////////////////////////////
                        // Here comes the OpenCV functionality for each frame //
                        ////////////////////////////////////////////////////////

                        // Create an image header (mono image)
                        // Push ImageBuffer data into the image matrix
                        Mat image = Mat(frame_heigth, frame_width, CV_8UC1);
                        image.data = (uchar *)myCamera.Frame.ImageBuffer;

                        // Show the actual frame
                        imshow("View window", image);

                        // Now wait for a keystroke and respond to it
                        int key = waitKey(5);
                        if (key == 27){
                            cout << "Closed down the application by pressing ESC." << endl;
                            break;
                        }
                        if (key == 115){
                            cout << "Save key pressed, storing current frame." << endl;
                            stringstream location;
                            location << "FILL_IN_A_LOCATION_HERE" << counter << ".png";

                            imwrite(location.str(), image);

                            counter++;
                        }

                        // Release the image data
                        image.release();
                    }
                }

                // Stop the acquisition & free the camera
                Errcode = PvCommandRun(myCamera.Handle, "AcquisitionStop");
                if (Errcode != ePvErrSuccess)
                    throw Errcode;

                PvCaptureEnd(myCamera.Handle);
                PvCameraClose(myCamera.Handle);

                cout << endl << "finished" << endl;
            }
            else
                cout << "open camera error" << endl;
        }
        else
            cout << "camera not found" << endl;
    }
    else
        cout << "failed to initialise the API" << endl;

    return 0;
}