2012年8月6日 星期一

OpenCV 2.4.2 V4L2 Camera resolution bug fix

When using camera with opencv api, the default camera resolution is ALWAYS 160x120
From source code modules/highgui/src/cap_libv4l.cpp the default resolution should be 640x480

/* Defaults - If your board can do better, set it here.  Set for the most common type inputs. */
#define DEFAULT_V4L_WIDTH  640
#define DEFAULT_V4L_HEIGHT 480

I have study a little bit of modules/highgui/src/cap_libv4l.cpp then I found the problem.

   CvCaptureCAM_V4L * capture = (CvCaptureCAM_V4L*)cvAlloc(sizeof(CvCaptureCAM_V4L));
   if (!capture) {
      fprintf( stderr, "HIGHGUI ERROR: V4L: Could not allocate memory for capture process.\n");
      return NULL;
   }

   /* set the default size */
   capture->width  = DEFAULT_V4L_WIDTH;
   capture->height = DEFAULT_V4L_HEIGHT;

...
...

   /* w/o memset some parts  arent initialized - AKA: Fill it with zeros so it is clean */
   memset(capture,0,sizeof(CvCaptureCAM_V4L));

   /* Present the routines needed for V4L funtionality.  They are inserted as part of
      the standard set of cv calls promoting transparency.  "Vector Table" insertion. */
   capture->FirstCapture = 1;

   if (_capture_V4L2 (capture, deviceName) == -1) {

The memset instruction is called after setting width & height. @@

So, just move up memset behind alloc memory.

--- modules/highgui/src/cap_libv4l.cpp.org    2012-08-06 19:28:58.746347834 +0800
+++ modules/highgui/src/cap_libv4l.cpp    2012-08-06 19:29:42.510348966 +0800
@@ -1007,6 +1007,9 @@
       return NULL;
    }
 
+   /* w/o memset some parts  arent initialized - AKA: Fill it with zeros so it is clean */
+   memset(capture,0,sizeof(CvCaptureCAM_V4L));
+
    /* set the default size */
    capture->width  = DEFAULT_V4L_WIDTH;
    capture->height = DEFAULT_V4L_HEIGHT;
@@ -1028,8 +1031,6 @@
    /* Print the CameraNumber at the end of the string with a width of one character */
    sprintf(deviceName, "/dev/video%1d", index);
 
-   /* w/o memset some parts  arent initialized - AKA: Fill it with zeros so it is clean */
-   memset(capture,0,sizeof(CvCaptureCAM_V4L));
    /* Present the routines needed for V4L funtionality.  They are inserted as part of
       the standard set of cv calls promoting transparency.  "Vector Table" insertion. */
    capture->FirstCapture = 1;