使用python3.4+的import concurrent.futures
首先定義函數處理函數,例如視頻提幀的函數如下:
def function(json_path):
key_frame_list = []
with open(json_path) as fr_json:
data = json.load(fr_json)
video_filename = video_path + data['videoid']for i in range(len(data['shots'])):
for target in data['shots'][i]['targets']:
if target['category'] == 0:result_path = extract_result_path + data['videoid']
if not os.path.exists(result_path):
os.mkdir(result_path)
key_frame_list.append(data['shots'][i]['keyframe'])
key_frame_list = list(set(key_frame_list))
key_frame_list.sort()
cap = cv2.VideoCapture(video_filename)
for frame_num in key_frame_list:
cap.set(1,frame_num)
rval, frame = cap.read()
try:
# frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# img = Image.fromarray(frame)
# cv2.imshow('Frame',frame)
cv2.imwrite(result_path+'/'+str(frame_num)+'.jpg',frame)ch = cv2.waitKey(5)
if ch == 27:
break
except:
passcap.release()
然後用多進程調用使用的函數。注意多進程的衝突問題,也就是隻能多對多或者一對多(如果一個文件生成多個文件,需要在function函數中進行判斷),不能多對一(如果多個文件同時寫入一個文件的話會產生衝突)
最後是函數調用,先將需要處理的文件放到List當中,然後調用function函數
json_file=os.listdir(json_path)
json_filename_list=[]
# print(json_file)
# for json_filename in json_file:
# json_all_filename=os.path.join(json_path,json_filename)
# json_filename_list.append(json_all_filename)for json_filename in json_file:
json_all_filename = json_path+json_filename
json_filename_list.append(json_all_filename)
# print(json_all_filename)
# print(type(json_all_filename))
# json_all_filename=str(json_all_filename)
# print(json_all_filename)
#function(json_all_filename)#not use multiThreadwith concurrent.futures.ProcessPoolExecutor() as executor:
for image_file,result in zip(json_filename_list,executor.map(function,json_filename_list)):
print("finish one video!!")