如何使用OpenCV,多线程,队列在python中同时运行多个视频?

时间:2018-05-11 11:02:44

标签: python multithreading python-3.x opencv multiprocessing

我正在尝试使用opencv,MultiThreading和Queues同时运行两个视频。但是,两个队列都充满了帧,但视频不是同时运行,而是一个接一个地运行。有没有什么方法可以使用多线程或多处理队列同时制作多个视频?

import os
import threading
import queue as Queue
import cv2

video_path_1 = '/home/big_buck_bunny.mp4'
video_path_2 = '/home/cup.mp4'




class MyThread (threading.Thread):
    maxRetries = 22


def __init__(self, thread_id, name, video_url, thread_lock):
    threading.Thread.__init__(self)
    self.thread_id = thread_id
    self.name = name
    self.video_url = video_url
    self.thread_lock = thread_lock
    self.Q = Queue.Queue(maxsize=128)



def run(self):
    print("Starting " + self.name)
    cap = cv2.VideoCapture(self.video_url)
    while True:
        ret, frame = cap.read()
        if ret == True:
            self.Q.put(frame)

def view(self):
    print('start view')
    while self.Q.qsize()>0:
        print('true')
        cv2.imshow('self.1', self.Q.get())
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        print('false')

def main():

thread_lock = threading.Lock()
thread1 = MyThread(1, "Thread 1", video_path_1, thread_lock)
thread2 = MyThread(2, "Thread 2", video_path_2, thread_lock)
thread1.start()
thread2.start()
cv2.imshow('1', thread2.Q.get())
cv2.imshow('23', thread1.Q.get())
print("Exiting Main Thread")

thread1.view()
thread2.view()

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:0)

正在努力同时播放同一视频的分段帧,我还没有,但这里有一些多处理,我可以同时播放多个视频。


import multiprocessing
import cv2

from concurrent.futures import ProcessPoolExecutor


def play_video(video, name):
    cap = cv2.VideoCapture(video)

    while True:
        ret, frame = cap.read()

        if frame is None:
            continue
        if ret is False:
            cv2.destroyAllWindows()
            cap.release()
            break
        cv2.imshow(name, frame)
        if cv2.waitKey(1) == ord('q'):
            cv2.destroyAllWindows()
            break
    cap.release()


videos = ["/Videos/samples/obamas.mp4", "/Videos/samples/testvideo.mp4"]

with ProcessPoolExecutor(max_workers=multiprocessing.cpu_count()) as executor:
    [executor.submit(play_video, i, str(i))for i in videos]