How to capture a image from webcam in Python?

How to capture a image from webcam in Python?

To capture an image from a webcam in Python, you can use the OpenCV library, which provides extensive functionalities for computer vision tasks.

Here's a step-by-step guide to capture an image from a webcam using OpenCV:

  • First, you'll need to install OpenCV. You can do this with pip:
pip install opencv-python 
  • Then, you can write the Python script to capture an image from the webcam:
import cv2 # Open the webcam cap = cv2.VideoCapture(0) # Check if the webcam is opened correctly if not cap.isOpened(): print("Could not open webcam") exit() # Read a frame from the webcam ret, frame = cap.read() # Check if the frame is captured correctly if not ret: print("Failed to grab frame") exit() # Save the frame as an image file cv2.imwrite('captured_image.jpg', frame) # Display the captured image in a window cv2.imshow('Captured Image', frame) cv2.waitKey(0) cv2.destroyAllWindows() # Release the webcam cap.release() 

When you run the above script, it'll capture a single frame from the default webcam (usually the built-in webcam for laptops) and save it as captured_image.jpg in the current directory. It'll also display the captured image in an OpenCV window. You can close the window by pressing any key.


More Tags

rx-kotlin mdx calculation signed-apk latitude-longitude jquery-animate android-7.0-nougat windows-subsystem-for-linux automatic-ref-counting long-long

More Programming Guides

Other Guides

More Programming Examples