cv2.imwrite saves an OpenCV image array to disk. Give it a filename and image data; the filename extension selects the expected encoded image format. For example, saving a captured frame as photo.jpg creates a JPEG snapshot in the current directory. section 8.3.1
Save one camera frame
After cap.read() returns a frame, write it directly: cv2.imwrite('photo.jpg', frame). The captured frame is a NumPy ndarray; the example call returns True after saving the image. section 8.3.1 section 8.3.1
For repeated snapshots, put the write call in a small save_photo function. Generate a timestamp, replace colons in it with periods, then use it in a unique .jpg filename. Calling that function when the spacebar is pressed saves each live camera frame without overwriting earlier photos. section 8.3.3
Listing 8.2 snapshot.py: Taking a snapshot when the space key is pressed
#!/usr/bin/env python3
from datetime import datetime
import cv2
ESC_KEY = 27
BLUE = (255, 0, 0)
FONT = cv2.FONT_HERSHEY_SIMPLEX
TEXT_POS = (10, 30)
MSG_FRAME_COUNT = 10
def save_photo(frame):
stamp = datetime.now().isoformat().replace(':', '.')
cv2.imwrite(f'photo_{stamp}.jpg', frame)
def show_image(frame, messages):
if messages:
cv2.putText(frame, messages.pop(), TEXT_POS, FONT, 1, BLUE)
cv2.imshow('preview', frame)
def set_message(messages, text):
messages[:] = [text] * MSG_FRAME_COUNT
def main():
cap = cv2.VideoCapture(0)
assert cap.isOpened(), 'Cannot open camera'
messages = []
while (key := cv2.waitKey(1)) not in [ord('q'), ESC_KEY]:
ret, frame = cap.read()
assert ret, 'Cannot read frame from camera'
if key == ord(' '):
save_photo(frame)
set_message(messages, 'saving photo...')
show_image(frame, messages)
cap.release()
if __name__ == "__main__":
main()
Use the complete snapshot script to connect keyboard input, camera capture, timestamped imwrite calls, preview display, and camera cleanup. section 8.3.3
