0

I am only able to capture small images with my webcam using opencv2 even though I can see higher resoution using cheese and over the command line uvcdynctrl (see output at bottom).

Here is my python code which works on a raspberry pi, but not on my laptop.

import cv2
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
print(width, height)
### outputs 176.0 144.0

    (base) ~/code/CaptureQueen$ uvcdynctrl -f
Listing available frame formats for device video0:
Pixel format: MJPG (Motion-JPEG; MIME type: image/jpeg)
  Frame size: 160x120
    Frame rates: 30, 25, 20, 15, 10, 5
  Frame size: 176x144
    Frame rates: 30, 25, 20, 15, 10, 5
  Frame size: 320x240
    Frame rates: 30, 25, 20, 15, 10, 5
  Frame size: 352x288
    Frame rates: 30, 25, 20, 15, 10, 5
  Frame size: 640x480
    Frame rates: 30, 25, 20, 15, 10, 5
  Frame size: 800x600
    Frame rates: 15, 10, 5
Pixel format: YUYV (YUYV 4:2:2; MIME type: video/x-raw-yuv)
  Frame size: 160x120
    Frame rates: 15, 10, 5
  Frame size: 176x144
    Frame rates: 15, 10, 5
Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
  • 2
    The 640x480 size is only available with MJPG format, and the default is format is YUYV. I don't know if it's going to work. Try: `cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG')` (before `cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)`) – Rotem Jan 05 '23 at 14:32
  • Thanks, I'll try when I get home tonight. – user1859871 Jan 05 '23 at 14:55
  • I don't think it's going to work... In case the camera is V4L compatible, you may try using FFmpeg (using a pipe) instead of OpenCV. The [following post](https://stackoverflow.com/a/59574988/4926757) and [this one](https://superuser.com/a/495685/635712), show how to select `mjpeg` format. [Here](https://stackoverflow.com/a/67357382/4926757) is an example for using FFmpeg for reading from a file. If you want, I can post an answer showing how to grab from a webcam using FFmpeg (I need to know the device name). – Rotem Jan 05 '23 at 17:19
  • 1
    it's going to work. the listed pixel formats clearly say 640x480 is only available for MJPG. set the FOURCC as Rotem showed. play with the order of the set() calls. it matters. some people need to set the FOURCC last for this to work, some need to set it first. – Christoph Rackwitz Jan 05 '23 at 17:22
  • Friggin' genius!! it worked... thanks a lot! – user1859871 Jan 05 '23 at 22:19

1 Answers1

0

Thanks to @Rotem for suggesting the fix! Code posted below for completness.

import cv2
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG')
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
print(width, height)
### old output: 176.0 144.0
### new output: 640.0 480.0