目录下的所有mp4转图片
可以选择roi进行裁剪保存。
import datetime
import os
import time
import cv2
import numpy as np
keys = [['0.mp4', '0'], ['1.mp4', '1'], ['2.mp4', '2'], ['3.mp4', '3'], ['4.mp4', '4'], ['5.mp4', '5'], ['6.mp4', '6'], ['7.mp4', '7'], ['8.mp4', '8'], ['9.mp4', '9'], ['10.mp4', '10'], ['11.mp4', '11'], ['12.mp4', '12'], ['33.mp4', '33']]
keys = [['0.mp4', '0'], ['2.mp4', '2']]
keys = [['11.mp4', 35,200],['9.mp4', 35,256],['6.mp4', 35,131],['4.mp4', 35,256],['2.mp4', 35,256]]
keys = []
tongji = 1
keys_dict = {}
for row in keys:
keys_dict[row[0]] = row[1:]
def mp42pic():
dir_a=r'C:\Vids'
roi_files = ['%s/%s' % (i[0].replace("\\", "/"), j) for i in os.walk(dir_a) for j in i[-1] if
j.endswith(('.mp4', '.data')) and j.startswith('Res')]
save_to=r'D:\data/1216/'
for cam_id in [0,1]:
save_to = save_to +str(cam_id)
for index, path in enumerate(roi_files):
cap = cv2.VideoCapture(path)
print(index,path)
file_name=os.path.basename(path)
if len(keys_dict) and file_name not in keys_dict:
continue
frame_index = 0
img_dir = f"{save_to}/{file_name[:-4]}"
os.makedirs(img_dir, exist_ok=True)
while True:
ret_val, img0 = cap.read() #
frame_index+=1
if img0 is None:
cap.release()
# cv2.destroyAllWindows()
break
if len(keys_dict) and frame_index <keys_dict[file_name][0]:
continue
if len(keys_dict) and frame_index > keys_dict[file_name][1]:
break
if cam_id == 0:
img0 = img0[:1080]
else:
img0 = img0[1080:]
img_file = f"{img_dir}/{frame_index}.jpg"
cv2.imwrite(img_file, img0)
if __name__ == '__main__':
# mp42pic()
dir_a=r'D:\project'
files = ['%s/%s' % (i[0].replace("\\", "/"), j) for i in os.walk(dir_a) for j in i[-1] if j.endswith(('.mp4', 'jpg', 'png', 'jpeg', 'JPG'))]
for index, path in enumerate(files):
date = time.strftime("%m%d%H%M")
cap = cv2.VideoCapture(path)
file_name = os.path.basename(path)
frame_index = 0
save_to=r'D:\project'
img_dir = f"{save_to}/{file_name[:-4]}"
os.makedirs(img_dir, exist_ok=True)
input_box=None
while True:
ret_val, img0 = cap.read() #
frame_index += 1
if img0 is None:
cap.release()
# cv2.destroyAllWindows()
break
# if input_box is None:
# print("pelease select roi")
# roi = cv2.selectROI(windowName="roi", img=img0, showCrosshair=True, fromCenter=False)
# x, y, w, h = roi
#
# input_box = np.array([x, y, x + w, y + h])
# cv2.destroyAllWindows()
#
# img_crop = img0[input_box[1]:input_box[3], input_box[0]:input_box[2]]
cv2.imshow('img',img0)
cv2.waitKey(1)
img_file = f"{img_dir}/{date}_{frame_index}.jpg"
cv2.imwrite(img_file, img0)