如何在python GUI中显示cv2视频? [英] How to display a cv2 video inside a python GUI?
问题描述
我正在使用Python/PyQt5创建一个GUI,该GUI应该在同一窗口中显示视频以及其他小部件.我尝试了不同的方法来解决此问题,但Stil似乎无法使其正常工作.
I'm creating a GUI using Python/PyQt5 which should display a video along with other widgets in the same window. I've tried different approaches to this problem but stil can't seem to get it to work.
方法1:使用OpenCV/cv2在像素图中添加视频只会显示视频的第一帧.
Approach 1: Adding the video in a pixmap using OpenCV/cv2 only shows the first frame of the video.
方法2:我设法用cv2播放了视频,但是它在新窗口中打开.
Approach 2: I have managed to get the video to play using cv2 however, it opens up in a new window.
方法3:我也尝试使用QVideoWidget,但显示空白屏幕,并且视频无法播放.
Approach 3: I also tried using QVideoWidget, but a blank screen shows and the video does not play.
# only shows an image from the video, but in the correct place
cap = cv2.VideoCapture('video.mov')
ret, frame = cap.read()
if ret:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
img = QImage(frame, frame.shape[1], frame.shape[0], QImage.Format_RGB888)
pix = QPixmap.fromImage(img)
pix = pix.scaled(600, 400, Qt.KeepAspectRatio, Qt.SmoothTransformation)
self.ui.label_7.setPixmap(pix)
# opens new window
cap = cv2.VideoCapture('video.mov')
while (cap.isOpened()):
ret, frame = cap.read()
self.ui.frame = cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
# shows a blank screen
self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)
videoWidget = self.ui.vid_widget
self.mediaPlayer.setVideoOutput(videoWidget)
self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile('video.mov')))
在如何使视频在另一个窗口小部件中/在同一窗口中播放的任何帮助将不胜感激.
Any help on how to get the video play inside another widget/in the same window would be really appreciated.
推荐答案
在 while
循环中,您需要将 frame
转换为 QPixmap
同样,类似于您在上面所做的操作,然后更新 ui
:
Inside the while
loop, you need to convert frame
into a QPixmap
again, similar to what you did above, and then update ui
:
cap = cv2.VideoCapture('video.mov')
while (cap.isOpened()):
ret, frame = cap.read()
if not ret:
break
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
img = QImage(frame, frame.shape[1], frame.shape[0], QImage.Format_RGB888)
pix = QPixmap.fromImage(img)
pix = pix.scaled(600, 400, Qt.KeepAspectRatio, Qt.SmoothTransformation)
self.ui.label_7.setPixmap(pix)
self.ui.frame = pix # or img depending what `ui.frame` needs
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
这篇关于如何在python GUI中显示cv2视频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!