Skip to content

Instantly share code, notes, and snippets.

@jcheong0428
Created May 23, 2022 06:34
Show Gist options
  • Save jcheong0428/0e80bb7f7e0e50cbd44fcf0e35265578 to your computer and use it in GitHub Desktop.
Save jcheong0428/0e80bb7f7e0e50cbd44fcf0e35265578 to your computer and use it in GitHub Desktop.
OpenCV webcam example
# import packages.
import numpy as np
import cv2
import time
# Initialize the fist webcam as webCam
webCam = cv2.VideoCapture(0)
# Define the codec, fps, and resolution, to create the VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
fps = 30
width = 1280
height = 720
out = cv2.VideoWriter('output.mp4', fourcc, fps, (width, height))
# Initialize font, framecount, and start time.
font = cv2.FONT_HERSHEY_SIMPLEX
frameCount = 0
start = time.time()
# record
while(True):
# read frame from webcam
ret, frame = webCam.read()
end = time.time()
# calculate fps: frames per second
fps = int(1 / (end - start))
fps_str = "Estimated frames per second : {0}".format(fps)
# reset clock
start = time.time()
# output the frame to video
out.write(frame)
# show webcam stream with fps
cv2.putText(frame, fps_str, (7, 70), font, 1, (100, 255, 0), 3, cv2.LINE_AA)
cv2.imshow('frame', frame)
# break if 'q' key is pressed.
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
# release webcam and video writer
webCam.release()
out.release()
# close windows
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment