乐闻世界logo
搜索文章和话题

Python : how to capture image from webcam on click using OpenCV

1个答案

1

When using the OpenCV library to capture images from a webcam, ensure that OpenCV is installed. If not, install it via pip:

bash
pip install opencv-python

Next, create a Python script that implements the following functionalities:

  1. Initialize the webcam
  2. Create a window to display the webcam's real-time video
  3. Capture images upon mouse click events
  4. Save the captured image
  5. Exit the program

Here is a simple example script that achieves this:

python
import cv2 def capture_image(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDOWN: ret, frame = cap.read() if ret: cv2.imwrite('captured_image.jpg', frame) print("Image captured and saved!") # Initialize the webcam cap = cv2.VideoCapture(0) # 0 represents the default webcam # Create a window cv2.namedWindow("Webcam") # Bind mouse click event cv2.setMouseCallback("Webcam", capture_image) while True: # Read the current frame from the webcam ret, frame = cap.read() if not ret: print("Failed to grab frame") break # Display the frame cv2.imshow("Webcam", frame) # Exit loop by pressing 'q' key if cv2.waitKey(1) & 0xFF == ord('q'): break # Release webcam resources cap.release() # Close all OpenCV-created windows cv2.destroyAllWindows()

Code Explanation:

  • cv2.VideoCapture(0): Initializes the webcam. The number 0 specifies the default webcam.
  • cv2.namedWindow("Webcam"): Creates a window named "Webcam".
  • cv2.setMouseCallback("Webcam", capture_image): Binds the mouse click event to the capture_image function.
  • In the capture_image function, a left mouse button click triggers reading the current frame and saving it as an image.
  • The main loop continuously reads and displays webcam frames until the user presses 'q' to exit.

This script captures the current frame from the webcam when the user clicks the left mouse button within the window and saves it as a JPEG file. This approach captures only a single frame from the live video stream, making it ideal for straightforward image capture tasks.

2024年8月15日 11:39 回复

你的答案