用opencv和pyqt5做一个录像机
import sys
import cv2
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QPushButton, QLabel
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import Qt, QTimer, QDateTime
class VideoPlayer(QWidget):
def __init__(self):
super().__init__()
self.video_label = QLabel(self)
self.record_button = QPushButton('开始录制', self)
self.stop_button = QPushButton('停止录制', self)
layout = QVBoxLayout()
layout.addWidget(self.video_label)
layout.addWidget(self.record_button)
layout.addWidget(self.stop_button)
self.setLayout(layout)
self.record_button.clicked.connect(self.start_recording)
self.stop_button.clicked.connect(self.stop_recording)
self.camera = cv2.VideoCapture(0)
self.recording = False
self.video_writer = None
self.timer = QTimer()
self.timer.timeout.connect(self.display_video_frame)
self.timer.start(30)
def display_video_frame(self):
_, frame = self.camera.read()
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
image = QImage(frame_rgb.data, frame_rgb.shape[1], frame_rgb.shape[0], QImage.Format_RGB888)
pixmap = QPixmap.fromImage(image)
scaled_pixmap = pixmap.scaled(self.video_label.size() , Qt.KeepAspectRatio)
self.video_label.setPixmap(scaled_pixmap)
if self.recording:
self.video_writer.write(frame)
def start_recording(self):
self.record_button.setEnabled(False)
self.stop_button.setEnabled(True)
self.recording = True
# 根据当前时间创建视频文件名
current_time = QDateTime.currentDateTime().toString('yyyy-MM-dd_hh-mm-ss')
output_filename = f'output_{current_time}.avi'
# 创建视频编写器
codec = cv2.VideoWriter_fourcc(*'XVID')
fps = 20.0
frame_size = (640, 480)
self.video_writer = cv2.VideoWriter(output_filename, codec, fps, frame_size)
def stop_recording(self):
self.record_button.setEnabled(True)
self.stop_button.setEnabled(False)
self.recording = False
self.video_writer.release()
def closeEvent(self, event):
self.camera.release()
event.accept()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = QMainWindow()
video_player = VideoPlayer()
window.setCentralWidget(video_player)
window.resize(800, 600) # 设置窗口大小
window.show()
sys.exit(app.exec_())