一.通过控件Label显示Opencv摄像头视频
①Qt designer
②webcam.ui -> webcam.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'webcam.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(734, 646)
self.imagelabel = QtWidgets.QLabel(Dialog)
self.imagelabel.setGeometry(QtCore.QRect(50, 110, 640, 480))
self.imagelabel.setFrameShape(QtWidgets.QFrame.Box)
self.imagelabel.setText("")
self.imagelabel.setObjectName("imagelabel")
self.widget = QtWidgets.QWidget(Dialog)
self.widget.setGeometry(QtCore.QRect(50, 50, 641, 30))
self.widget.setObjectName("widget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.widget)
self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout.setObjectName("horizontalLayout")
self.startButton = QtWidgets.QPushButton(self.widget)
self.startButton.setObjectName("startButton")
self.horizontalLayout.addWidget(self.startButton)
self.stopButton = QtWidgets.QPushButton(self.widget)
self.stopButton.setObjectName("stopButton")
self.horizontalLayout.addWidget(self.stopButton)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.startButton.setText(_translate("Dialog", "start webcam"))
self.stopButton.setText(_translate("Dialog", "stop webcam"))
③main.py
# -*- coding: utf-8 -*-
import sys
import cv2
from PyQt5.QtGui import QImage,QPixmap
from PyQt5.QtWidgets import QDialog,QApplication
from PyQt5.QtCore import QTimer
from PyQt5.uic import loadUi
from webcam import Ui_Dialog
class Life2Coding(QDialog,Ui_Dialog):
def __init__(self, parent=None):
super(QDialog, self).__init__(parent)
self.setupUi(self)
self.image = None
self.startButton.clicked.connect(self.start_webcam)
self.stopButton.clicked.connect(self.stop_webcam)
def start_webcam(self):
camera_number = 0
self.capture = cv2.VideoCapture(camera_number + cv2.CAP_DSHOW)
# 这里若写self.capture = cv2.VideoCapture(0)会报错
# 参考博客 https://blog.csdn.net/qq_33532713/article/details/88541111
self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT,480)
self.capture.set(cv2.CAP_PROP_FRAME_WIDTH,640)
self.timer = QTimer(self)
self.timer.timeout.connect(self.update_frame)
self.timer.start(5)
def update_frame(self):
ret,self.image = self.capture.read()
self.image = cv2.flip(self.image,1)
self.displayImage(self.image,1)
def stop_webcam(self):
self.timer.stop()
def displayImage(self,img,window=1):
qformat = QImage.Format_Indexed8
if (len(img.shape)) == 3: # [0]=rows,[1]=cols,[2]=channels
if img.shape[2] == 4:
qformat = QImage.Format_RGBA8888
else:
qformat = QImage.Format_RGB888
outImage = QImage(img,img.shape[1],img.shape[0],img.strides[0],qformat)
# BGR->RGB
outImage = outImage.rgbSwapped()
if window == 1:
self.imagelabel.setPixmap(QPixmap.fromImage(outImage))
self.imagelabel.setScaledContents(True)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Life2Coding()
window.setWindowTitle("Display Opencv webcam video feed into Glabel")
window.show()
sys.exit(app.exec_())
效果:
二.在网络摄像头中应用Canny算法
①Qt designer
②webcam.ui -> webcam.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'webcam.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(1333, 576)
self.imagelabel = QtWidgets.QLabel(Dialog)
self.imagelabel.setGeometry(QtCore.QRect(10, 70, 640, 480))
self.imagelabel.setFrameShape(QtWidgets.QFrame.Box)
self.imagelabel.setText("")
self.imagelabel.setObjectName("imagelabel")
self.processedlabel = QtWidgets.QLabel(Dialog)
self.processedlabel.setGeometry(QtCore.QRect(670, 70, 640, 480))
self.processedlabel.setFrameShape(QtWidgets.QFrame.Box)
self.processedlabel.setText("")
self.processedlabel.setObjectName("processedlabel")
self.widget = QtWidgets.QWidget(Dialog)
self.widget.setGeometry(QtCore.QRect(10, 20, 1301, 30))
self.widget.setObjectName("widget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.widget)
self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout.setObjectName("horizontalLayout")
self.startButton = QtWidgets.QPushButton(self.widget)
self.startButton.setObjectName("startButton")
self.horizontalLayout.addWidget(self.startButton)
self.stopButton = QtWidgets.QPushButton(self.widget)
self.stopButton.setObjectName("stopButton")
self.horizontalLayout.addWidget(self.stopButton)
self.cannyButton = QtWidgets.QPushButton(self.widget)
self.cannyButton.setObjectName("cannyButton")
self.horizontalLayout.addWidget(self.cannyButton)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.startButton.setText(_translate("Dialog", "start webcam"))
self.stopButton.setText(_translate("Dialog", "stop webcam"))
self.cannyButton.setText(_translate("Dialog", "Canny"))
③main.py
# -*- coding: utf-8 -*-
import sys
import cv2
from PyQt5.QtGui import QImage,QPixmap
from PyQt5.QtWidgets import QDialog,QApplication
from PyQt5.QtCore import QTimer
from PyQt5.uic import loadUi
from webcam import Ui_Dialog
class Life2Coding(QDialog,Ui_Dialog):
def __init__(self, parent=None):
super(QDialog, self).__init__(parent)
self.setupUi(self)
self.image = None
self.processedImage = None
self.startButton.clicked.connect(self.start_webcam)
self.stopButton.clicked.connect(self.stop_webcam)
self.cannyButton.toggled.connect(self.canny_webcam)
self.cannyButton.setCheckable(True)
self.canny_Enable = False
def canny_webcam(self,status):
if status:
self.canny_Enable = True
self.cannyButton.setText("Cannot Stop!")
else:
self.canny_Enable = False
self.cannyButton.setText("Canny!")
def start_webcam(self):
camera_number = 0
self.capture = cv2.VideoCapture(camera_number + cv2.CAP_DSHOW)
# 这里若写self.capture = cv2.VideoCapture(0)会报错
# 参考博客 https://blog.csdn.net/qq_33532713/article/details/88541111
self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT,480)
self.capture.set(cv2.CAP_PROP_FRAME_WIDTH,640)
self.timer = QTimer(self)
self.timer.timeout.connect(self.update_frame)
self.timer.start(5)
def update_frame(self):
ret,self.image = self.capture.read()
self.image = cv2.flip(self.image,1)
self.displayImage(self.image,1)
if (self.canny_Enable):
gray = cv2.cvtColor(self.image,cv2.COLOR_BGR2GRAY) if len(self.image.shape) >= 3 else self.image
self.processedImage = cv2.Canny(gray,100,200)
self.displayImage(self.processedImage,2)
def stop_webcam(self):
self.timer.stop()
def displayImage(self,img,window=1):
qformat = QImage.Format_Indexed8
if (len(img.shape)) == 3: # [0]=rows,[1]=cols,[2]=channels
if img.shape[2] == 4:
qformat = QImage.Format_RGBA8888
else:
qformat = QImage.Format_RGB888
outImage = QImage(img,img.shape[1],img.shape[0],img.strides[0],qformat)
# BGR->RGB
outImage = outImage.rgbSwapped()
if window == 1:
self.imagelabel.setPixmap(QPixmap.fromImage(outImage))
self.imagelabel.setScaledContents(True)
if window == 2:
self.processedlabel.setPixmap(QPixmap.fromImage(outImage))
self.processedlabel.setScaledContents(True)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Life2Coding()
window.setWindowTitle("Display Opencv webcam video feed into Glabel")
window.show()
sys.exit(app.exec_())
效果:
三.创建实时人脸检测的界面应用程序
①Qt designer
②webcam.ui -> webcam.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'webcam.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(681, 576)
self.imagelabel = QtWidgets.QLabel(Dialog)
self.imagelabel.setGeometry(QtCore.QRect(10, 70, 640, 480))
self.imagelabel.setFrameShape(QtWidgets.QFrame.Box)
self.imagelabel.setText("")
self.imagelabel.setObjectName("imagelabel")
self.layoutWidget = QtWidgets.QWidget(Dialog)
self.layoutWidget.setGeometry(QtCore.QRect(10, 20, 641, 30))
self.layoutWidget.setObjectName("layoutWidget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.layoutWidget)
self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout.setObjectName("horizontalLayout")
self.startButton = QtWidgets.QPushButton(self.layoutWidget)
self.startButton.setObjectName("startButton")
self.horizontalLayout.addWidget(self.startButton)
self.stopButton = QtWidgets.QPushButton(self.layoutWidget)
self.stopButton.setObjectName("stopButton")
self.horizontalLayout.addWidget(self.stopButton)
self.detectButton = QtWidgets.QPushButton(self.layoutWidget)
self.detectButton.setObjectName("detectButton")
self.horizontalLayout.addWidget(self.detectButton)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.startButton.setText(_translate("Dialog", "start webcam"))
self.stopButton.setText(_translate("Dialog", "stop webcam"))
self.detectButton.setText(_translate("Dialog", "detect face"))
③main.py
# -*- coding: utf-8 -*-
import sys
import cv2
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QDialog, QApplication
from PyQt5.QtCore import QTimer
from PyQt5.uic import loadUi
from webcam import Ui_Dialog
class Life2Coding(QDialog, Ui_Dialog):
def __init__(self, parent=None):
super(QDialog, self).__init__(parent)
self.setupUi(self)
self.image = None
self.startButton.clicked.connect(self.start_webcam)
self.stopButton.clicked.connect(self.stop_webcam)
self.detectButton.setCheckable(True)
self.detectButton.toggled.connect(self.detect_webcam_face)
self.face_Enabled = False
self.faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
def detect_webcam_face(self,status):
if status:
self.detectButton.setText("Stop Detection!")
self.face_Enabled = True
else:
self.detectButton.setText("Detect Face")
self.face_Enabled = False
def start_webcam(self):
camera_number = 0
self.capture = cv2.VideoCapture(camera_number + cv2.CAP_DSHOW)
# 这里若写self.capture = cv2.VideoCapture(0)会报错
# 参考博客 https://blog.csdn.net/qq_33532713/article/details/88541111
self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
self.timer = QTimer(self)
self.timer.timeout.connect(self.update_frame)
self.timer.start(5)
def update_frame(self):
ret, self.image = self.capture.read()
self.image = cv2.flip(self.image, 1)
if (self.face_Enabled):
detected_image = self.detect_face(self.image)
self.displayImage(detected_image,1)
else:
self.displayImage(self.image, 1)
def detect_face(self,img):
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces = self.faceCascade.detectMultiScale(gray,1.2,5,minSize=(90,90))
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)
return img
def stop_webcam(self):
self.timer.stop()
def displayImage(self, img, window=1):
qformat = QImage.Format_Indexed8
if (len(img.shape)) == 3: # [0]=rows,[1]=cols,[2]=channels
if img.shape[2] == 4:
qformat = QImage.Format_RGBA8888
else:
qformat = QImage.Format_RGB888
outImage = QImage(img, img.shape[1], img.shape[0], img.strides[0], qformat)
# BGR->RGB
outImage = outImage.rgbSwapped()
if window == 1:
self.imagelabel.setPixmap(QPixmap.fromImage(outImage))
self.imagelabel.setScaledContents(True)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Life2Coding()
window.setWindowTitle("Display Opencv webcam video feed into Glabel")
window.show()
sys.exit(app.exec_())
效果: