Python QT与Opencv(五)

一.Opencv与PyQt:运动检测监视系统

①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(1041, 576)
        self.imagelabel = QtWidgets.QLabel(Dialog)
        self.imagelabel.setGeometry(QtCore.QRect(370, 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, 1001, 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.motimgButton = QtWidgets.QPushButton(self.layoutWidget)
        self.motimgButton.setObjectName("motimgButton")
        self.horizontalLayout.addWidget(self.motimgButton)
        self.motionButton = QtWidgets.QPushButton(self.layoutWidget)
        self.motionButton.setObjectName("motionButton")
        self.horizontalLayout.addWidget(self.motionButton)
        self.motionlabel = QtWidgets.QLabel(Dialog)
        self.motionlabel.setGeometry(QtCore.QRect(20, 180, 320, 240))
        self.motionlabel.setFrameShape(QtWidgets.QFrame.Box)
        self.motionlabel.setText("")
        self.motionlabel.setObjectName("motionlabel")

        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/Pause"))
        self.motimgButton.setText(_translate("Dialog", "Set Refer Image"))
        self.motionButton.setText(_translate("Dialog", "Detect Motion"))

③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 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.motionButton.setCheckable(True)
        self.motionButton.toggled.connect(self.detect_webcam_motion)
        self.motion_Enable = False

        self.motimgButton.clicked.connect(self.set_motion_image)
        self.motionFrame = None

    def detect_webcam_motion(self,status):
        if status:
            self.motion_Enable = True
            self.motimgButton.setText("Stop Motion!")
        else:
            self.motion_Enable = False
            self.motimgButton.setText("Detect Motion")

    def set_motion_image(self):
        gray = cv2.cvtColor(self.image.copy(),cv2.COLOR_BGR2GRAY)
        gray = cv2.GaussianBlur(gray,(21,21),0)
        self.motionFrame = gray
        self.displayImage(self.motionFrame,2)

    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.motion_Enable):
            detect_motion = self.detect_motion(self.image.copy())
            self.displayImage(detect_motion,1)
        else:
            self.displayImage(self.image, 1)

    def detect_motion(self,input_img):
        self.text = "No Motion"
        gray = cv2.cvtColor(input_img,cv2.COLOR_BGR2GRAY)
        gray = cv2.GaussianBlur(gray, (21, 21), 0)

        frameDiff = cv2.absdiff(self.motionFrame,gray)
        thresh = cv2.threshold(frameDiff,40,255,cv2.THRESH_BINARY)[1]

        thresh = cv2.dilate(thresh,None,iterations=5)

        im2,cnts,hierarchy = cv2.findContours(thresh.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

        try:
            hierarchy = hierarchy[0]
        except:
            hierarchy = []

        height,width,channels = input_img.shape

        min_x,min_y = width,height
        max_x = max_y = 0

        # 下面的编程思路参考上面的原理图
        for contour,hier in zip(cnts,hierarchy):
            (x,y,w,h) = cv2.boundingRect(contour)
            min_x,max_x = min(x,min_x),max(x+w,max_x)
            min_y,max_y = min(y,min_y),max(y+h,max_y)

        if max_x - min_x > 80 and max_y - min_y > 80:
            cv2.rectangle(input_img,(min_x,min_y),(max_x,max_y),(0,255,0),3)
            self.text = "Motion Detected"
        cv2.putText(input_img,"Motion Status:{}".format(self.text),(10,20),cv2.FONT_HERSHEY_SIMPLEX,0.7,(0,0,255),2)
        return input_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 window == 2:
            self.motionlabel.setPixmap(QPixmap.fromImage(outImage))
            self.motionlabel.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_())

效果:
程序运行效果视频:
链接:https://pan.baidu.com/s/1CJkPz4Ud-3n2UBP1AKbLQw
提取码:ddc4

二.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(1319, 725)
        self.imagelabel = QtWidgets.QLabel(Dialog)
        self.imagelabel.setGeometry(QtCore.QRect(10, 60, 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, 1291, 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.trackButton = QtWidgets.QPushButton(self.layoutWidget)
        self.trackButton.setObjectName("trackButton")
        self.horizontalLayout.addWidget(self.trackButton)
        self.processedlabel = QtWidgets.QLabel(Dialog)
        self.processedlabel.setGeometry(QtCore.QRect(660, 60, 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(30, 580, 271, 88))
        self.widget.setObjectName("widget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.widget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.label = QtWidgets.QLabel(self.widget)
        self.label.setObjectName("label")
        self.horizontalLayout_2.addWidget(self.label)
        self.hMin = QtWidgets.QSlider(self.widget)
        self.hMin.setMaximum(255)
        self.hMin.setProperty("value", 0)
        self.hMin.setOrientation(QtCore.Qt.Horizontal)
        self.hMin.setObjectName("hMin")
        self.horizontalLayout_2.addWidget(self.hMin)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.label_3 = QtWidgets.QLabel(self.widget)
        self.label_3.setObjectName("label_3")
        self.horizontalLayout_4.addWidget(self.label_3)
        self.sMin = QtWidgets.QSlider(self.widget)
        self.sMin.setMaximum(255)
        self.sMin.setProperty("value", 0)
        self.sMin.setOrientation(QtCore.Qt.Horizontal)
        self.sMin.setObjectName("sMin")
        self.horizontalLayout_4.addWidget(self.sMin)
        self.verticalLayout.addLayout(self.horizontalLayout_4)
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.label_4 = QtWidgets.QLabel(self.widget)
        self.label_4.setObjectName("label_4")
        self.horizontalLayout_5.addWidget(self.label_4)
        self.vMin = QtWidgets.QSlider(self.widget)
        self.vMin.setMaximum(255)
        self.vMin.setProperty("value", 0)
        self.vMin.setOrientation(QtCore.Qt.Horizontal)
        self.vMin.setObjectName("vMin")
        self.horizontalLayout_5.addWidget(self.vMin)
        self.verticalLayout.addLayout(self.horizontalLayout_5)
        self.widget1 = QtWidgets.QWidget(Dialog)
        self.widget1.setGeometry(QtCore.QRect(350, 580, 271, 88))
        self.widget1.setObjectName("widget1")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.widget1)
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.label_2 = QtWidgets.QLabel(self.widget1)
        self.label_2.setObjectName("label_2")
        self.horizontalLayout_3.addWidget(self.label_2)
        self.hMax = QtWidgets.QSlider(self.widget1)
        self.hMax.setMaximum(255)
        self.hMax.setProperty("value", 255)
        self.hMax.setOrientation(QtCore.Qt.Horizontal)
        self.hMax.setObjectName("hMax")
        self.horizontalLayout_3.addWidget(self.hMax)
        self.verticalLayout_2.addLayout(self.horizontalLayout_3)
        self.horizontalLayout_6 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")
        self.label_5 = QtWidgets.QLabel(self.widget1)
        self.label_5.setObjectName("label_5")
        self.horizontalLayout_6.addWidget(self.label_5)
        self.sMax = QtWidgets.QSlider(self.widget1)
        self.sMax.setMaximum(255)
        self.sMax.setProperty("value", 255)
        self.sMax.setOrientation(QtCore.Qt.Horizontal)
        self.sMax.setObjectName("sMax")
        self.horizontalLayout_6.addWidget(self.sMax)
        self.verticalLayout_2.addLayout(self.horizontalLayout_6)
        self.horizontalLayout_7 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_7.setObjectName("horizontalLayout_7")
        self.label_6 = QtWidgets.QLabel(self.widget1)
        self.label_6.setObjectName("label_6")
        self.horizontalLayout_7.addWidget(self.label_6)
        self.vMax = QtWidgets.QSlider(self.widget1)
        self.vMax.setMaximum(255)
        self.vMax.setProperty("value", 255)
        self.vMax.setOrientation(QtCore.Qt.Horizontal)
        self.vMax.setObjectName("vMax")
        self.horizontalLayout_7.addWidget(self.vMax)
        self.verticalLayout_2.addLayout(self.horizontalLayout_7)
        self.widget2 = QtWidgets.QWidget(Dialog)
        self.widget2.setGeometry(QtCore.QRect(691, 581, 471, 30))
        self.widget2.setObjectName("widget2")
        self.horizontalLayout_8 = QtWidgets.QHBoxLayout(self.widget2)
        self.horizontalLayout_8.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_8.setObjectName("horizontalLayout_8")
        self.color1_Check = QtWidgets.QCheckBox(self.widget2)
        self.color1_Check.setObjectName("color1_Check")
        self.horizontalLayout_8.addWidget(self.color1_Check)
        self.color1_Button = QtWidgets.QPushButton(self.widget2)
        self.color1_Button.setObjectName("color1_Button")
        self.horizontalLayout_8.addWidget(self.color1_Button)
        self.color1_Label = QtWidgets.QLabel(self.widget2)
        self.color1_Label.setObjectName("color1_Label")
        self.horizontalLayout_8.addWidget(self.color1_Label)

        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/Pause"))
        self.trackButton.setText(_translate("Dialog", "Track Color"))
        self.label.setText(_translate("Dialog", "H_Min"))
        self.label_3.setText(_translate("Dialog", "S_Min"))
        self.label_4.setText(_translate("Dialog", "V_Min"))
        self.label_2.setText(_translate("Dialog", "H_Max"))
        self.label_5.setText(_translate("Dialog", "S_Max"))
        self.label_6.setText(_translate("Dialog", "V_Max"))
        self.color1_Check.setText(_translate("Dialog", "Track Color 1"))
        self.color1_Button.setText(_translate("Dialog", "Set Color 1"))
        self.color1_Label.setText(_translate("Dialog", "Value:"))

③main.py

# -*- coding: utf-8 -*-
import sys
import cv2
import numpy as np
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QDialog, QApplication
from PyQt5.QtCore import QTimer
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.trackButton.setCheckable(True)
        self.trackButton.toggled.connect(self.track_webcam_color)
        self.track_Enabled = False

        self.color1_Button.clicked.connect(self.setColor1)

    def track_webcam_color(self,status):
        if status:
            self.track_Enabled = True
            self.trackButton.setText("Stop Tracking!")
        else:
            self.track_Enabled = False
            self.trackButton.setText("Track Color")

    def setColor1(self):
        self.color1_lower = np.array([self.hMin.value(), self.sMin.value(), self.vMin.value()], np.uint8)
        self.color1_upper = np.array([self.hMax.value(), self.sMax.value(), self.vMax.value()], np.uint8)

        self.color1_Label.setText("Min:"+ str(self.color1_lower) + "Max:" + str(self.color1_upper))

    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)

        hsv = cv2.cvtColor(self.image,cv2.COLOR_BGR2HSV)

        color_lower = np.array([self.hMin.value(), self.sMin.value(), self.vMin.value()], np.uint8)
        color_upper = np.array([self.hMax.value(), self.sMax.value(), self.vMax.value()], np.uint8)

        color_mask = cv2.inRange(hsv,color_lower,color_upper)
        self.displayImage(color_mask,2)

        if (self.track_Enabled and self.color1_Check.isChecked()):
            trackedImage = self.track_colored_object(self.image.copy())
            self.displayImage(trackedImage,1)
        else:
            self.displayImage(self.image,1)

    def track_colored_object(self,img):
        blur = cv2.blur(img,(3,3))
        hsv = cv2.cvtColor(blur,cv2.COLOR_BGR2HSV)
        color_mask = cv2.inRange(hsv,self.color1_lower,self.color1_upper)

        erode = cv2.erode(color_mask,None,iterations=2)
        dilate = cv2.dilate(erode,None,iterations=10)

        kernelOpen = np.ones((5,5))
        kernelClose = np.ones((20,20))

        maskOpen = cv2.morphologyEx(dilate,cv2.MORPH_OPEN,kernelOpen)
        maskClose = cv2.morphologyEx(maskOpen,cv2.MORPH_CLOSE,kernelClose)

        (_,contours,hierarchy) = cv2.findContours(maskClose,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

        for cnt in contours:
            area = cv2.contourArea(cnt)
            if (area > 5000):
                x,y,w,h = cv2.boundingRect(cnt)
                img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)
                cv2.putText(img,"Object Detected",(x,y),cv2.FONT_HERSHEY_SIMPLEX,0.8,(0,255,0),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 window == 2:
            self.processedlabel.setPixmap(QPixmap.fromImage(outImage))
            self.processedlabel.setScaledContents(True)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Life2Coding()
    window.show()
    sys.exit(app.exec_())

运行效果、程序的源代码及UI文件在
链接:https://pan.baidu.com/s/124Forzqyyz_lBLmlaafqaA
提取码:myki

三.opencv中对多个彩色对象的实时跟踪

(对上个程序的修改)
①Qt designer
在这里插入图片描述
②Multiple.ui -> Multiple.py

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'Multiple.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(1255, 725)
        self.imagelabel = QtWidgets.QLabel(Dialog)
        self.imagelabel.setGeometry(QtCore.QRect(10, 60, 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, 1291, 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.trackButton = QtWidgets.QPushButton(self.layoutWidget)
        self.trackButton.setObjectName("trackButton")
        self.horizontalLayout.addWidget(self.trackButton)
        self.processedlabel = QtWidgets.QLabel(Dialog)
        self.processedlabel.setGeometry(QtCore.QRect(660, 60, 640, 480))
        self.processedlabel.setFrameShape(QtWidgets.QFrame.Box)
        self.processedlabel.setText("")
        self.processedlabel.setObjectName("processedlabel")
        self.layoutWidget1 = QtWidgets.QWidget(Dialog)
        self.layoutWidget1.setGeometry(QtCore.QRect(30, 580, 271, 88))
        self.layoutWidget1.setObjectName("layoutWidget1")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.layoutWidget1)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.label = QtWidgets.QLabel(self.layoutWidget1)
        self.label.setObjectName("label")
        self.horizontalLayout_2.addWidget(self.label)
        self.hMin = QtWidgets.QSlider(self.layoutWidget1)
        self.hMin.setMaximum(255)
        self.hMin.setProperty("value", 0)
        self.hMin.setOrientation(QtCore.Qt.Horizontal)
        self.hMin.setObjectName("hMin")
        self.horizontalLayout_2.addWidget(self.hMin)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.label_3 = QtWidgets.QLabel(self.layoutWidget1)
        self.label_3.setObjectName("label_3")
        self.horizontalLayout_4.addWidget(self.label_3)
        self.sMin = QtWidgets.QSlider(self.layoutWidget1)
        self.sMin.setMaximum(255)
        self.sMin.setProperty("value", 0)
        self.sMin.setOrientation(QtCore.Qt.Horizontal)
        self.sMin.setObjectName("sMin")
        self.horizontalLayout_4.addWidget(self.sMin)
        self.verticalLayout.addLayout(self.horizontalLayout_4)
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.label_4 = QtWidgets.QLabel(self.layoutWidget1)
        self.label_4.setObjectName("label_4")
        self.horizontalLayout_5.addWidget(self.label_4)
        self.vMin = QtWidgets.QSlider(self.layoutWidget1)
        self.vMin.setMaximum(255)
        self.vMin.setProperty("value", 0)
        self.vMin.setOrientation(QtCore.Qt.Horizontal)
        self.vMin.setObjectName("vMin")
        self.horizontalLayout_5.addWidget(self.vMin)
        self.verticalLayout.addLayout(self.horizontalLayout_5)
        self.layoutWidget2 = QtWidgets.QWidget(Dialog)
        self.layoutWidget2.setGeometry(QtCore.QRect(350, 580, 271, 88))
        self.layoutWidget2.setObjectName("layoutWidget2")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.layoutWidget2)
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.label_2 = QtWidgets.QLabel(self.layoutWidget2)
        self.label_2.setObjectName("label_2")
        self.horizontalLayout_3.addWidget(self.label_2)
        self.hMax = QtWidgets.QSlider(self.layoutWidget2)
        self.hMax.setMaximum(255)
        self.hMax.setProperty("value", 255)
        self.hMax.setOrientation(QtCore.Qt.Horizontal)
        self.hMax.setObjectName("hMax")
        self.horizontalLayout_3.addWidget(self.hMax)
        self.verticalLayout_2.addLayout(self.horizontalLayout_3)
        self.horizontalLayout_6 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")
        self.label_5 = QtWidgets.QLabel(self.layoutWidget2)
        self.label_5.setObjectName("label_5")
        self.horizontalLayout_6.addWidget(self.label_5)
        self.sMax = QtWidgets.QSlider(self.layoutWidget2)
        self.sMax.setMaximum(255)
        self.sMax.setProperty("value", 255)
        self.sMax.setOrientation(QtCore.Qt.Horizontal)
        self.sMax.setObjectName("sMax")
        self.horizontalLayout_6.addWidget(self.sMax)
        self.verticalLayout_2.addLayout(self.horizontalLayout_6)
        self.horizontalLayout_7 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_7.setObjectName("horizontalLayout_7")
        self.label_6 = QtWidgets.QLabel(self.layoutWidget2)
        self.label_6.setObjectName("label_6")
        self.horizontalLayout_7.addWidget(self.label_6)
        self.vMax = QtWidgets.QSlider(self.layoutWidget2)
        self.vMax.setMaximum(255)
        self.vMax.setProperty("value", 255)
        self.vMax.setOrientation(QtCore.Qt.Horizontal)
        self.vMax.setObjectName("vMax")
        self.horizontalLayout_7.addWidget(self.vMax)
        self.verticalLayout_2.addLayout(self.horizontalLayout_7)
        self.layoutWidget3 = QtWidgets.QWidget(Dialog)
        self.layoutWidget3.setGeometry(QtCore.QRect(690, 580, 471, 30))
        self.layoutWidget3.setObjectName("layoutWidget3")
        self.horizontalLayout_8 = QtWidgets.QHBoxLayout(self.layoutWidget3)
        self.horizontalLayout_8.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_8.setObjectName("horizontalLayout_8")
        self.color1_Check = QtWidgets.QCheckBox(self.layoutWidget3)
        self.color1_Check.setObjectName("color1_Check")
        self.horizontalLayout_8.addWidget(self.color1_Check)
        self.color1_Button = QtWidgets.QPushButton(self.layoutWidget3)
        self.color1_Button.setObjectName("color1_Button")
        self.horizontalLayout_8.addWidget(self.color1_Button)
        self.color1_Label = QtWidgets.QLabel(self.layoutWidget3)
        self.color1_Label.setObjectName("color1_Label")
        self.horizontalLayout_8.addWidget(self.color1_Label)
        self.layoutWidget_2 = QtWidgets.QWidget(Dialog)
        self.layoutWidget_2.setGeometry(QtCore.QRect(690, 610, 471, 30))
        self.layoutWidget_2.setObjectName("layoutWidget_2")
        self.horizontalLayout_9 = QtWidgets.QHBoxLayout(self.layoutWidget_2)
        self.horizontalLayout_9.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_9.setObjectName("horizontalLayout_9")
        self.color2_Check = QtWidgets.QCheckBox(self.layoutWidget_2)
        self.color2_Check.setObjectName("color2_Check")
        self.horizontalLayout_9.addWidget(self.color2_Check)
        self.color2_Button = QtWidgets.QPushButton(self.layoutWidget_2)
        self.color2_Button.setObjectName("color2_Button")
        self.horizontalLayout_9.addWidget(self.color2_Button)
        self.color2_Label = QtWidgets.QLabel(self.layoutWidget_2)
        self.color2_Label.setObjectName("color2_Label")
        self.horizontalLayout_9.addWidget(self.color2_Label)
        self.layoutWidget_3 = QtWidgets.QWidget(Dialog)
        self.layoutWidget_3.setGeometry(QtCore.QRect(690, 640, 471, 30))
        self.layoutWidget_3.setObjectName("layoutWidget_3")
        self.horizontalLayout_10 = QtWidgets.QHBoxLayout(self.layoutWidget_3)
        self.horizontalLayout_10.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_10.setObjectName("horizontalLayout_10")
        self.color3_Check = QtWidgets.QCheckBox(self.layoutWidget_3)
        self.color3_Check.setObjectName("color3_Check")
        self.horizontalLayout_10.addWidget(self.color3_Check)
        self.color3_Button = QtWidgets.QPushButton(self.layoutWidget_3)
        self.color3_Button.setObjectName("color3_Button")
        self.horizontalLayout_10.addWidget(self.color3_Button)
        self.color3_Label = QtWidgets.QLabel(self.layoutWidget_3)
        self.color3_Label.setObjectName("color3_Label")
        self.horizontalLayout_10.addWidget(self.color3_Label)

        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/Pause"))
        self.trackButton.setText(_translate("Dialog", "Track Color"))
        self.label.setText(_translate("Dialog", "H_Min"))
        self.label_3.setText(_translate("Dialog", "S_Min"))
        self.label_4.setText(_translate("Dialog", "V_Min"))
        self.label_2.setText(_translate("Dialog", "H_Max"))
        self.label_5.setText(_translate("Dialog", "S_Max"))
        self.label_6.setText(_translate("Dialog", "V_Max"))
        self.color1_Check.setText(_translate("Dialog", "Track Color 1"))
        self.color1_Button.setText(_translate("Dialog", "Set Color 1"))
        self.color1_Label.setText(_translate("Dialog", "Value:"))
        self.color2_Check.setText(_translate("Dialog", "Track Color 2"))
        self.color2_Button.setText(_translate("Dialog", "Set Color 2"))
        self.color2_Label.setText(_translate("Dialog", "Value:"))
        self.color3_Check.setText(_translate("Dialog", "Track Color 3"))
        self.color3_Button.setText(_translate("Dialog", "Set Color 3"))
        self.color3_Label.setText(_translate("Dialog", "Value:"))

③main_code

# -*- coding: utf-8 -*-
import sys
import cv2
import numpy as np
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QDialog, QApplication
from PyQt5.QtCore import QTimer
from Multiple 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.trackButton.setCheckable(True)
        self.trackButton.toggled.connect(self.track_webcam_color)
        self.track_Enabled = False

        self.color1_Button.clicked.connect(self.setColor1)
        self.color2_Button.clicked.connect(self.setColor2)
        self.color3_Button.clicked.connect(self.setColor3)

    def track_webcam_color(self,status):
        if status:
            self.track_Enabled = True
            self.trackButton.setText("Stop Tracking!")
        else:
            self.track_Enabled = False
            self.trackButton.setText("Track Color")

    def setColor1(self):
        self.color1_lower = np.array([self.hMin.value(), self.sMin.value(), self.vMin.value()], np.uint8)
        self.color1_upper = np.array([self.hMax.value(), self.sMax.value(), self.vMax.value()], np.uint8)

        self.color1_Label.setText("Min:"+ str(self.color1_lower) + "Max:" + str(self.color1_upper))

    def setColor2(self):
        self.color2_lower = np.array([self.hMin.value(), self.sMin.value(), self.vMin.value()], np.uint8)
        self.color2_upper = np.array([self.hMax.value(), self.sMax.value(), self.vMax.value()], np.uint8)

        self.color2_Label.setText("Min:"+ str(self.color2_lower) + "Max:" + str(self.color2_upper))

    def setColor3(self):
        self.color3_lower = np.array([self.hMin.value(), self.sMin.value(), self.vMin.value()], np.uint8)
        self.color3_upper = np.array([self.hMax.value(), self.sMax.value(), self.vMax.value()], np.uint8)

        self.color3_Label.setText("Min:"+ str(self.color3_lower) + "Max:" + str(self.color3_upper))

    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)

        hsv = cv2.cvtColor(self.image,cv2.COLOR_BGR2HSV)

        color_lower = np.array([self.hMin.value(), self.sMin.value(), self.vMin.value()], np.uint8)
        color_upper = np.array([self.hMax.value(), self.sMax.value(), self.vMax.value()], np.uint8)

        color_mask = cv2.inRange(hsv,color_lower,color_upper)
        self.displayImage(color_mask,2)

        if (self.track_Enabled and (self.color1_Check.isChecked() or self.color2_Check.isChecked() or self.color3_Check.isChecked())):
            trackedImage = self.track_colored_object(self.image.copy())
            self.displayImage(trackedImage,1)
        else:
            self.displayImage(self.image,1)

    def track_colored_object(self,img):
        blur = cv2.blur(img,(3,3))
        hsv = cv2.cvtColor(blur,cv2.COLOR_BGR2HSV)

        if self.color1_Check.isChecked():
            color_mask = cv2.inRange(hsv,self.color1_lower,self.color1_upper)

            erode = cv2.erode(color_mask,None,iterations=2)
            dilate = cv2.dilate(erode,None,iterations=10)

            kernelOpen = np.ones((5,5))
            kernelClose = np.ones((20,20))

            maskOpen = cv2.morphologyEx(dilate,cv2.MORPH_OPEN,kernelOpen)
            maskClose = cv2.morphologyEx(maskOpen,cv2.MORPH_CLOSE,kernelClose)

            (_,contours,hierarchy) = cv2.findContours(maskClose,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

            for cnt in contours:
                area = cv2.contourArea(cnt)
                if (area > 5000):
                    x,y,w,h = cv2.boundingRect(cnt)
                    img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)
                    cv2.putText(img,"Color 1 Detected",(x,y),cv2.FONT_HERSHEY_SIMPLEX,0.8,(0,255,0),2) # 参数调节

        if self.color2_Check.isChecked():
            color_mask = cv2.inRange(hsv, self.color2_lower, self.color2_upper)

            erode = cv2.erode(color_mask, None, iterations=2)
            dilate = cv2.dilate(erode, None, iterations=10)

            kernelOpen = np.ones((5, 5))
            kernelClose = np.ones((20, 20))

            maskOpen = cv2.morphologyEx(dilate, cv2.MORPH_OPEN, kernelOpen)
            maskClose = cv2.morphologyEx(maskOpen, cv2.MORPH_CLOSE, kernelClose)

            (_, contours, hierarchy) = cv2.findContours(maskClose, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

            for cnt in contours:
                area = cv2.contourArea(cnt)
                if (area > 5000):
                    x, y, w, h = cv2.boundingRect(cnt)
                    img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)
                    cv2.putText(img, "Color 2 Detected", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)  # 参数调节

        if self.color3_Check.isChecked():
            color_mask = cv2.inRange(hsv, self.color3_lower, self.color3_upper)

            erode = cv2.erode(color_mask, None, iterations=2)
            dilate = cv2.dilate(erode, None, iterations=10)

            kernelOpen = np.ones((5, 5))
            kernelClose = np.ones((20, 20))

            maskOpen = cv2.morphologyEx(dilate, cv2.MORPH_OPEN, kernelOpen)
            maskClose = cv2.morphologyEx(maskOpen, cv2.MORPH_CLOSE, kernelClose)

            (_, contours, hierarchy) = cv2.findContours(maskClose, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

            for cnt in contours:
                area = cv2.contourArea(cnt)
                if (area > 5000):
                    x, y, w, h = cv2.boundingRect(cnt)
                    img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)
                    cv2.putText(img, "Color 3 Detected", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 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 window == 2:
            self.processedlabel.setPixmap(QPixmap.fromImage(outImage))
            self.processedlabel.setScaledContents(True)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Life2Coding()
    window.show()
    sys.exit(app.exec_())

运行效果、程序的源代码及UI文件在:
链接:https://pan.baidu.com/s/1xNKUTw1IUQaQRJ-cgFJcPg
提取码:0s4n
(PS:运行的效果不太好)

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

boss-dog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值