For USB webcams that are UVC-compatible (as most are), there is a reasonable chance one can use the camera's autofocus and then lock it. To figure out whether the camera allows this via UVC, on Linux one can use v4l2-ctl
, which is in package v4l-utils
. v4l2-ctl -l
lists all available controls, v4l2-ctl -c
sets the value for a control, and v4l2-ctl -C
gets the value.
For example, the following commands did the trick for a Microsoft LifeCam Cinema on an Ubuntu 16.04 box that had a simple Python OpenCV program running to display the current frame:
> v4l2-ctl -d 0 -c focus_auto=1
> v4l2-ctl -d 0 -C focus_absolute
focus_absolute: 12
After moving the object closer to the camera, the focus changed, and I got a different value for focus_absolute
: (So UVC gives access to what what value the autofocus picked.)
> v4l2-ctl -d 0 -C focus_absolute
focus_absolute: 17
I then changed to manual focus and this locked the value the autofocus had picked:
> v4l2-ctl -d 0 -c focus_auto=0
> v4l2-ctl -d 0 -C focus_absolute
focus_absolute: 17
So for the LifeCam Cinema, the only thing the code would need to do is change the focus_auto
control initially to auto (1
) and then to manual once the focus is to be locked.
From Python, I typically run v4l2-ctl
simply by using subprocess.check_output()
. I recall seeing Windows libraries for UVC, but never played with them.