如果你在文件夾里有很多視頻,并且文件夾里還有文件夾,文件夾里的文件夾也有視頻,怎么能逐個讀取并且保存。。所以我寫了個代碼用了os,walk,這個可以遍歷所有文件夾里的文件和文件夾
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
import os import cv2 cut_frame = 250 # 多少幀截一次,自己設置就行 save_path = "C:\文獻與資料\手持紅外\圖片" for root, dirs, files in os.walk(r "C:\文獻與資料\手持紅外" ): # 這里就填文件夾目錄就可以了 for file in files: # 獲取文件路徑 if ( '.mp4' in file ): path = os.path.join(root, file ) video = cv2.VideoCapture(path) video_fps = int (video.get(cv2.CAP_PROP_FPS)) print (video_fps) current_frame = 0 while ( True ): ret, image = video.read() current_frame = current_frame + 1 if ret is False : video.release() break if current_frame % cut_frame = = 0 : # cv2.imwrite(save_path + '/' + file[:-4] + str(current_frame) + '.jpg', # image) # file[:-4]是去掉了".mp4"后綴名,這里我的命名格式是,視頻文件名+當前幀數+.jpg,使用imwrite就不能有中文路徑和中文文件名 cv2.imencode( '.jpg' , image)[ 1 ].tofile(save_path + '/' + file [: - 4 ] + str (current_frame) + '.jpg' ) #使用imencode就可以整個路徑中可以包括中文,文件名也可以是中文 print ( '正在保存' + file + save_path + '/' + file [: - 4 ] + str (current_frame)) |
ps:下面看下python 遍歷文件夾
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import os # 遍歷文件夾 def walkFile( file ): for root, dirs, files in os.walk( file ): # root 表示當前正在訪問的文件夾路徑 # dirs 表示該文件夾下的子目錄名list # files 表示該文件夾下的文件list # 遍歷文件 for f in files: print (os.path.join(root, f)) # 遍歷所有的文件夾 for d in dirs: print (os.path.join(root, d)) def main(): walkFile( "f:/ostest/" ) if __name__ = = '__main__' : main() |
總結
以上所述是小編給大家介紹的python使用openCV遍歷文件夾里所有視頻文件并保存成圖片,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
原文鏈接:https://blog.csdn.net/weixin_43446161/article/details/103929236