python pyqt5調用攝像頭實時顯示

功能;

pyqt5實現一個界面,上面設置一個畫面,一個按鈕

通過按鈕文字和狀態切換來控制攝像頭的開啟與關閉

完整代碼如下:

python 复制代码
import sys
import cv2
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QPushButton, QVBoxLayout, QWidget


class CameraThread(QThread):
    change_pixmap = pyqtSignal(QImage)
    stopped = pyqtSignal()  # 通知主線程線程已停止

    def run(self):
        cap = cv2.VideoCapture(0)
        if not cap.isOpened():
            self.stopped.emit()
            return

        while not self.isInterruptionRequested():
            ret, frame = cap.read()
            if not ret:
                break

            # ✅ 水平翻轉鏡像(左右翻轉)
            frame = cv2.flip(frame, 1)

            rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            h, w, ch = rgb_frame.shape
            bytes_per_line = ch * w
            qt_image = QImage(rgb_frame.data, w, h, bytes_per_line, QImage.Format_RGB888)
            self.change_pixmap.emit(qt_image.copy())
            self.msleep(10)

        cap.release()
        self.stopped.emit()

    def stop(self):
        self.requestInterruption()
        self.wait()


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("攝像頭實時顯示")
        self.resize(640, 480)

        # 圖像顯示標籤
        self.image_label = QLabel("攝像頭畫面")
        self.image_label.setScaledContents(True)
        self.image_label.setStyleSheet("border: 1px solid #888;")
        self.image_label.setAlignment(Qt.AlignCenter)  # 文字居中

        # ✅ 只有一個按鈕
        self.toggle_btn = QPushButton("啟動攝像頭")
        self.toggle_btn.setStyleSheet("""
            QPushButton {
                background-color: #4CAF50;
                color: white;
                font-size: 14px;
                font-weight: bold;
                padding: 10px;
                border-radius: 5px;
            }
            QPushButton:hover {
                background-color: #45a049;
            }
            QPushButton:disabled {
                background-color: #cccccc;
            }
        """)
        self.toggle_btn.setFixedHeight(40)

        # 佈局
        layout = QVBoxLayout()
        layout.addWidget(self.image_label)
        layout.addWidget(self.toggle_btn)

        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

        # 攝像頭線程
        self.camera_thread = CameraThread(self)
        self.camera_thread.change_pixmap.connect(self.update_image)
        self.camera_thread.stopped.connect(self.on_camera_stopped)

        # ✅ 按鈕點擊切換狀態
        self.toggle_btn.clicked.connect(self.toggle_camera)

    def toggle_camera(self):
        """切換攝像頭狀態:啟動 / 停止"""
        if not self.camera_thread.isRunning():
            # 啟動攝像頭
            self.image_label.setText("加載中...")
            self.toggle_btn.setEnabled(False)  # 短暫禁用防止重複點擊
            self.camera_thread.start()
            # 線程啟動後更新按鈕狀態
            self.toggle_btn.setText("停止攝像頭")
            self.toggle_btn.setStyleSheet("""
                QPushButton {
                    background-color: #f44336;
                    color: white;
                    font-size: 14px;
                    font-weight: bold;
                    padding: 10px;
                    border-radius: 5px;
                }
                QPushButton:hover {
                    background-color: #da190b;
                }
            """)
            self.toggle_btn.setEnabled(True)
        else:
            # 停止攝像頭
            self.camera_thread.stop()

    def update_image(self, qt_image):
        """更新畫面"""
        self.image_label.setPixmap(QPixmap.fromImage(qt_image))

    def on_camera_stopped(self):
        """攝像頭停止後的回調"""
        self.image_label.clear()
        self.image_label.setText("攝像頭已停止")
        # ✅ 恢復按鈕為「啟動」狀態
        self.toggle_btn.setText("啟動攝像頭")
        self.toggle_btn.setStyleSheet("""
            QPushButton {
                background-color: #4CAF50;
                color: white;
                font-size: 14px;
                font-weight: bold;
                padding: 10px;
                border-radius: 5px;
            }
            QPushButton:hover {
                background-color: #45a049;
            }
        """)

    def closeEvent(self, event):
        """窗口關閉時確保線程停止"""
        if self.camera_thread.isRunning():
            self.camera_thread.stop()
        super().closeEvent(event)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
相关推荐
2601_962078191 小时前
Python中calendar.weekday用法
python·编程技巧·calendar·日期处理·weekday
2601_962218611 小时前
万象生鲜系统业财一体化底层打通技术自动生成经营账单
大数据·数据库·人工智能·python·算法
2601_966949651 小时前
为什么量化策略需要大量历史股票数据?从回测可信度理解数据规模
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
niucloud-admin1 小时前
JAVA V6 多商户商城 开发文档——插件目录结构
java·开发语言
2601_962885721 小时前
如何用 Python 扫描 A 股跳空缺口并统计缺口回补概率?
java·前端·python
滕州市燕猫虎计算机科技工作室个体工商户1 小时前
Java锁
java·开发语言
李高钢2 小时前
Python FastAPI 框架入门:从零搭建你的第一个高性能 API 服务
数据库·python·fastapi
多加点辣也没关系2 小时前
JavaScript|第31章:表单与控件
开发语言·javascript·ecmascript
菜鸟~noob2332 小时前
【电子战】 第09篇:阵列信号处理——波束形成、MVDR、MUSIC【含matlab代码】
开发语言·matlab·信号处理
ocean21032 小时前
2025-2026年Python面试高频知识点洞察
开发语言·python·面试·python八股文