首页 > 解决方案 > 如何在使用openCV python播放时移动视频窗口

问题描述

我一直在做一个项目,经过 6 个多小时的谷歌搜索和挖掘 openCV 书籍后,我有点难过。

import cv2
import numpy as np

cap = cv2.VideoCapture('tree.avi')
count = 0
x_pos = 0
y_pos = 0
a_x = 180
a_y = 180
frames = 60

if (cap.isOpened()== False): 
   print("Error opening video stream or file")

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

  if ret == True:
    resized = frame
    scale_percent = 200
    width = int(frame.shape[1] * scale_percent / 100)
    height = int(frame.shape[0] * scale_percent / 100)
    dim = (width, height)

    if count < 50 or count >= 55:
      cv2.moveWindow('Frame', x_pos, y_pos)
      cv2.imshow('Frame', frame)

    if count in range(50, 55):
      resized = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)
      cv2.imshow('Frame',resized)
      x_pos = x_pos + int((a_x / frames) * (count - 50))
      y_pos = y_pos + int((a_y / frames) * (count - 50))

      cv2.moveWindow('Frame', x_pos, y_pos)

      count = count + 1

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

      else: 
        break

cap.release()

cv2.destroyAllWindows()

这是我作为灵感的非常通用的代码。我想要实现的是将正在播放的视频窗口移动到屏幕上的另一个位置。我从经验中知道,简单地在给定的下添加另一个 moveWindow() 会导致窗口在应用于每个帧时在两者之间模糊。

有没有办法让它,例如,帧 1~100 在 (100,100) 并且帧 101~200 在 (200, 200) 等等?如果它是实时的,那将是最好的,但是非常感谢有关让用户在播放视频时移动窗口的任何帮助。

提前致谢。

更新 我找到了一种手动设置视频以移动某些帧的方法。但是,这似乎只适用于预设值。(ex) 帧 50 ~ 55 有没有办法实时使用一些外部输入?

标签: pythonopencv

解决方案


我想要实现的是将正在播放的视频窗口移动到屏幕上的另一个位置

如果上述声明是您的主要关注点,请使用FileVideoStream.

正如我在之前的回答中提到的:

VideoCapture 管道在读取和解码下一帧上花费的时间最多。在读取、解码和返回下一帧时,OpenCV 应用程序被完全阻塞。

这意味着当您移动视频时,应用程序被阻止,因为管道无法解码下一帧。

例如:下面是显示框架,同时手动拖动窗口。

import cv2
import time
from imutils.video import FileVideoStream

vs = FileVideoStream('result.mp4').start()
time.sleep(0.2)

while True:
    frame = vs.read()

    cv2.imshow("out", frame)
    if cv2.waitKey(25) & 0xFF == ord('q'):
        break

vs.stop()
cv2.destroyAllWindows()

现在,如果我们将代码与您的一些变量合并:

import cv2
import time
from imutils.video import FileVideoStream

vs = FileVideoStream('result.mp4').start()
time.sleep(0.2)

count = 0
x_pos = 0
y_pos = 0
a_x = 180
a_y = 180
frames = 60


while True:
    frame = vs.read()

    scale_percent = 200
    width = int(frame.shape[1] * scale_percent / 100)
    height = int(frame.shape[0] * scale_percent / 100)
    dim = (width, height)

    if count in range(0, 55):
        resized = cv2.resize(frame, dim, interpolation=cv2.INTER_AREA)
        cv2.imshow('Frame', resized)
        x_pos = x_pos + int((a_x / frames) * (count - 50))
        y_pos = y_pos + int((a_y / frames) * (count - 50))

        cv2.moveWindow('Frame', x_pos, y_pos)

    cv2.imshow("out", frame)
    if cv2.waitKey(25) & 0xFF == ord('q'):
        break

vs.stop()
cv2.destroyAllWindows()

您将看到两个窗口,一个正在显示,第二个窗口正在从窗口的右侧位置移动到左侧位置。

在此处输入图像描述


推荐阅读