如何在python中使用opencv同时播放多个视频?

时间:2017-12-21 09:56:18

标签: python opencv

嗨,大家好,我在这一点上被困住了。我想用opencv在屏幕上播放四个视频。任何人都可以帮我怎么做?假设我想同时玩

  1. first.avi
  2. second.avi
  3. third.avi
  4. fourth.avi
  5. 我指的是以下代码。它对单个avi文件非常有效。 是否有必要连接或我可以在四个不同的窗口运行?欢迎任何建议     导入cv2     导入numpy为np

    # Create a VideoCapture object and read from input file
    # If the input is the camera, pass 0 instead of the video file name
    cap = cv2.VideoCapture('first.avi')
    cap2 =cv2.VideoCapture('second.avi')
    
    if (cap.isOpened()== False): 
      print("Error opening video stream or file")
    if (cap2.isOpened()== False): 
      print("Error opening video stream or file")
    
    while(cap.isOpened()||cap2.isOpened()):
      # Capture frame-by-frame
      ret, frame = cap.read()
      ret, frame1 = cap2.read()
      if ret == True:
    
       # Display the resulting frame
        cv2.imshow('Frame',frame)
        cv2.imshow('Frame', frame1)
    
    
       # Press Q on keyboard to  exit
       if cv2.waitKey(25) & 0xFF == ord('q'):
      break
      else: 
        break
    
    
    cap.release()
    cap2.release()
    
    cv2.destroyAllWindows()
    

1 个答案:

答案 0 :(得分:6)

要播放多个视频,我们必须为每个视频使用唯一的窗口标题。这是一个示例代码,演示如何实现它。

import numpy as np
import cv2

names = ['first.avi', 'second.avi', 'third.avi', 'fourth.avi'];
window_titles = ['first', 'second', 'third', 'fourth']


cap = [cv2.VideoCapture(i) for i in names]

frames = [None] * len(names);
gray = [None] * len(names);
ret = [None] * len(names);

while True:

    for i,c in enumerate(cap):
        if c is not None:
            ret[i], frames[i] = c.read();


    for i,f in enumerate(frames):
        if ret[i] is True:
            gray[i] = cv2.cvtColor(f, cv2.COLOR_BGR2GRAY)
            cv2.imshow(window_titles[i], gray[i]);

    if cv2.waitKey(1) & 0xFF == ord('q'):
       break


for c in cap:
    if c is not None:
        c.release();

cv2.destroyAllWindows()

P.S:此代码只是一个快速而肮脏的示例,仅用于演示目的。在Ubuntu 14.04上使用python 2和OpenCV 3.2进行测试。