Changes

Jump to navigation Jump to search
1,699 bytes added ,  14:16, 28 April 2025
Line 32: Line 32:  
|}
 
|}
 
=== Python ===
 
=== Python ===
Example demonstrating how to record a video from a facecam:
+
Example demonstrating how to record a video with a facecam:
 
<syntaxhighlight lang="python" line>
 
<syntaxhighlight lang="python" line>
 
#!/usr/bin/env python3.10
 
#!/usr/bin/env python3.10
 
# -*- coding: utf-8 -*-
 
# -*- coding: utf-8 -*-
 +
 +
import datetime
 +
import cv2
 +
import ctypes
 +
import ffmpegcv
 +
 +
#set sleep to 1ms accuracy
 +
winmm = ctypes.WinDLL('winmm')
 +
winmm.timeBeginPeriod(1)
 +
 +
def configure_webcam(cam_id, width=1920, height=1080, fps=60):
 +
    cap = cv2.VideoCapture(cam_id, cv2.CAP_DSHOW)
 +
    if not cap.isOpened():
 +
        print(f"Error: Couldn't open webcam {cam_id}.")
 +
        return None
 +
 +
    # Try to set each property
 +
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
 +
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
 +
    cap.set(cv2.CAP_PROP_FPS, fps)
 +
 +
    # Read back the values
 +
    actual_width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
 +
    actual_height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
 +
    actual_fps = cap.get(cv2.CAP_PROP_FPS)
 +
 +
    print(f"Resolution set to: {actual_width}x{actual_height}")
 +
    print(f"FPS set to: {actual_fps}")
 +
 +
    return cap
 +
 +
def getWebcamData():
 +
    global frame_width
 +
    global frame_height
 +
 +
    print("opening webcam...")
 +
    camera = configure_webcam(1, frame_width, frame_height)
 +
    time_stamp = datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S')
 +
    file_name = time_stamp +'_output.avi'
 +
    video_writer = ffmpegcv.VideoWriter(file_name, 'h264', fps=freq)
 +
   
 +
    while True:
 +
        grabbed = camera.grab()
 +
        if grabbed:
 +
            grabbed, frame = camera.retrieve()
 +
           
 +
            video_writer.write(frame)  # Write the video to the file system
 +
           
 +
            frame = cv2.resize(frame, (int(frame_width/4),int(frame_height/4)))
 +
            cv2.imshow("Frame", frame)  # show the frame to our screen
 +
       
 +
        if cv2.waitKey(1) & 0xFF == ord('q'):
 +
            break
 +
 +
freq = 60
 +
frame_width = 1920
 +
frame_height = 1080
 +
 +
getWebcamData()
 +
 +
cv2.destroyAllWindows()
 
</syntaxhighlight>
 
</syntaxhighlight>
  

Navigation menu