如何在python中使用ThreadPoolExecutor来实现并行化?

2 人关注

我无法运行 线程池执行器(线程池执行器(ThreadPoolExecutor in python & openCV

this is my code

def main(video_path,visualization,count):
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        print("Error opening video stream or file")
    while cap.isOpened():
        count = count + 1
        ret, frame = cap.read()
        raw_frame = None
        if ret:
            raw_frame = frame.copy()
        if ret:
            frame = resize_img(frame, 50)
            if count % FREQUENCY == 0:
                face_locations = hogFaceDetector(frame, 0)
                if len(face_locations) > 0:
                    sorted_detections_distances = calculate_face_distance(face_locations, frame, faces_encodings)
                    if sorted_detections_distances[0][1] < TOLERANCE_THRES:
                        print(str(sorted_detections_distances[0][0]))
                    if visualization == True:
                        for faceRect in face_locations:
                            x1 = faceRect.left()
                            y1 = faceRect.top()
                            x2 = faceRect.right()
                            y2 = faceRect.bottom()
                            cv2.line(frame, (x1, y2), (x1, y1), (0, 0, 255), 4)
                            cv2.line(frame, (x1, y2), (x2, y2), (0, 0, 255), 4)
                            cv2.line(frame, (x2, y1), (x2, y2), (0, 0, 255), 4)
                            cv2.line(frame, (x1, y1), (x2, y1), (0, 0, 255), 4)
                            cv2.putText(frame, str(sorted_detections_distances[0][0]), (x1, y1),
                                        cv2.FONT_HERSHEY_SIMPLEX, 1,
                                        (255, 0, 0), 3)
                            cv2.imshow('Frame', frame)
            if visualization == True:
                cv2.imshow('raw_frame', raw_frame)
            if cv2.waitKey(25) & 0xFF == ord('q'):
                break
        else:
            break
    cap.release()
    cv2.destroyAllWindows()
if __name__ == '__main__':
    visualization = False
    count = 0
    with open('faces_encodings.pickle', 'rb') as handle:
        faces_encodings = pickle.load(handle)
    with ThreadPoolExecutor(max_workers=3) as executor:
        process1 = executor.submit(main, ("stock.mp4",visualization,count))
        process2 = executor.submit(main, ("stock2.mp4",visualization,count))
        process3 = executor.submit(main, ("stock3.mp4",visualization,count))

我能够使用旧的多处理技术达到某种程度的多处理效果

这是在工作

p1 = multiprocessing.Process(target=main, args=("stock.mp4",visualization,count))
p2 = multiprocessing.Process(target=main, args=("stock2.mp4",visualization,count))
p3 = multiprocessing.Process(target=main, args=("stock3.mp4",visualization,count))
p1.start()
p2.start()
p3.start()
p1.join()