Integrating the FlyCapture SDK for use with OpenCV

Introduction

A recent stab at grabbing images from the Flea2 camera using APIs from the FlyCapture2 SDK by Point Gray Research (PGR).  Additionally, the camera was to be used in  “Format 7 mode”, so that we may grab partial regions of the complete image.

This application builds on the AsynchTriggerEx C++ example provided by PGR, so that the user can grab images from the camera either by way of software triggers, or from an external hardware triggers.

Using Format7 mode to grab partial images

The Format7ImageSettings data structure is modified in order to set the desired output image size, pixel formats etc.  Standard FlyCapture API calls are used to perform all necessary camera actions: connect to camera, disconnect from camera, start image capturing, retrieve image buffers etc. When the using the default equipment setup, the input images obtained are grayscales of 24 x 480 pixels consisting of an array of dark gray spots against a lighter shade of gray background. 

Converting FlyCapture images into OpenCV images

In the image grabbing loop, FlyCapture2-obtained images are converted into OpenCV-compatible images by copying the pixel data from one to the other:

1
2
3
memcpy( img->imageData,
        image.GetData(),
        data_size );

Thresholding the grayscale image into binary (black & white)

The OpenCV grayscale image is then thresholded to produce a black and white (binary) image, from which we can use for things like detecting the number and location of the spots.  Depending on the equipment used and lighting arrangement, some experimentation is probably needed to come up with an optimal threshold value.

1
2
3
4
5
cvThreshold( img,         // source_img,
             img_bw,      // destination image
             140,         // threhold val.
             255,         // max. val
             CV_THRESH_BINARY );   // binary type );

Original FlyCapture grayscale image, set to a Format 7 partial image (24 x 480 pixels) and converted to OpenCV format:


Thresholded to a black and white (binary) image:


Full code listing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
// CameraTest.cpp : Defines entry point for console application.
 
#include "stdafx.h"
#include "FlyCapture2.h"
#include <cv.h>
#include <highgui.h> 
 
// Disable  C4996 warnings
#pragma warning(disable: 4996)
#define SOFTWARE_TRIGGER_CAMERA
 
using namespace FlyCapture2;
 
const int col_size   = 24;
const int row_size   = 480;
const int data_size  = row_size * col_size;
 
// Forward declarations
bool CheckSoftwareTriggerPresence( Camera* pCam );
bool PollForTriggerReady( Camera* pCam );
bool FireSoftwareTrigger( Camera* pCam );
void PrintError( Error error );
void ReleaseImage( IplImage* pimg,
               IplImage* pimg_bw,
               CvMemStorage* pstorage );
 
void GrabImages( Camera* pcam,
                 IplImage* pimg,
                 IplImage* pimg_bw,
                 CvMemStorage* pstorage,
                 int cnt );
 
// Main Control Loop
int _tmain(int argc, _TCHAR* argv[])
{
    Camera cam;
    CameraInfo camInfo;
    Error error;
    BusManager busMgr;
    PGRGuid guid;
    Format7PacketInfo fmt7PacketInfo;
    Format7ImageSettings fmt7ImageSettings;
    CvMemStorage* storage = NULL;
    IplImage* img    = NULL;
    IplImage* img_bw = NULL;
    TriggerMode triggerMode;
 
    // Create OpenCV structs for grayscale image
    img = cvCreateImage( cvSize( col_size, row_size ),
             IPL_DEPTH_8U,
             1 );
    img_bw = cvCloneImage( img );  
 
    storage = cvCreateMemStorage( 0 );
 
    // Get Flea2 camera
    error = busMgr.GetCameraFromIndex( 0, &guid ); 
 
    if ( error != PGRERROR_OK )
    {
    PrintError( error );
        return -1;
    }  
 
    // Connect to the camera
    error = cam.Connect( &guid );
    if ( error != PGRERROR_OK )
    {
        PrintError( error );
        return -1;
    }  
 
    // Get camera information
    error = cam.GetCameraInfo(&camInfo);
    if ( error != PGRERROR_OK )
    {
        PrintError( error );
        return -1;
    }
 
#ifndef SOFTWARE_TRIGGER_CAMERA
    // Check for external trigger support
    TriggerModeInfo triggerModeInfo;
    error = cam.GetTriggerModeInfo( &triggerModeInfo ;
 
    if ( error != PGRERROR_OK )
    {
        PrintError( error );
    return -1;
    }
 
    if ( triggerModeInfo.present != true )
    {
        printf( "Camera doesn't support external trigger!\n" );
    return -1;
    }
 
#endif
    // Get current trigger settings
    error = cam.GetTriggerMode( &triggerMode );
    if ( error != PGRERROR_OK )
    {
        PrintError( error );
        return -1;
    }
 
    // Set camera to trigger mode 0
    triggerMode.onOff = true;
    triggerMode.mode = 0;
    triggerMode.parameter = 0;
#ifdef SOFTWARE_TRIGGER_CAMERA
 
    // A source of 7 means software trigger
    triggerMode.source = 7;
#else
 
    // Triggering the camera externally using source 0.
    triggerMode.source = 0;
#endif
 
    // Set camera triggering mode
    error = cam.SetTriggerMode( &triggerMode );
    if ( error != PGRERROR_OK )
    {
        PrintError( error );
        return -1;
    }
 
    // Power on the camera
    const unsigned int k_cameraPower = 0x610;
    const unsigned int k_powerVal = 0x80000000;
    error  = cam.WriteRegister( k_cameraPower, k_powerVal );
 
    if ( error != PGRERROR_OK )
    {
        PrintError( error );
        return -1;
    }
 
    // Poll to ensure camera is ready
    bool retVal = PollForTriggerReady( &cam );
    if( !retVal )
    {
        PrintError( error );
        return -1;
    }  
 
    // Set camera configuration: region of 24 x 480 pixels
    // greyscale image mode
    fmt7ImageSettings.width   = col_size;
    fmt7ImageSettings.height  = row_size;
    fmt7ImageSettings.mode    = MODE_0;
    fmt7ImageSettings.offsetX = 312;
    fmt7ImageSettings.offsetY = 0;
    fmt7ImageSettings.pixelFormat = PIXEL_FORMAT_MONO8;
 
    // Validate Format 7 settings
    bool valid;
    error = cam.ValidateFormat7Settings( &fmt7ImageSettings,
                                 &valid,
                     &fmt7PacketInfo );
    unsigned int num_bytes =
        fmt7PacketInfo.recommendedBytesPerPacket;  
 
    // Set Format 7 (partial image mode) settings
    error = cam.SetFormat7Configuration( &fmt7ImageSettings,
                                         num_bytes );
    if ( error != PGRERROR_OK)
    {
        PrintError( error );
        return -1;
    }
 
    // Start capturing images
    error = cam.StartCapture();
    if ( error != PGRERROR_OK )
    {
        PrintError( error );
        return -1;
    }
 
    #ifdef SOFTWARE_TRIGGER_CAMERA
 
    if ( !CheckSoftwareTriggerPresence( &cam ) )
    {
        printf( "SOFT_ASYNC_TRIGGER not implemented on "
                "this camera! Stopping application\n" );
        return -1;
    }
 
    #else
    printf( "Trigger the camera by sending a trigger pulse"
            " to GPIO%d.\n",
            triggerMode.source );
    #endif
 
    error = cam.StartCapture();
 
    // Warm up - necessary to get decent images.
    // See Flea2 Technical Ref.: camera will typically not
    // send first 2 images acquired after power-up
    // It may therefore take several (n) images to get
    // satisfactory image, where n is undefined
    for ( int i = 0; i < 30; i++ )
    {
        // Check that the trigger is ready
        PollForTriggerReady( &cam );
 
        // Fire software trigger
        FireSoftwareTrigger( &cam );
 
        Image im;
 
        // Retrieve image before starting main loop
        Error error = cam.RetrieveBuffer( &im );
        if ( error != PGRERROR_OK )
        {
            PrintError( error );
            return -1;
        }
    }
 
    #ifdef SOFTWARE_TRIGGER_CAMERA
 
    if ( !CheckSoftwareTriggerPresence( &cam ) )
    {
        printf( "SOFT_ASYNC_TRIGGER not implemented on this"
                " camera! Stopping application\n");
        return -1;
    }
    #else
 
    printf( "Trigger camera by sending trigger pulse to"
            " GPIO%d.\n",
            triggerMode.source );
    #endif
 
    // Grab images acc. to number of hw/sw trigger events
    for ( int i = 0; i < 25; i++ )
    {
        GrabImages( &cam, img, img_bw, storage, i );
    }
 
    // Turn trigger mode off.
    triggerMode.onOff = false;
    error = cam.SetTriggerMode( &triggerMode );
    if ( error != PGRERROR_OK )
    {
        PrintError( error );
        return -1;
    }
 
    printf( "\nFinished grabbing images\n" );
 
    // Stop capturing images error = cam.StopCapture();
    if ( error != PGRERROR_OK )
    {
        PrintError( error );
        return -1;
    }
 
    // Disconnect the camera
    error = cam.Disconnect();
    if ( error != PGRERROR_OK )
    {
        PrintError( error );
        return -1;
    }
 
    ReleaseImage( img, img_bw, storage);
    return 0;
}
 
// Print error trace
void PrintError( Error error )
{
    error.PrintErrorTrace();
}
 
// Check for the presence of software trigger
bool CheckSoftwareTriggerPresence( Camera* pCam )
{
    const unsigned int k_triggerInq = 0x530;
    Error error;
    unsigned int regVal = 0;
    error = pCam->ReadRegister( k_triggerInq, &regVal );
    if ( error != PGRERROR_OK )
    {
        // TODO
    }
 
    if( ( regVal & 0x10000 ) != 0x10000 )
    {
        return false;
    }
 
    return true;
}
 
// Start polling for trigger ready
bool PollForTriggerReady( Camera* pCam )
{
    const unsigned int k_softwareTrigger = 0x62C;
    Error error;
    unsigned int regVal = 0;
 
    do
    {
        error = pCam->ReadRegister( k_softwareTrigger,
                                       regVal );
 
        if ( error != PGRERROR_OK )
        {
            // TODO
        }
    } while ( (regVal >> 31) != 0 );
 
    return true;
}
 
// Launch the software trigger event
bool FireSoftwareTrigger( Camera* pCam )
{
    const unsigned int k_softwareTrigger = 0x62C;
    const unsigned int k_fireVal = 0x80000000;
    Error error;
 
    error = pCam->WriteRegister( k_softwareTrigger,
                                    k_fireVal );
 
    if ( error != PGRERROR_OK )
    {
        // TODO
    }
 
    return true;
}
 
// Tidy up memory allocated for images etc
void ReleaseImage( IplImage* pimg,
                   IplImage* pimg_bw,
                   CvMemStorage* pstorage )
{
    cvReleaseImage( &pimg );
    cvReleaseImage( &pimg_bw );
    cvClearMemStorage( pstorage );
}
 
// Grab camera grayscale image and convert into
// an OpenCV image
void GrabImages( Camera* pcam,
                 IplImage* pimg,
                 IplImage* pimg_bw,
                 CvMemStorage* pstorage,
                 int cnt )
{
    Image image;
 
    #ifdef SOFTWARE_TRIGGER_CAMERA
 
    // Check that the trigger is ready
    PollForTriggerReady( pcam );
 
    printf( "Press Enter to initiate software trigger.\n" );
 
    getchar();
 
    // Fire software trigger
    bool retVal = FireSoftwareTrigger( pcam );
 
    if ( !retVal )
    {
        // TODO.
    }
 
    #endif
 
    // Retrieve image before starting main loop
    Error error = pcam->RetrieveBuffer( &image );
 
    if ( error != PGRERROR_OK )
    {
        // TODO.
    }
 
    // Copy FlyCapture2 image into OpenCV struct
    memcpy( pimg->imageData,
    image.GetData(),
    data_size );
 
    // Save the bitmap to file
    cvSaveImage( "orig.bmp", pimg );
 
    // Threshold to convert image into binary (B&W)
    cvThreshold( pimg,    // source image
                 pimg_bw, // destination image
                 145,     // threhold val.
                 255,     // max. val
                 CV_THRESH_BINARY ); // binary type );
 
    // Save the bitmap to file
    char buffer[ 20 ];
    sprintf( buffer, "%d", cnt );
    std::string mess = "B_W.bmp_";
    mess.append( buffer );
    mess.append( ".bmp" );
    cvSaveImage( mess.c_str(), pimg_bw );
 
    // Find connected components using OpenCV
    // for black spots against a white background
    CvSeq* seq;
    int num_blobs = cvFindContours( pimg_bw,
                                    pstorage,
                                    &seq,
                                    sizeof( CvContour ),
                                    CV_RETR_LIST,
                                    CV_CHAIN_APPROX_NONE,
                                    cvPoint( 0, 0 ) ) - 1;
}


Other posts related to image detection

Tracking Coloured Objects in Video using OpenCV
Displaying AVI Video using OpenCV
Analyzing FlyCapture2 Images obtained from Flea2 Cameras
OpenCV Detection of Dark Objects Against Light Backgrounds
Getting Started with OpenCV in Visual Studio
Object Detection Using the OpenCV / cvBlobsLib Libraries