CAPTURING AN IMAGE FROM CAMERA USING PYTHON AND OPEN CV

Photo of author

By Jackson Taylor

Home » Electronics Topics » Python & OpenCv » CAPTURING AN IMAGE FROM CAMERA USING PYTHON AND OPEN CV

As an Amazon Associate we earn from qualifying purchases.

Taking a picture from a webcam or USB camera takes only a few lines of Python when you use OpenCV. This article gives you a working script that grabs a frame from the camera, saves it as a JPEG file and shows it on screen. It then explains each line and covers the problems people most often run into.

What you need

  • Python 3 installed on your computer.
  • The OpenCV package for Python, installed with pip install opencv-python.
  • A working camera, either built into your laptop or connected over USB.

If you are new to the library, our introduction to OpenCV is a good place to start.

Python code to capture an image from the camera

The original version of this script used xrange, which only exists in Python 2. The version below uses range and works in Python 3. It also checks that the camera opened and releases it at the end.

Hardware Hack

Stop Buying New Batteries for Your Tech

Electronics are expensive, but their power sources don't have to be. Discover the simple engineering trick to recondition dead batteries and bring your gadgets back to 100% capacity.

Watch the Free Video
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
for i in range(30):
    retval, f = camera.read()

if retval:
    cv2.imwrite("test1.jpg", f)  # save the last frame to disk
    cv2.imshow("image", f)       # show it in a window
    cv2.waitKey(0)               # wait until a key is pressed
    cv2.destroyAllWindows()

camera.release()  # free the camera for other programs

Save the code as a .py file and run it. After a moment a window opens with the captured picture, and a file named test1.jpg appears in the folder you ran the script from.

How the code works

Importing OpenCV

The line import cv2 loads the OpenCV module. Even though the package is called opencv-python, you always import it as cv2.

Choosing the camera

camera_port = 0 is the camera number. Index 0 is normally the default camera, which on a laptop is the built-in webcam. If you plug in a second camera, try 1 or 2.

Opening the camera

cv2.VideoCapture(camera_port) creates a capture object and starts the connection to the camera. The isOpened() check tells you right away if something went wrong, instead of failing later with a confusing error.

See also
PLOTTING DATA ON INTERNET USING PYTHON AND THINGSSPEAK.COM

Skipping the first frames

Many cameras return dark or poorly exposed images for the first few frames, because auto exposure and white balance need a moment to settle. The loop reads 30 frames and throws them away, so the frame you save is the last one read. Thirty is not a magic number. A webcam that settles quickly may need far fewer, and a slow one may need more.

Reading and saving the frame

Each call to camera.read() returns two values. The first, retval, is True if a frame was read successfully. The second is the image itself, stored as a NumPy array. cv2.imwrite(“test1.jpg”, f) writes that array to a file, and the extension decides the format. Use .png if you want lossless output. For more on saving files, see our guide to writing a new image in Python.

Showing the image and cleaning up

cv2.imshow opens a window with the picture. cv2.waitKey(0) pauses the script until you press a key while the window is selected. Without it the window would close instantly. cv2.destroyAllWindows() then closes the window. Finally, camera.release() hands the camera back to the system. The original script used del(camera) for this, but release() is the proper method.

Capturing the image on a key press

The script above takes the picture automatically. If you want to preview the live video and save a frame only when you choose, see how to capture an image when a key is pressed. That approach reads frames in a loop and checks for a key on every pass.

Checking the saved picture

To confirm the file saved correctly, load it again with OpenCV or open it in any image viewer. Our article on opening an image in Python shows how to do this in code.

Common problems and fixes

  • NameError: name ‘xrange’ is not defined. You are running Python 3. Replace xrange with range.
  • The camera does not open. Another program, such as a video call app, may be using it. Close it and try again. You can also try a different camera index.
  • The saved image is black or very dark. Increase the number of skipped frames so the camera has more time to adjust.
  • On Windows, opening the camera is slow or fails. Try cv2.VideoCapture(0, cv2.CAP_DSHOW), which uses a different backend.
  • imshow raises an error. This usually means you installed the headless build of OpenCV, which has no window support. Install the standard opencv-python package instead.
  • The file is not where you expect. A relative name like test1.jpg is saved in the current working directory. Use a full path if you want it somewhere else.
See also
CIRCUIT WIZARD

Tips for better results

  • Make sure the scene is well lit. Low light gives noisy images whatever the code does.
  • Give each picture a unique file name, for example by adding a counter, so you do not overwrite earlier shots.
  • Always check retval before using the frame. If the read failed, the frame will be empty and imwrite will not work.
  • Call release() every time. Leaving the camera open can block it from other programs until your script exits.

Frequently asked questions

How do I choose a different camera in OpenCV?

Change the number passed to cv2.VideoCapture. 0 is usually the default camera, and 1, 2 and so on are additional cameras. If one index does not work, try the next.

Sustainable Tech

Keep Toxic E-Waste Out of Landfills

Don't throw away your failing laptop, phone, or car batteries. Learn how to recondition them at home in just a few hours. It's better for the planet—and your wallet.

Learn How It Works

Why do I need to read 30 frames before saving?

The first frames from many cameras are dark or blurry while the sensor adjusts exposure and focus. Discarding them gives you a more usable picture.

Can I save the image as PNG instead of JPG?

Yes. Change the file name to end in .png, for example cv2.imwrite(“test1.png”, f). OpenCV picks the format from the extension.

Does this work on Windows, macOS and Linux?

Yes, the same code works on all three, as long as OpenCV is installed and the system lets Python access the camera. On macOS you may need to grant camera permission to your terminal or editor.

Revive Your Dead Electronics

Got a drawer full of dead gadgets or a failing car battery? Instead of paying a premium for replacements, use this simple trick to easily recondition them right from home.

See How It Works