想法:獲取目錄中所有視頻的持續時間。
問題:我想輸出目錄中所有視頻的持續時間,但出現錯誤,這是我的代碼:
這是原始代碼https://pastebin.com/xnpfwE55
from colorama import init
from colorama import Fore
import datetime
import glob
import cv2
init()
w = input(str(Fore.GREEN "Type path to dir: ")) # path of directory
b = print(str(glob.glob(w "*"))) # Adds a directory and reads files from there
print(b)
# create video capture object
data = cv2.VideoCapture(str(b))
# count the number of frames
frames = data.get(cv2.CAP_PROP_FRAME_COUNT)
fps = int(data.get(cv2.CAP_PROP_FPS))
# calculate dusration of the video
seconds = int(frames / fps)
video_time = str(datetime.timedelta(seconds=seconds))
print("duration in seconds:", seconds)
print("video time:", video_time)
我該怎么辦?
輸出:
[gooder@GOD ffmpeg]$ python untitled2.py
Type path to dir: /home/gooder/Desktop/ffmpeg/videos/
['/home/gooder/Desktop/ffmpeg/videos/ou1t.mp4', '/home/gooder/Desktop/ffmpeg/videos/out.mp4', '/home/gooder/Desktop/ffmpeg/videos/Halloween.Kills.2021.DUB.HDRip.x264.mkv']
None
[ WARN:0@1.851] global /build/opencv/src/opencv-4.5.5/modules/videoio/src/cap_gstreamer.cpp (1127) open OpenCV | GStreamer warning: Error opening bin: no element "None"
[ WARN:0@1.851] global /build/opencv/src/opencv-4.5.5/modules/videoio/src/cap_gstreamer.cpp (862) isPipelinePlaying OpenCV | GStreamer warning: GStreamer: pipeline have not been created
[ERROR:0@2.770] global /build/opencv/src/opencv-4.5.5/modules/videoio/src/cap.cpp (164) open VIDEOIO(CV_IMAGES): raised OpenCV exception:
OpenCV(4.5.5) /build/opencv/src/opencv-4.5.5/modules/videoio/src/cap_images.cpp:253: error: (-5:Bad argument) CAP_IMAGES: can't find starting number (in the name of file): None in function 'icvExtractPattern'
Traceback (most recent call last):
File "/home/gooder/Desktop/ffmpeg/untitled2.py", line 19, in <module>
seconds = int(frames / fps)
ZeroDivisionError: float division by zero
uj5u.com熱心網友回復:
這一行似乎有一些混亂的代碼:
b = print(str(glob.glob(w "*"))) # Adds a directory and reads files from there
您在變數中輸入目錄的內容w,將該串列轉換為字串,print將該字串轉換為標準輸出,然后分配None給b,因為print將其引數寫入標準輸出(或其他一些流)并且不回傳任何內容。
評論中已經指出,print以這種方式呼叫不會在這里做你想要的。因此,第一步是擺脫它:
b = str(glob.glob(w "*")) # Adds a directory and reads files from there
print(b)
然而這還不夠,因為b它不是檔案名,而是將檔案名串列轉換為字串的結果。嘗試打開名稱為 的檔案b仍然會失敗。
glob.glob回傳一個串列,串列中的每個專案都是與給定模式匹配的檔案。您需要遍歷此串列,然后為串列中的每個專案運行一次其余代碼:
for b in glob.glob(w "*"): # Adds a directory and reads files from there
print(b)
# create video capture object
data = cv2.VideoCapture(b)
# remaining lines also indented, but omitted here for brevity
每次通過回圈時,b應該是您輸入的目錄中的檔案之一的名稱。
最后,如果cv2由于某種原因無法讀取視頻檔案的 FPS,我建議不要嘗試計算視頻的持續時間。將回圈底部的代碼替換為以下內容:
if fps == 0:
print("Could not read an FPS value, unable to calculate duration of video")
else:
# calculate duration as normal...
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/424714.html
上一篇:OpenCVBackgroundSubtractorMOG2演算法在作為我的SwiftUI應用程式的一部分執行時崩潰
