[英]Python webcam record
我想創建一個記錄網絡攝像頭流的網絡攝像頭流應用程序,比如大約 30 秒,並將其保存為myFile.wmv
。 現在要獲得實時攝像頭饋送,我知道此代碼:-
import cv2
import numpy as np
c = cv2.VideoCapture(0)
while(1):
_,f = c.read()
cv2.imshow('e2',f)
if cv2.waitKey(5)==27:
break
cv2.destroyAllWindows()
但我不知道如何記錄給定的秒數並將其保存為當前目錄中的文件,
請有人指出我正確的方向
謝謝
關於時間
為什么不使用python時間函數? 特別是time.time()
看看這個關於 python 時間的答案
NB OpenCV 應該有(或有)自己的計時器,但我不能確定它是否適用於當前版本。
關於錄音/保存
看看這個另一個答案
OpenCV 允許您錄制視頻,但不能錄制音頻。 我從 JRodrigoF 遇到了這個腳本,它使用 openCV 錄制視頻,使用 pyaudio 錄制音頻。 我在一個類似的項目中使用了一段時間; 但是,我注意到有時線程會掛起並導致程序崩潰。 另一個問題是 openCV 無法以可靠的速率捕獲視頻幀,並且 ffmpeg 在重新編碼時會使視頻失真。
https://github.com/JRodrigoF/AVrecordeR
我想出了一個新的解決方案,它的記錄更可靠,質量更高。 它目前僅適用於 Windows,因為它使用pywinauto
和內置的 Windows 相機應用程序。 腳本的最后一點會進行一些錯誤檢查,通過檢查視頻名稱的時間戳來確認視頻已成功錄制。
https://gist.github.com/mjdargen/956cc968864f38bfc4e20c9798c7d670
import pywinauto
import time
import subprocess
import os
import datetime
def win_record(duration):
subprocess.run('start microsoft.windows.camera:', shell=True) # open camera app
# focus window by getting handle using title and class name
# subprocess call opens camera and gets focus, but this provides alternate way
# t, c = 'Camera', 'ApplicationFrameWindow'
# handle = pywinauto.findwindows.find_windows(title=t, class_name=c)[0]
# # get app and window
# app = pywinauto.application.Application().connect(handle=handle)
# window = app.window(handle=handle)
# window.set_focus() # set focus
time.sleep(2) # have to sleep
# take control of camera window to take video
desktop = pywinauto.Desktop(backend="uia")
cam = desktop['Camera']
# cam.print_control_identifiers()
# make sure in video mode
if cam.child_window(title="Switch to Video mode", auto_id="CaptureButton_1", control_type="Button").exists():
cam.child_window(title="Switch to Video mode", auto_id="CaptureButton_1", control_type="Button").click()
time.sleep(1)
# start then stop video
cam.child_window(title="Take Video", auto_id="CaptureButton_1", control_type="Button").click()
time.sleep(duration+2)
cam.child_window(title="Stop taking Video", auto_id="CaptureButton_1", control_type="Button").click()
# retrieve vids from camera roll and sort
dir = 'C:/Users/michael.dargenio/Pictures/Camera Roll'
all_contents = list(os.listdir(dir))
vids = [f for f in all_contents if "_Pro.mp4" in f]
vids.sort()
vid = vids[-1]
# compute time difference
vid_time = vid.replace('WIN_', '').replace('_Pro.mp4', '')
vid_time = datetime.datetime.strptime(vid_time, '%Y%m%d_%H_%M_%S')
now = datetime.datetime.now()
diff = now - vid_time
# time different greater than 2 minutes, assume something wrong & quit
if diff.seconds > 120:
quit()
subprocess.run('Taskkill /IM WindowsCamera.exe /F', shell=True) # close camera app
print('Recorded successfully!')
win_record(2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.