How to record video from a camera using OpenCV on Mac

Joel Masters
Jun 19, 2021

Photo by Waldemar Brandt on Unsplash

OpenCV has several nuances and silent fails that makes recording videos from cameras difficult and frustrating. Here’s how to record from a camera:

import cv2cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
out = cv2.VideoWriter('output.mp4', fourcc, 20.0, (w,h))

while(cap.isOpened()):
ret, frame = cap.read()
if ret:
out.write(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()

Adapted from: https://stackoverflow.com/questions/29317262/opencv-video-saving-in-python/45868817

If your videos are being saved as ~6kb files, there is likely a size mismatch between the resolution of the camera and the VideoWriter.

Hope this helps.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Joel Masters
Joel Masters

No responses yet

Write a response