Skip to content

Instantly share code, notes, and snippets.

@tmattio
Created March 16, 2016 02:57
Show Gist options
  • Save tmattio/c041eeda27b4cc9994b1 to your computer and use it in GitHub Desktop.
Save tmattio/c041eeda27b4cc9994b1 to your computer and use it in GitHub Desktop.
A simple python script for capturing images from a webcam and building a video from it
# This script is based on https://github.com/nvellon/timelapse
import os
import sys
import time
import cv2
command = 'capture'
cam_num = 0
output_path = 'out/'
image_prefix = 'timelapse_'
clicked = False
fps = 20
size = (640, 480)
def print_params():
print("Params: " + str(sys.argv))
def sorted_ls(path):
mtime = lambda f: os.stat(os.path.join(path, f)).st_mtime
return list(sorted(os.listdir(path), key=mtime))
def build_video():
global output_path, fps, size
if len(sys.argv) > 2:
output_path = sys.argv[2]
if len(sys.argv) > 3:
fps = int(sys.argv[3])
video_writer = cv2.VideoWriter('time_lapse.avi', cv2.cv.CV_FOURCC('M', 'J', 'P', 'G'), fps, size)
for file in sorted_ls(output_path):
if file.endswith(".jpg"):
image = cv2.imread(output_path + file)
video_writer.write(image)
def capturing():
global cam_num, output_path, image_prefix
if len(sys.argv) > 2:
cam_num = int(sys.argv[2])
if len(sys.argv) > 3:
output_path = sys.argv[3]
if len(sys.argv) > 4:
image_prefix = sys.argv[4]
camera_capture = cv2.VideoCapture(cam_num)
success, frame = camera_capture.read()
while not success:
success, frame = camera_capture.read()
cv2.imwrite(output_path + image_prefix + str(time.time()) + '.jpg', frame)
def on_mouse(event, x, y, flags, param):
global clicked
if event == cv2.cv.CV_EVENT_LBUTTONUP:
clicked = True
def testing():
global clicked, cam_num
if len(sys.argv) > 2:
cam_num = int(sys.argv[2])
camera_capture = cv2.VideoCapture(cam_num)
cv2.namedWindow('MyWindow')
cv2.setMouseCallback('MyWindow', on_mouse)
success, frame = camera_capture.read()
while success and cv2.waitKey(1) == -1 and not clicked:
cv2.imshow('MyWindow', frame)
success, frame = camera_capture.read()
cv2.destroyWindow('MyWindow')
def exec_command(command):
if command == 'test':
testing()
elif command == 'capture':
capturing()
elif command == 'build':
build_video()
else:
print("wrong command!")
def main():
if len(sys.argv) > 1:
command = sys.argv[1]
exec_command(command)
print_params()
print("done!")
else:
print('no command given')
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment