pyqt5调用摄像头
1、UI布局
2、代码
"""
@contact: 微信 1257309054
@file: t.py
@time: 2023/9/10 0:16
@author: LDC
"""
import sys
import cv2
from PyQt5 import QtCore
from PyQt5 import QtWidgets, QtGui
from PyQt5. QtGui import QPixmap, QImage
from camera import Ui_MainWindow
class OpenCamera ( QtWidgets. QMainWindow, Ui_MainWindow) :
def __init__ ( self) :
super ( OpenCamera, self) . __init__( )
self. setupUi( self)
self. init( )
self. label_video. setScaledContents( True )
def init ( self) :
self. btn_open_camera. clicked. connect( self. open_camera)
self. btn_close_camera. clicked. connect( self. close_camera)
def open_camera ( self) :
self. is_close = False
cap = cv2. VideoCapture( 0 )
w, h = 640 , 360
cap. set ( 3 , w)
cap. set ( 4 , h)
while True :
success, img = cap. read( )
mirrow = cv2. flip( img, 1 )
width, height = mirrow. shape[ : 2 ]
if cv2. waitKey( 1 ) == 27 :
break
image_show = cv2. cvtColor( mirrow, cv2. COLOR_BGR2RGB)
self. showImage = QtGui. QImage( image_show. data, height, width, QImage. Format_RGB888)
self. label_video. setPixmap( QPixmap. fromImage( self. showImage) )
if self. is_close:
break
cap. release( )
self. label_video. clear( )
def close_camera ( self) :
self. is_close = True
if __name__ == '__main__' :
QtCore. QCoreApplication. setAttribute( QtCore. Qt. AA_EnableHighDpiScaling)
app = QtWidgets. QApplication( sys. argv)
ui = OpenCamera( )
ui. show( )
sys. exit( app. exec_( ) )