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

2024-05-23 23:26:44 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,伙计们,我被困在这一点上了。我想用opencv在屏幕上播放四个视频。有人能帮我怎么做吗?假设我想同时演奏

  1. 第一.avi
  2. 第二.avi
  3. 第三.avi
  4. 第四.avi

我指的是下面的代码。它对单个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()

Tags: thefalsereadinputifvideocv2frame
1条回答
网友
1楼 · 发布于 2024-05-23 23:26:44

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

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进行了测试。

相关问题 更多 >