没有在python GUI中播放任何视频文件

时间:2016-06-09 09:32:54

标签: python opencv tkinter

以下代码用于打开filedialogue。但它不播放任何视频文件。

它只返回视频文件地址但不播放文件。

from Tkinter import Tk
import cv2
import numpy as np
from tkFileDialog import askopenfilename

Tk().withdraw()
filename = askopenfilename() 

print(filename)
cap = cv2.VideoCapture(filename)
print(cap)
print(cap.isOpened())

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

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

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

cap.release()
cv2.destroyAllWindows()

2 个答案:

答案 0 :(得分:1)

使用Tkinter和OpenCV,这段代码对我有用。

如果我使用.avi和.mpg格式,.mov和.mp4只是打印文件路径。

from Tkinter import Tk
from tkFileDialog import askopenfilename

import cv2

Tk().withdraw()
filename = askopenfilename()
print(filename)

cap = cv2.VideoCapture(filename)

while cap.isOpened():
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('frame', gray)
    if cv2.waitKey(250) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

可替换地, 您可以使用PyQt4在Python GUI中播放视频(Qt跨平台GUI的Python绑定)。

以下是一个简单的例子:

from PyQt4 import QtGui
from PyQt4 import phonon


class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.resize(960, 540)
        layout = QtGui.QGridLayout(self)
        player = phonon.Phonon.VideoPlayer(self)
        filename = QtGui.QFileDialog.getOpenFileName()
        media = phonon.Phonon.MediaSource(filename)
        player.load(media)
        player.play()
        layout.addWidget(player)


if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    win = Window()
    win.show()
    sys.exit(app.exec_())

答案 1 :(得分:0)

我认为问题在于你的帧速率。你把它设置为0.001秒,所以也许你的视频结果非常快。尝试增加它:

from tkinter import Tk
from tkinter import filedialog
import cv2

Tk().withdraw()
filename = filedialog.askopenfilename() 
print(filename)

cap = cv2.VideoCapture(filename)
while(cap.isOpened()):
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    cv2.imshow('frame',gray)
    if cv2.waitKey(250) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()