liveBook · Manning

Imwrite

As explained in Build Your Own Robot: Using Python, CRICKIT, and Raspberry Pi

OpenCV imwrite encodes image data according to a filename extension and writes it to a file.

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

How Build Your Own Robot: Using Python, CRICKIT, and Raspberry Pi covers it

How deep it goes
Demonstrates direct calls and a reusable timestamped save function, without detailing image codecs or encoding internals.
Examples
Uses photo.jpg for one captured frame and photo_<timestamp>.jpg files for spacebar-triggered snapshots.
What it assumes
Uses OpenCV camera capture and NumPy image arrays, while demonstrating the needed imwrite call directly.
What you can do after
Apply it via OpenCV to save captured camera frames as JPEG files with fixed or timestamped names.
How it connects
Connects camera capture, NumPy ndarray frames, keyboard input, datetime timestamps, imshow, and video-stream release.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build Your Own Robot: Using Python, CRICKIT, and Raspberry Pi. The section links point to the parts of the book it draws on.