clinuxopencvwebcamvideo4linux

OpenCV fails to recognize webcam, but mplayer succeeds


As a first step on a larger project I was trying to display the imagem from my webcam using OpenCV:

#include <stdlib.h>                                                         
#include <opencv2/core/core.hpp>                                            
#include <opencv2/highgui/highgui.hpp>                                      

int                                                                         
main()                                                                      
{                                                                           
  cv::VideoCapture cap(-1);                                                 
  if (!cap.isOpened())                                                   
    exit(EXIT_FAILURE);                                                                                                                             
  cv::Mat frame;                                                            
  bool done = false;                                                        
  while (!done) {                                                           
    cap >> frame;                                                           
    cv::imshow("webcam", frame);                                            
    done = (cv::waitKey(30) >= 0);                                          
  }                                                                         
  return EXIT_SUCCESS;                                                      
}                                                                           

This returns an error code (!cap.isOpened() passes ,confirmed with gdb). Initially I had 0 instead of -1. When searching this site -1 was suggested, but it was to no avail. I also tried 1 through 3, as another user suggested it.

I can display my webcam using mplayer, more specifically mplayer tv:// -tv driver=v4l2.


Solution

  • v4l2 is the "video for linux" driver. I noticed OpenCV can be installed with such driver by compiling it with -DWITH_V4L and -DWITH_LIBV4L (v4l USE flag in Gentoo). After recompiling OpenCV with it, it successfully recognized the webcam. GTK support seems to be needed to display the image.