When using the OpenCV library to capture images from a webcam, ensure that OpenCV is installed. If not, install it via pip:
bashpip install opencv-python
Next, create a Python script that implements the following functionalities:
- Initialize the webcam
- Create a window to display the webcam's real-time video
- Capture images upon mouse click events
- Save the captured image
- Exit the program
Here is a simple example script that achieves this:
pythonimport 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 thecapture_imagefunction.- In the
capture_imagefunction, 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 回复