Python OpenCV access webcam maximum resolution

logitechopencvpythonresolutionwebcam

I am trying to acquire images from my webcam using a python code that imports OpenCV. The code is the following:

import sys
sys.path.append("C:\\opencv\\build\\python\\2.7")
import cv2
import cv2.cv as cv
import time

# Set resolution
cap = cv2.VideoCapture(0)
print "Frame default resolution: (" + str(cap.get(cv.CV_CAP_PROP_FRAME_WIDTH)) + "; " + str(cap.get(cv.CV_CAP_PROP_FRAME_HEIGHT)) + ")"
cap.set(cv.CV_CAP_PROP_FRAME_WIDTH, 800)
cap.set(cv.CV_CAP_PROP_FRAME_HEIGHT, 600)
print "Frame resolution set to: (" + str(cap.get(cv.CV_CAP_PROP_FRAME_WIDTH)) + "; " + str(cap.get(cv.CV_CAP_PROP_FRAME_HEIGHT)) + ")"

# Acquire frame
capture = cv.CreateCameraCapture(0)
img = cv.QueryFrame(capture)

The code works fine, except that the Camera default resolution is 640×480, and my code seems to be able to set only resolution values lower than that. For example, I can set the image size to 320×240, but I can't change it to 800×600. I have no error appearing: simply the resolution is set to the default one (640×480) as I try to set it to higher values.

The camera I am using (no other webcam is connected to the computer) is the QuickCam V-UBK45: with the software provided by Logitech, I am able to take pictures at full resolution (1280×960) and at all intermediate ones (e.g. 800×600).

Therefore, those frame sizes are supported from the hardware, but my code can't access them.

Does anyone know what I can do?

Best Answer

The problem as mentioned above is caused by the camera driver. I was able to fix it using Direct Show as a backend. I read (sorry, but I do not remember where) that almost all cameras provide a driver that allows their use from DirectShow. Therefore, I used DirectShow in Windows to interact with the cameras and I was able to configure the resolution as I wanted and also get the native aspect ratio of my camera (16: 9). You can try this code to see if this works for you.

import cv2

cam = cv2.VideoCapture(0,cv2.CAP_DSHOW)

cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)

r, frame = cam.read()
...
print('Resolution: ' + str(frame.shape[0]) + ' x ' + str(frame.shape[1]))

In the OpenCV documentation, I found the following information for those who want to know more about OpenCV backends (OpenCV docs)

I hope this can help you!