Collin McGuire
Collin McGuire

Reputation: 724

Problems using webcam in python + openCV

I am using the following code to access my webcam using openCV + python...

import cv

cv.NamedWindow('webcam_feed', cv.CV_WINDOW_AUTOSIZE)

cam = cv.CaptureFromCAM(-1)

I am then getting the following error in the console...

VIDIOC_QUERYMENU: Invalid argument
VIDIOC_QUERYMENU: Invalid argument
VIDIOC_QUERYMENU: Invalid argument

I was originally using,

cv.CaptureFromCAM(0)

to access the same and had the same issue and used -1 because it is suppose to pick up any webcam.

I also tested to see if Ubuntu recognizes the webcam and it does. I am using v4l2 for the webcam.

{EDIT}

I am using the following code to display a video feed, it seems to only be showing just one image the web cam captured instead of a continuous video feed...

import cv
cv.NamedWindow('webcam_feed', cv.CV_WINDOW_AUTOSIZE)
cam = cv.CaptureFromCAM(-1)
feed = cv.QueryFrame(cam)
cv.ShowImage("webcam_feed", feed)
cv.WaitKey(-1)

Upvotes: 5

Views: 12729

Answers (3)

Compusam
Compusam

Reputation: 261

For me, the command in root

xhost +

save my time, Note to close and open new terminal.

See you.

Upvotes: 0

Collin McGuire
Collin McGuire

Reputation: 724

WOW, answered my own question in 15 after me posting this. I did some research and the reason for the web cam only grabbing one image is because of the...

cv.WaitKey(-1)

This doesn't allow the contents of the window to refresh. I set the number to 10...

cv.WaitKey(10)

and it worked beautifully. I also tried 100, but saw no difference. I only saw a difference when the number was 1000. I use 1 because seems that it runs the smoothest.

Here is the full code to display a web cam feed

import cv

cv.NamedWindow("webcam", 1)

cam = cv.CaptureFromCAM(-1)

While True:
feed = cv.QueryFrame(cam)
cv.ShowImage("webcam", feed)
cv.WaitKey(1)

Upvotes: 1

Brian L
Brian L

Reputation: 3251

I believe you need to put

frame = cv.QueryFrame(cam)
cv.ShowImage("Webcam Feed", frame)

in a loop to continuously update the image shown in the window. That is, the frame from cv.QueryFrame is a static image, not a continuous video.

If you want to be able to exit with a key press, test cv.WaitKey with a small timeout in the loop too.

Upvotes: 0

Related Questions