Skip to content

Instantly share code, notes, and snippets.

@laygond
Created April 5, 2024 00:15
Show Gist options
  • Save laygond/57b90718387b652564873a4a01510933 to your computer and use it in GitHub Desktop.
Save laygond/57b90718387b652564873a4a01510933 to your computer and use it in GitHub Desktop.
Take snapshots with your webcam by hitting the space bar on your keyboard.
#***
# USAGE: python snapshot.py -l optionalCustomLabelHere
#***
#
# Take snapshots with your webcam.
# - Exit with ESC
# - Snapshot with SPACE
#
# NOTE:
# -Change webcam src to your usb port number (Line 29)
# -With argument -l optionally pre-append a custom label
# to your images (default: 'snapshot')
#Import the necessary packages
import cv2
import time
from datetime import datetime
from imutils.video import VideoStream
import argparse
#Construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-l", "--label",
help="pre-append label to snapshots (optional)")
args = vars(ap.parse_args())
#Load cam
print("[INFO] Starting main video stream thread...")
vs = VideoStream(src=1).start()
time.sleep(2.0)
while True:
#Read the next frame from webcam
image = vs.read()
#Show the output image
cv2.imshow("Image", image)
#Grab key
key = cv2.waitKey(1) & 0xFF
#Exit with ESC
if key == ord("\x1b"):
print("[INFO] Escape hit, closing...")
break
#Snapshot with SPACE
if key == ord(" "):
img_label = args["label"] if args["label"] else 'snapshot'
img_id = ''.join(i for i in str(datetime.now()) if i.isdigit())
img_name = "{}_{}.png".format(img_label, img_id)
cv2.imwrite(img_name, image)
print("[INFO] {} saved!".format(img_name))
#Do a bit of cleanup
cv2.destroyAllWindows()
vs.stop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment