使用pycharm,pyqt6编写一个测试程序,程序的基本功能是通过单击一个按钮,调用摄像头。通过单击另一个按钮,关闭摄像头。出现如上报错。只需要将
QImage.Format_RGB888改为QImage.Format.Format_RGB888
就正常运行了。
程序文档如下:
from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget
from PyQt6.QtCore import Qt
import sys
import cv2
from PyQt6.QtGui import QImage, QPixmap
from PyQt6.QtCore import QTimer
class CameraWindow(QMainWindow):
def __init__(self):
super().__init__()
self.cap = cv2.VideoCapture(0) # 打开默认摄像头
self.timer = QTimer(self)
self.timer.timeout.connect(self.update_frame)
self.is_camera_active = False
self.init_ui()
def init_ui(self):
self.setWindowTitle('Camera App')
self.setGeometry(100, 100, 640, 480)
layout = QVBoxLayout()
self.start_button = QPushButton('Start Camera')
self.start_button.clicked.connect(self.start_camera)
self.stop_button = QPushButton('Stop Camera')
self.stop_button.clicked.connect(self.stop_camera)
self.stop_button.setEnabled(False)
self.image_label = QLabel()
layout.addWidget(self.start_button)
layout.addWidget(self.stop_button)
layout.addWidget(self.image_label)
container = QWidget()
container.setLayout(layout)
self.setCentralWidget(container)
def start_camera(self):
self.is_camera_active = True
self.timer.start(30) # 设置定时器,每隔30ms捕获一帧
self.start_button.setEnabled(False)
self.stop_button.setEnabled(True)
def stop_camera(self):
self.is_camera_active = False
self.timer.stop()
self.start_button.setEnabled(True)
self.stop_button.setEnabled(False)
def update_frame(self):
if self.is_camera_active:
ret, frame = self.cap.read()
if ret:
rgb_image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
h, w, ch = rgb_image.shape
bytes_per_line = ch * w
q_image = QImage(rgb_image.data, w, h, bytes_per_line, QImage.Format.Format_RGB888)
p = QPixmap.fromImage(q_image)
self.image_label.setPixmap(p.scaled(640, 480, Qt.AspectRatioMode.KeepAspectRatio))
def closeEvent(self, event):
self.cap.release()
super().closeEvent(event)
from PyQt6.QtWidgets import QLabel
app = QApplication(sys.argv)
window = CameraWindow()
window.show()
sys.exit(app.exec())