OpenCVpyqt5视频抽帧显示代码
时间: 2023-06-13 08:04:38 浏览: 54
下面是一个简单的示例代码,演示了如何使用OpenCV和PyQt5从视频中提取帧并在GUI中显示它们:
```python
import sys
import cv2
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow, QFileDialog
from PyQt5.QtCore import Qt, QTimer
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.label = QLabel(self)
self.setCentralWidget(self.label)
# 打开视频文件对话框
file_dialog = QFileDialog(self)
file_dialog.setNameFilter("Videos (*.mp4 *.avi)")
if file_dialog.exec_() == QFileDialog.Accepted:
self.file_path = file_dialog.selectedFiles()[0]
else:
sys.exit()
self.cap = cv2.VideoCapture(self.file_path)
self.timer = QTimer(self)
self.timer.timeout.connect(self.update_frame)
self.timer.start(1000 // self.cap.get(cv2.CAP_PROP_FPS))
def update_frame(self):
ret, frame = self.cap.read()
if ret:
# 转换为RGB格式
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# 将帧转换为QImage格式
h, w, c = frame.shape
q_img = QImage(frame.data, w, h, c * w, QImage.Format_RGB888)
# 将QImage显示在标签上
self.label.setPixmap(QPixmap.fromImage(q_img))
else:
self.timer.stop()
self.cap.release()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
这个示例程序打开一个对话框,让用户选择要打开的视频文件。然后它使用OpenCV打开视频文件,并使用PyQt5定时器从视频中提取帧并将它们显示在标签上。