環境:python3.8
video_path為待轉換視頻的路徑,pic_path為輸出圖像的路徑,輸出的圖像統一保存在pic_path下面與相應視頻名相同的文件夾下面。
代碼如下:
# coding=utf-8 import cv2 import os import threading from threading import Lock, Thread video_path = "E:/BaiduNetdiskDownload/video/"; pic_path = "C:/Users/xxx/Desktop/pic2/"; filelist = os.listdir(video_path) # 返回指定的文件夾下包含的文件或文件夾名字的列表,這個列表按字母順序排序。 def video2pic(filename): # print(filename) cnt = 0 dnt = 0 if os.path.exists(pic_path + str(filename)): pass else: os.mkdir(pic_path + str(filename)) cap = cv2.VideoCapture(video_path + str(filename)) # 讀入視頻 while True: # get a frame ret, image = cap.read() if image is None: break # show a frame w = image.shape[1] h = image.shape[0] if (cnt % 20) == 0: cv2.imencode('.jpg', image)[1].tofile(pic_path + str(filename) + '/' + str(dnt) + '.jpg') # cv2.imwrite('C:/Users/JiangHuiQi/Desktop/pic/' + str(filename) + '/' + str(dnt) + '.jpg', image) #含中文路徑,不可行 print(pic_path + str(filename) + '/' + str(dnt) + '.jpg') dnt = dnt + 1 # cv2.namedWindow('sliding_slice',0) # cv2.imshow('image', image) # cv2.waitKey(1000) cnt = cnt + 1 if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() if __name__ == '__main__': for filename in filelist: threading.Thread(target=video2pic, args=(filename,)).start()