python+opencv+pyqt5控制攝像頭在Qlabel上顯示


import cv2
import numpy as numpy
from PIL import *
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from threading import *
#一大堆引用,亂七八糟,都要用到
#需要繼承QWidget,初始化窗體
class initform(QWidget):
    def __init__(self):
        super().__init__()
        return self.initUI()

    def initUI(self):
        #設置窗口左上邊距,寬度高度
        self.setGeometry(300,300,800,600)
        #設置窗體標題
        self.setWindowTitle("myui")
        # self.layout=QGridLayout(self)
        #設置lable文本內容
        self.lable=QLabel("iamlable",self)
        # self.lable.move(0,0)
        #label的對其方式,為左上對其
        self.lable.setAlignment(Qt.AlignTop)
        self.lable.setAlignment(Qt.AlignLeft)
        #設置lable的大小
        self.lable.setGeometry(0,0,800,600)
        # self.lable.size(800,600)
        self.lable.setScaledContents(True)
        # self.lable.setWordWrap(True)
        # self.lable.setFixedSize(800,600)
        # self.lable.setFixedWidth(800)
        # self.lable.setFixedHeight(600)
        #lable加入窗體
        # self.layout.addWidget(self.lable)
        
        # self.lable.setAutoFillBackground(True)
        # self.lable.alignment(Qt.AlignCenter)
        # pe=QPalette()
        # pe.setColor(QPalette.windowText,Qt.blue)
        # pe.setColor(QPalette.window,Qt.red)
        # self.lable.setPalette(pe)
        # self.lable.move(0,0)
        #讀取圖片
        self.show()
        
    def SetPic(self,img):
        # self.lable.setPixmap(QPixmap(imgPath))
        #圖片顯示
        self.lable.setPixmap(QPixmap.fromImage(img))
        # print(QPixmap(imgPath))
thstop=False
#上面的這個來控制進程結束
def showcamre():
    #參數0代表系統第一個攝像頭,第二就用1 以此類推
    cap=cv2.VideoCapture(0)
    #設置顯示分辨率和FPS ,不設置的話會非常卡
    cap.set(cv2.CAP_PROP_FRAME_WIDTH,800)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT,600)
    cap.set (cv2.CAP_PROP_FPS,20)
    while cap.isOpened():
        if thstop:
            return
        ret,frame=cap.read()
        if ret==False:
            continue
        #水平翻轉,很有必要
        frame=cv2.flip(frame,1)
        #opencv 默認圖像格式是rgb qimage要使用BRG,這里進行格式轉換,不用這個的話,圖像就變色了,困擾了半天,翻了一堆資料
        frame=cv2.cvtColor(frame,cv2.COLOR_RGB2BGR)
        #mat-->qimage
        a=QImage(frame.data,frame.shape[1],frame.shape[0],QImage.Format_RGB888)
        ex.SetPic(a)
app=QApplication(sys.argv)

ex=initform()
#全屏顯示
# ex.showFullScreen()
#使用線程,否則程序卡死
th=Thread(target=showcamre)
th.start()
app.exec_()
#退出的時候,結束進程,否則,關不掉進程
thstop=True

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM