PyQt5 + Opencv 显示摄像头图像

  • 需要安装的库
  1.   PyQt5
  2.   opencv
  • 效果

  • 代码
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import cv2
import sys

class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.initTimer()

    def initTimer(self):
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.show_pic)

    def show_pic(self):
        ret, img = self.vc.read()
        if not ret:
            print('read error!\n')
            return
        cv2.flip(img, 1, img)
        cur_frame = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        heigt, width = cur_frame.shape[:2]
        pixmap = QImage(cur_frame, width, heigt, QImage.Format_RGB888)
        pixmap = QPixmap.fromImage(pixmap)
        self.lbl.setPixmap(pixmap)

    def openCamera(self):
        self.lbl.setEnabled(True)
        self.vc = cv2.VideoCapture(0)
        self.openCameraBtn.setEnabled(False)
        self.closeCameraBtn.setEnabled(True)
        self.timer.start(100)

    def closeCamera(self):
        self.vc.release()
        self.openCameraBtn.setEnabled(True)
        self.closeCameraBtn.setEnabled(False)
        self.QLable_close()
        self.timer.stop()

    def initUI(self):
        self.openCameraBtn = QPushButton('open')
        self.openCameraBtn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.openCameraBtn.clicked.connect(self.openCamera)
        self.closeCameraBtn = QPushButton('close')
        self.closeCameraBtn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.closeCameraBtn.clicked.connect(self.closeCamera)
        self.openCameraBtn.setEnabled(True)
        self.closeCameraBtn.setEnabled(False)
        self.lbl = QLabel(self)
        self.lbl.resize(200, 100)
        self.hbox = QHBoxLayout(self)
        self.hbox.addWidget(self.lbl)

        self.vbox = QVBoxLayout(self)
        self.vbox.addWidget(self.openCameraBtn)
        self.vbox.addWidget(self.closeCameraBtn)
        self.hbox.addLayout(self.vbox)

        self.setLayout(self.hbox)
        self.QLable_close()
        self.move(300, 300)
        self.setWindowTitle('OPENCV')
        self.setGeometry(300, 300, 500, 250)
        self.show()

    def QLable_close(self):
        self.lbl.setStyleSheet("background:black;")
        self.lbl.setPixmap(QPixmap())

    def start(self):
        self.timer.start(100)


if __name__=='__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

 

 
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值