问题
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.
Approach 1: Adding the video in a pixmap using OpenCV/cv2 only shows the first frame of the video.
Approach 2: I have managed to get the video to play using cv2 however, it opens up in a new window.
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.
回答1:
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()
来源:https://stackoverflow.com/questions/57076105/how-to-display-a-cv2-video-inside-a-python-gui