As an Amazon Associate we earn from qualifying purchases.
A common task in computer vision projects is showing a live camera preview and saving a single frame when you press a key. This article shows how to do that with Python and OpenCV, using the key as the trigger. The script opens the camera, displays a live window, saves the current frame as a JPEG when you press 0, and then shows the saved picture.
If you only need the basics of grabbing one frame, see our guide on how to capture an image with Python and OpenCV. This page focuses on the key-press version.
What you need
- Python 3 installed on your computer.
- The OpenCV package for Python (installed with pip install opencv-python).
- A working webcam or built-in laptop camera that no other app is using.
The complete script
The original version of this script used xrange, which only exists in Python 2, and ended with del(camera). The version below uses range so it runs on Python 3, and it releases the camera properly.
import cv2
camera_port = 0 # camera number
camera = cv2.VideoCapture(camera_port) # activates the camera
if not camera.isOpened():
raise RuntimeError("Could not open the camera")
# skip the first 30 frames so the camera can adjust exposure
for i in range(30):
camera.read()
while True:
retval, f = camera.read()
if not retval:
print("Could not read a frame from the camera")
break
cv2.imshow("preview", f)
# 48 is the ASCII code of the number 0
if cv2.waitKey(1) & 0xFF == 48:
cv2.imwrite("test1.jpg", f)
cv2.destroyAllWindows()
cv2.imshow("image", f)
cv2.waitKey(0)
break
camera.release()
cv2.destroyAllWindows()How the script works
Opening the camera
cv2.VideoCapture(0) opens the camera with index 0, which is normally the default camera. If you have more than one camera, such as a laptop webcam and a USB camera, try 1 or 2 to select another one. The isOpened() check stops the script with a clear message if the camera cannot be opened, instead of failing later with a confusing error.
Skipping the first frames
Many webcams return dark or washed-out images in the first moments after they start, because auto exposure and white balance have not settled yet. Reading and discarding 30 frames gives the camera time to adjust. The exact number is not special, so you can raise or lower it to suit your camera.
Showing the live preview
Inside the loop, camera.read() returns two values: a success flag and the frame itself, which is a NumPy array. cv2.imshow draws that frame in a window called “preview”. Because the loop runs continuously, the window behaves like a live video feed.
Detecting the key press
cv2.waitKey(1) waits one millisecond for a key press and returns its code, or -1 if nothing was pressed. It also gives OpenCV time to refresh the window, so the preview will not appear if you leave it out. The code 48 is the ASCII value of the character 0, so the script reacts when you press that key. You can also write ord(“0”) instead of 48, which is easier to read.
The & 0xFF part keeps only the lowest 8 bits of the returned value. On some systems the full value contains extra bits, and this mask makes the comparison reliable.
Saving and showing the image
cv2.imwrite(“test1.jpg”, f) writes the current frame to a file in the folder where you run the script. The file format is chosen from the extension, so use .png if you want lossless output. The script then closes the preview and opens the saved frame in a new window. Pressing any key in that window ends the program. If you want to learn more about this step, see our notes on writing a new image in Python.
Cleaning up
camera.release() frees the camera so other programs can use it. cv2.destroyAllWindows() closes any OpenCV windows still open. Skipping these calls can leave the camera locked until the Python process exits.
Using a different key
To trigger the capture with another key, change the comparison. For example, ord(“s”) saves when you press S, and ord(“q”) is a common choice for quitting. You can also combine them: save on one key and exit on another, so you can take several pictures in one session. In that case, give each file a different name, for example by adding a counter to the file name, or each new image will overwrite the last one.
Checking the saved picture
After the script finishes, you should find test1.jpg next to your script. You can open it in any image viewer, or load it again in code. Our article on opening an image in Python covers the common ways to do that.
Common problems and fixes
- The preview window does not respond to the 0 key. The OpenCV window must have focus. Click on it first, then press 0. Also check that you are pressing the 0 on the main keyboard row or the numeric keypad, depending on your setup, and that Num Lock is on if you use the keypad.
- NameError: xrange is not defined. You are running the old Python 2 code on Python 3. Replace xrange with range.
- The camera does not open. Close other apps that may be using it, such as video call software, and try a different camera index. On Windows, passing cv2.CAP_DSHOW as a second argument to VideoCapture sometimes helps.
- The saved image is dark. Increase the number of skipped frames at the start so the camera can finish adjusting.
- The window never appears on a remote or headless machine. imshow needs a display. On a server without one, remove the preview and save frames based on a different trigger.
- The file is not where you expect. A relative file name is saved in the current working directory, which may not be the script’s folder. Use a full path if in doubt.
Related reading
If you work with MATLAB instead of Python, you can also learn how to capture an image from a USB webcam in MATLAB.
FAQ
Why does the script use 48 for the 0 key?
48 is the ASCII code for the character 0. cv2.waitKey returns the code of the key pressed, so comparing it with 48 checks for that key. Writing ord(“0”) gives the same result and is easier to understand.
How do I use a different camera?
Change camera_port to another number, such as 1 or 2. Index 0 is usually the default camera, and additional cameras take the following numbers.
Can I save the image as PNG instead of JPG?
Yes. Change the file name in cv2.imwrite to end in .png. OpenCV picks the format from the extension, and PNG keeps the full quality of the frame.
Why do I need to call camera.release()?
It tells the operating system that your program has finished with the camera. Without it, the camera may stay busy until the program fully exits, which can stop other applications from using it.