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_())
相关推荐
Wang's Blog9 分钟前
Java 项目实战: 外卖平台优化-YApi接口管理平台与文档导入导出
java·开发语言·yapi
lzqrzpt12 分钟前
临沂LED驱动电源工程选型标准与工艺对比解析
python·单片机·嵌入式硬件·物联网
专业程序开发源13 分钟前
django新闻推荐系统70655-计算机课程设计、毕业设计
java·javascript·spring boot·后端·python·django·课程设计
jimy115 分钟前
基类没有虚析构函数,基类指针删除派生类对象,行为是未定义的
开发语言·c++
蒲公英eric23 分钟前
人口增长问题:从 Malthus 到 Logistic 的建模之旅
人工智能·python·数学建模·人口增长问题
全栈练习生24 分钟前
大模型原理之 Softmax
python·ai
迅猛龙办公室24 分钟前
python获取星期字符串
开发语言·python
打工仔折腾 AI25 分钟前
把 AI Agent 托管到家里电脑:UU远程端口映射与CLI实测记录
人工智能·后端·python·langchain·电脑·ai agent 实战
vx_Biye_Design1 小时前
springboot小学生英语学习APP62773-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·python·学习·课程设计
打工仔折腾 AI1 小时前
用UU远程把家里电脑变成AI Agent常驻服务器:CLI、端口映射与代理实测
运维·服务器·人工智能·后端·python·电脑·ai agent 实战