简体   繁体   English

无法在 OpenCV 中关闭视频窗口

[英]Cannot Close Video Window in OpenCV

I would like to play a video in openCV using python and close that window at any time, but it is not working.我想使用 python 在 openCV 中播放视频并随时关闭该窗口,但它不起作用。

import numpy as np
import cv2

fileName='test.mp4'  # change the file name if needed

cap = cv2.VideoCapture(fileName)   # load the video

while(cap.isOpened()):
    # play the video by reading frame by frame
    ret, frame = cap.read()
    if ret==True:
        # optional: do some image processing here 

        cv2.imshow('frame',frame)              # show the video
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

cv2.waitKey(1)
cv2.destroyAllWindows()
cv2.waitKey(1)

The window opens and starts playing the video, but I cannot close the window.窗口打开并开始播放视频,但我无法关闭窗口。

You can use cv2.getWindowProperty('window-name', index) to detect if the window is closed.您可以使用cv2.getWindowProperty('window-name', index)来检测窗口是否关闭。 I'm not totally sure about the index but this worked for me:我不完全确定索引,但这对我有用:

import cv2

filename = 'test.mp4'
cam = cv2.VideoCapture(filename)

while True:
    ret, frame = cam.read()
    if not ret:
        break
    cv2.imshow('asd', frame)
    cv2.waitKey(1)
    if cv2.getWindowProperty('asd', 4) < 1:
        break

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM