有一个untitled.ui文件,请写一个项目代码实现引用这个ui文件,基于opencv实现点击self.pushButton打开搜索到的相机列表中,与self.spinBox数据对应的相机打开再将视频显示在self.label,点击self.pushButton_2保存当前帧到当前文件目录并显示在self.label_2
时间: 2023-06-26 20:04:27 浏览: 119
可以参考如下代码实现:
```
import cv2
import os
from PyQt5 import QtCore, QtGui, QtWidgets, uic
# 加载 UI 文件
Ui_MainWindow, _ = uic.loadUiType('untitled.ui')
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
# 点击 self.pushButton 按钮,打开相机并显示在 self.label
self.pushButton.clicked.connect(self.start_camera)
# 点击 self.pushButton_2 按钮,保存当前帧并显示在 self.label_2
self.pushButton_2.clicked.connect(self.save_frame)
# 初始化相机列表
self.camera_list = []
for i in range(10):
camera = cv2.VideoCapture(i)
if camera.isOpened():
self.camera_list.append(camera)
self.comboBox.addItem(str(i))
else:
break
def start_camera(self):
# 获取选中的相机编号
camera_index = int(self.comboBox.currentText())
# 获取帧率
fps = self.spinBox.value()
# 获取视频宽度和高度
width = int(self.lineEdit.text())
height = int(self.lineEdit_2.text())
# 打开相机
camera = self.camera_list[camera_index]
# 设置相机参数
camera.set(cv2.CAP_PROP_FRAME_WIDTH, width)
camera.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
camera.set(cv2.CAP_PROP_FPS, fps)
# 循环读取视频帧并显示在 self.label
while True:
ret, frame = camera.read()
if ret:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
image = QtGui.QImage(frame.data, frame.shape[1], frame.shape[0], QtGui.QImage.Format_RGB888)
pixmap = QtGui.QPixmap.fromImage(image)
self.label.setPixmap(pixmap)
QtWidgets.QApplication.processEvents()
else:
break
def save_frame(self):
# 获取当前帧
pixmap = self.label.pixmap()
if pixmap is None:
return
frame = pixmap.toImage().convertToFormat(QtGui.QImage.Format_RGB888)
width = frame.width()
height = frame.height()
# 保存当前帧到当前文件目录
filename, _ = QtWidgets.QFileDialog.getSaveFileName(self, 'Save Frame', os.getcwd(), 'Images (*.png *.xpm *.jpg)')
if filename:
frame.save(filename)
# 显示当前帧在 self.label_2
pixmap = QtGui.QPixmap.fromImage(frame)
pixmap = pixmap.scaled(self.label_2.width(), self.label_2.height(), QtCore.Qt.KeepAspectRatio)
self.label_2.setPixmap(pixmap)
if __name__ == '__main__':
app = QtWidgets.QApplication([])
window = MainWindow()
window.show()
app.exec_()
```
需要注意的是,在使用 OpenCV 打开相机时,需要先读取一帧视频才能获取到相机的参数,否则设置参数可能会无效。此外,需要使用 `QtCore.Qt.KeepAspectRatio` 参数来保持保存的图像的宽高比与原图相同。
阅读全文