0
votes

I have a piece of c++ code:

#include <opencv/highgui.h>
#include <iostream>

int main()
{
    CvCapture* capture = cvCaptureFromCAM(CV_CAP_ANY); //tried (0) too
    if(capture == NULL)
        std::cout<<"NULL"<<std::endl;

    return 0;
}

and compile it using:

g++ main.cpp `pkg-config opencv --cflags` `pkg-config opencv --libs`

and the result of ./a.out is

NULL

I use OpenCV 2.4.2 and Ubuntu 12.04

But I am sure that my webcam is good because the following python code works fine.

import cv2
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
cv2.imshow('frame', frame) # it shows a correct image from the webcam
cv2.waitKey(0)

Does anyone have idea why I cannot read my webcam in the C++ code?

Update:

I then upgrade OpenCV to 2.4.8 and compile the C++ code again. The output is still NULL be it shows some error message:

VIDIOC_QUERYMENU: Invalid argument
VIDIOC_QUERYMENU: Invalid argument
VIDIOC_QUERYMENU: Invalid argument
VIDIOC_QUERYMENU: Invalid argument
VIDIOC_QUERYMENU: Invalid argument
VIDIOC_QUERYMENU: Invalid argument
libv4l2: error setting pixformat: Device or resource busy
HIGHGUI ERROR: libv4l unable to ioctl S_FMT
libv4l2: error setting pixformat: Device or resource busy
libv4l1: error setting pixformat: Device or resource busy
HIGHGUI ERROR: libv4l unable to ioctl VIDIOCSPICT

NULL
3

3 Answers

1
votes

I saw that it says that "Device/Resource is busy"...i think that you are using your webcam somewhere else...e.g. skype etc. Else try to use the following code:

Try to use (1) instead of (0)

VideoCapture cap(1);

for(;;)
{
    Mat frame;
    cap >> frame;
    imshow("My webcam", frame);
}

The above code is for C++ format and if you want to get an IplImage you can add the following line to convert the "frame" which is in Mat format into IplImage* format

IplImage* img = new IplImage(frame);
cvShowImage("IplImage format webcam", img);
0
votes

Then I rebooted the system and it is solved. Well...

0
votes

Defaultly when you connect your camera to your linux system, a process called "motion" will keep it occupied. You have to kill it. The following command will find and kill the "motion".

sudo killall -9 motion

After executing this, I guess your code will work. Please do share if you managed to solve it. Thanks