I am attempting to set focus on a webcam, and take a photo. However the focus is unwilling to change. I will be using this on a Raspberry Pi 5 as well. I’ll post my code snippet if anyone can take a look and help me work through it that would be very appreciated.
import cv2
import time
def camera_snapshot():
cap = cv2.VideoCapture(0)
cap.set(28, 0)
# Set the resolution
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 3840) # Width
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 2160) # Height
# Set focus
cap.set(cv2.CAP_PROP_FOCUS, 20)
# Additional delay to allow the camera to adjust to the new resolution
time.sleep(.1)
ret, frame = cap.read()
if ret:
cv2.imwrite('captured_image.jpg', frame)
print("Image captured successfully")
else:
print("Failed to capture image")
cap.release()
amera_snapshot()
how do I put this…
it’s not gonna be as easy as you think.
servo focus takes a moment to settle. it takes a moment to even start moving.
there is no focus in the world that you can just set and it instantly applies.
cameras make frames at their own pace. they don’t care when you’ll ask for the frames. the frames get made regardless. there is buffering. “buffering” does not mean a fixed lag. it means stuff will pile up, unless you continually read it. first in, first out. that time.sleep() is pointless in that piece of code. it merely causes frames to pile up. the first read() is the very first frame, and it will be the same with or without any sleep(). with the sleep() it will merely be “older” because “now” is later.
if you just want to take a picture, there are a whole lot of programs for that. even command line programs. in the “raspberry pi” space, lots of people make lots of tools. most of them are junk. be aware of that when evaluating them. going by popularity is not necessarily going to help. even popular options may be junk. you should evaluate on technical merit.
OpenCV is not made to take snapshots. wrong library. OpenCV is for computer vision. you can use it for your snapshotting needs, but don’t expect things to be user-friendly. it’s a library, not a tool. you will have to know stuff at a depth that you weren’t aware of before.
you will need to read more than one frame. that’s for sure. if you read a few more, you should see the focus setting taking effect.
Thank you for your thorough response. I have no experience in computer vision, the plan is to collect lots of data via pictures using OpenCV then classify them. Not sure if it is the best option for what I want, just one of the first that I came across.
in that case, I’d recommend keeping the program running, showing live video continuously with cv.imshow()
and companion functions
you can easily handle mouse clicks or any key presses while the image window is active.