From RidgeRun Developer Wiki
import cv2
CAMERA_INDEX = 0
TOTAL_NUM_FRAMES = 100
FRAMERATE = 30.0
def is_camera_available(camera_index=0):
cap = cv2.VideoCapture(camera_index)
if not cap.isOpened():
return False
cap.release()
return True
def main():
if is_camera_available(CAMERA_INDEX):
print(f"Camera {CAMERA_INDEX} is available.")
else:
print(f"Camera {CAMERA_INDEX} is not available.")
exit()
cap = cv2.VideoCapture(CAMERA_INDEX)
if not cap.isOpened():
print("Error: Could not open video stream.")
exit()
print("Camera opened successfully.")
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('output.mp4', fourcc, FRAMERATE, (frame_width, frame_height))
num_frames = 0
while True:
ret, frame = cap.read()
if not ret:
print("Error: Failed to capture image.")
break
out.write(frame)
print(f"Recording: {num_frames} / {TOTAL_NUM_FRAMES}", end='\r')
if num_frames >= TOTAL_NUM_FRAMES:
print("\nCapture duration reached, stopping recording.")
break
num_frames += 1
cap.release()
out.release()
if __name__ == '__main__':
main()