How to set manual focus distance with libcamera / 64mp / C++

This looks like it works to change the focus in python manually for picamera2 (if it is updated to the latest version!)

Here is link to some example …

This is great! By the way, do you happen to know how to READ what the current focus level is?

For instance if i want to run the autofocus, and then use the focus that it arrived on and take multiple photos with the focus changed in either direction to do some focus stacking?

You can use Focuser.py provided with the driver package. Read and write.

1 Like

I searched, but it looks like it’s not possible to get a reading from autofocus. So the only way is to manually focus via focuser.py and then pass the data here to manual focus.

1 Like

The focuser.py program is somehow reading what the current focus level is, but im not sure how.

anyone have any ideas?

You can find this line in focuser.py

self.focus_value = v4l2_utils.get_ctrl(self.fd, Focuser.FOCUS_ID)

Personally, I don’t think this value is set by autofocus, but only if I set it with the previous command when using manual focus or this utility.

1 Like

cool! ill try that out!

so what i have noticed about the focuser example is this:

If i run a command using the autofocus in a different program and focus on something up close, and then close the program, and then i run the focuser example it starts up with a specific number (let’s say like 856)

then if i close that example, and run a different program to autofocus on something else, let’s say in the middle distance, and then i close that program, and open up the focuser again, it will start up with a different number (let’s say 439). So it looks to me like it’s somehow reading what the last focused value of the camera was.

(caveat - Ive never actually gotten the focuser example to work (is it supposed to show you a preview image? because i just see a black screen with text, do other people see a preview image with the focuser example? it seems like that would make sense right?)

Oh, that’s interesting.

No focuser is just a script to change the focus. To preview it, you need to run, for example, libcamera-still -t 0 in the second panel.

1 Like

ohhhh ok! i didn’t realize i could run them at the same time! thanks!

my libcamera is 0.0.11 now (instead of 0…0.10 on a system i set up before)
and now none of the autofocusing working? or changing the focus (it says “Control AfMode is not advertised by libcamera”)

also the camera seems to take abysmally long to open :confused:

$ dpkg -l | grep libcamera
ii libcamera-apps 0.0.11 armhf libcamera-apps
ii libcamera-dev 0.0.11 armhf libcamera
glowcake@glowcake:~ $

i was looking through the picamera2 library manual from RPI and they say this is the way to do manual focus


from picamera2 import Picamera2
from libcamera import controls
picam2 = Picamera2()
picam2.start(show_preview=True)
picam2.set_controls({"AfMode": controls.AfModeEnum.Manual, "LensPosition": 0.0})

but it still doesn’t work for me, it gives and error when running on the set_controls command

@Edward What are the features of 0.11?

Would be nice if patches are annotated someway :wink:

1 Like
Valid options are:
  -h [ --help ] [=arg(=1)] (=0)         Print this help message
  --version [=arg(=1)] (=0)             Displays the build version number
  --list-cameras [=arg(=1)] (=0)        Lists the available cameras attached to the system.
  --camera arg (=0)                     Chooses the camera to use. To list the available indexes, use the 
                                        --list-cameras option.
  -v [ --verbose ] [=arg(=2)] (=1)      Set verbosity level. Level 0 is no output, 1 is default, 2 is verbose.
  -c [ --config ] [=arg(=config.txt)]   Read the options from a file. If no filename is specified, default to 
                                        config.txt. In case of duplicate options, the ones provided on the command line
                                        will be used. Note that the config file must only contain the long form 
                                        options.
  --info-text arg (=#%frame (%fps fps) exp %exp ag %ag dg %dg)
                                        Sets the information string on the titlebar. Available values:
                                        %frame (frame number)
                                        %fps (framerate)
                                        %exp (shutter speed)
                                        %ag (analogue gain)
                                        %dg (digital gain)
                                        %rg (red colour gain)
                                        %bg (blue colour gain)
                                        %focus (focus FoM value)
                                        %aelock (AE locked status)
                                        %lp (lens position, if known)
                                        %afstate (AF state, if supported)
  --width arg (=0)                      Set the output image width (0 = use default value)
  --height arg (=0)                     Set the output image height (0 = use default value)
  -t [ --timeout ] arg (=5000)          Time (in ms) for which program runs
  -o [ --output ] arg                   Set the output file name
  --post-process-file arg               Set the file name for configuring the post-processing
  --rawfull [=arg(=1)] (=0)             Force use of full resolution raw frames
  -n [ --nopreview ] [=arg(=1)] (=0)    Do not show a preview window
  -p [ --preview ] arg (=0,0,0,0)       Set the preview window dimensions, given as x,y,width,height e.g. 0,0,640,480
  -f [ --fullscreen ] [=arg(=1)] (=0)   Use a fullscreen preview window
  --qt-preview [=arg(=1)] (=0)          Use Qt-based preview window (WARNING: causes heavy CPU load, fullscreen not 
                                        supported)
  --hflip [=arg(=1)] (=0)               Request a horizontal flip transform
  --vflip [=arg(=1)] (=0)               Request a vertical flip transform
  --rotation arg (=0)                   Request an image rotation, 0 or 180
  --roi arg (=0,0,0,0)                  Set region of interest (digital zoom) e.g. 0.25,0.25,0.5,0.5
  --shutter arg (=0)                    Set a fixed shutter speed in microseconds
  --analoggain arg (=0)                 Set a fixed gain value (synonym for 'gain' option)
  --gain arg                            Set a fixed gain value
  --metering arg (=centre)              Set the metering mode (centre, spot, average, custom)
  --exposure arg (=normal)              Set the exposure mode (normal, sport)
  --ev arg (=0)                         Set the EV exposure compensation, where 0 = no change
  --awb arg (=auto)                     Set the AWB mode (auto, incandescent, tungsten, fluorescent, indoor, daylight, 
                                        cloudy, custom)
  --awbgains arg (=0,0)                 Set explict red and blue gains (disable the automatic AWB algorithm)
  --flush [=arg(=1)] (=0)               Flush output data as soon as possible
  --wrap arg (=0)                       When writing multiple output files, reset the counter when it reaches this 
                                        number
  --brightness arg (=0)                 Adjust the brightness of the output images, in the range -1.0 to 1.0
  --contrast arg (=1)                   Adjust the contrast of the output image, where 1.0 = normal contrast
  --saturation arg (=1)                 Adjust the colour saturation of the output, where 1.0 = normal and 0.0 = 
                                        greyscale
  --sharpness arg (=1)                  Adjust the sharpness of the output image, where 1.0 = normal sharpening
  --framerate arg (=-1)                 Set the fixed framerate for preview and video modes
  --denoise arg (=auto)                 Sets the Denoise operating mode: auto, off, cdn_off, cdn_fast, cdn_hq
  --viewfinder-width arg (=0)           Width of viewfinder frames from the camera (distinct from the preview window 
                                        size
  --viewfinder-height arg (=0)          Height of viewfinder frames from the camera (distinct from the preview window 
                                        size)
  --tuning-file arg (=-)                Name of camera tuning file to use, omit this option for libcamera default 
                                        behaviour
  --lores-width arg (=0)                Width of low resolution frames (use 0 to omit low resolution stream
  --lores-height arg (=0)               Height of low resolution frames (use 0 to omit low resolution stream
  --mode arg                            Camera mode as W:H:bit-depth:packing, where packing is P (packed) or U 
                                        (unpacked)
  --viewfinder-mode arg                 Camera mode for preview as W:H:bit-depth:packing, where packing is P (packed) 
                                        or U (unpacked)
  --buffer-count arg (=0)               Number of in-flight requests (and buffers) configured for video, raw, and 
                                        still.
  --viewfinder-buffer-count arg (=0)    Number of in-flight requests (and buffers) configured for preview window.
  --autofocus-mode arg (=default)       Control to set the mode of the AF (autofocus) algorithm.(manual, auto, 
                                        continuous)
  --autofocus-range arg (=normal)       Set the range of focus distances that is scanned.(normal, macro, full)
  --autofocus-speed arg (=normal)       Control that determines whether the AF algorithm is to move the lens as quickly
                                        as possible or more steadily.(normal, fast)
  --autofocus-window arg (=0,0,0,0)     Sets AfMetering to  AfMeteringWindows an set region used, e.g. 
                                        0.25,0.25,0.5,0.5
  --lens-position arg                   Set the lens to a particular focus position, expressed as a reciprocal distance
                                        (0 moves the lens to infinity), or "default" for the hyperfocal distance
  --hdr [=arg(=1)] (=0)                 Enable (1) or disable (0) High Dynamic Range, where supported
  --metadata arg                        Save captured image metadata to a file or "-" for stdout
  --metadata-format arg (=json)         Format to save the metadata in, either txt or json (requires --metadata)
  -q [ --quality ] arg (=93)            Set the JPEG quality parameter
  -x [ --exif ] arg                     Add these extra EXIF tags to the output file
  --timelapse arg (=0)                  Time interval (in ms) between timelapse captures
  --framestart arg (=0)                 Initial frame counter value for timelapse captures
  --datetime [=arg(=1)] (=0)            Use date format for output file names
  --timestamp [=arg(=1)] (=0)           Use system timestamps for output file names
  --restart arg (=0)                    Set JPEG restart interval
  -k [ --keypress ] [=arg(=1)] (=0)     Perform capture when ENTER pressed
  -s [ --signal ] [=arg(=1)] (=0)       Perform capture when signal received
  --thumb arg (=320:240:70)             Set thumbnail parameters as width:height:quality, or none
  -e [ --encoding ] arg (=jpg)          Set the desired output encoding, either jpg, png, rgb, bmp or yuv420
  -r [ --raw ] [=arg(=1)] (=0)          Also save raw file in DNG format
  --latest arg                          Create a symbolic link with this name to most recent saved file
  --immediate [=arg(=1)] (=0)           Perform first capture immediately, with no preview phase
  --autofocus-on-capture [=arg(=1)] (=0)
                                        Switch to AfModeAuto and trigger a scan just before capturing a still

So now, to trigger focus should be
libcamera-still -n --autofocus-mode=auto --autofocus-on-capture=1 -o /mnt/ramdisk/whatever.jpg --width=9152 --height=6944 -q 100

Hi @Edward,
any updates on how to read the focus position of the camera at a certain moment in Python?
Thanks,

Marco

@marcocava

Sorry, as far as I know, there is no other better way to use in picamera2 besides LensPosition. Please let me know if you find something, such as an upstream update, and I’ll be happy to sync it in.