2021.4.6版本程序备份
效果图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d83edfd97a03f47ecaf2cc8cc2452b17.png)
代码
import cv2
import numpy as np
from imutils import contours
cap = cv2.VideoCapture('test.mp4')
green_lower = np.array([35, 43, 35])
green_upper = np.array([90, 255, 255])
red_lower = np.array([160, 20, 70])
red_upper = np.array([190, 255, 255])
kernel = np.ones((5, 5), np.uint8)
if cap.isOpened():
print('已经打开了视频')
fps = cap.get(cv2.CAP_PROP_FPS)
print('视频的帧率为:', fps)
while 1:
ret, frame = cap.read()
if not ret:
print('视频已结束')
break
draw_frame = frame.copy()
img_hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
img = cv2.inRange(img_hsv, red_lower, red_upper)
dilation = cv2.dilate(img, kernel, iterations=1)
closing = cv2.morphologyEx(dilation, cv2.MORPH_CLOSE, kernel)
closing = cv2.GaussianBlur(closing, (5, 5), 0)
edges = cv2.Canny(closing, 10, 20)
contour, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
if len(contour) > 0:
s = []
max_index = 0
(contour, boundingBoxes) = contours.sort_contours(contour)
for cnt in contour:
s.append(cv2.contourArea(cnt))
max_index = s.index(max(s))
(x, y, w, h) = boundingBoxes[max_index]
frame_out = cv2.rectangle(draw_frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.namedWindow('draw_frame', 0)
cv2.imshow("draw_frame", draw_frame)
cv2.waitKey(int(fps))
else:
print('视频打开失败')
2021.4.6第二版本程序备份
效果图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7e05d2a671330d6258a28944973c1c27.png)
代码
import cv2
import numpy as np
from imutils import contours
Picture_display_flag=0
cap = cv2.VideoCapture('test.mp4')
green_lower = np.array([35, 43, 35])
green_upper = np.array([90, 255, 255])
red_lower = np.array([160, 20, 70])
red_upper = np.array([190, 255, 255])
kernel = np.ones((5, 5), np.uint8)
kernel_1 = np.ones((7, 7), np.uint8)
if cap.isOpened():
print('已经打开了视频')
fps = cap.get(cv2.CAP_PROP_FPS)
print('视频的帧率为:', fps)
while 1:
ret, frame = cap.read()
if not ret:
print('视频已结束')
break
draw_frame = frame.copy()
img_hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
img = cv2.inRange(img_hsv, red_lower, red_upper)
if Picture_display_flag==1:
cv2.namedWindow('img', 0)
cv2.imshow("img", img)
dilation = cv2.dilate(img, kernel_1, iterations=1)
closing = cv2.morphologyEx(dilation, cv2.MORPH_CLOSE, kernel_1)
closing = cv2.GaussianBlur(closing, (5, 5), 0)
if Picture_display_flag==1:
cv2.namedWindow('closing', 0)
cv2.imshow("closing", img)
contour, hierarchy = cv2.findContours(closing, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
new_contour = []
if len(contour) > 0:
if Picture_display_flag == 1:
drawlk = cv2.drawContours(draw_frame, contour, -1, (0, 255, 255),2)
s = []
max_index = 0
(contour, boundingBoxes) = contours.sort_contours(contour)
for cnt in contour:
s.append(cv2.contourArea(cnt))
max_index = s.index(max(s))
epsilon = 0.01 * cv2.arcLength(contour[max_index], True)
approx=cv2.approxPolyDP(contour[max_index],epsilon,True)
cv2.polylines(draw_frame, [approx], True, (255, 255, 0), 4)
cv2.namedWindow('draw_frame', 0)
cv2.imshow("draw_frame", draw_frame)
cv2.waitKey(int(fps))
else:
print('视频打开失败')
2021.4.7第一版本程序备份——gui界面
效果图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/01f9264b8c2dc05dd8b802af7026e6dc.png)
代码
'''**************************************************************************
这是通用的图像识别的qt界面,具有读入图片,读入视频,显示图片显示视频的功能。
版本:1.0
内容:创建pyqt界面,用于图像识别,有基本打开图像,显示图像功能
时间:2020.3.20
作者:狄云
版本:2.0
内容:新增视频可以实时显示并检测,修改图片检测缓存路径,改为相对路劲
时间:2020.7.20
作者:狄云
版本:3.0
内容:新增空间间距设置,新增打开视频功能,(与之前打开图片功能相同)
时间:2020.8.16
作者:狄云
版本:4.0
内容:新增表格显示,使用方法参考:https://www.cnblogs.com/linyfeng/p/11832237.html
时间:2020.8.30
作者:狄云
版本:5.0
内容:新增登录界面,新增保存excel文件,使用方法参考:https://www.cnblogs.com/jyroy/p/9465034.html
时间:2020.9.04
作者:狄云
***************************************************************************'''
from PIL import Image
import datetime
import sys
import argparse
from PIL import Image
import numpy as np
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import os
import datetime
from timeit import time
import warnings
import cv2 as cv
import numpy as np
import argparse
from PIL import Image
import sys
from PyQt5.QtCore import QSize
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QComboBox
from PyQt5.QtWidgets import QGridLayout
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QLabel
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QTextEdit
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from imutils import contours
from qtpy import QtGui
from PyQt5.QtGui import QFont
camera_or_local_flag = 0
Start_or_pause_flag = 0
Picture_display_flag=0
result_image = ...
fps = 0.0
len_last = 0
class Camera:
def __init__(self, cam_preset_num=10):
self.cam_preset_num = cam_preset_num
def get_cam_num(self):
cnt = 0
for device in range(0, self.cam_preset_num):
stream = cv.VideoCapture(device)
grabbed = stream.grab()
stream.release()
if not grabbed:
break
cnt = cnt + 1
return cnt
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1650, 820)
self.verticalLayoutWidget = QtWidgets.QWidget(MainWindow)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(30, 25, 1280, 720))
self.verticalLayoutWidget.setStyleSheet('background-color:rgb(55,55,55)')
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName("verticalLayout")
self.label_ShowPicture = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_ShowPicture.setObjectName("label_ShowPicture")
self.verticalLayout.addWidget(self.label_ShowPicture)
self.verticalLayoutWidget_2 = QtWidgets.QWidget(MainWindow)
self.verticalLayoutWidget_2.setGeometry(QtCore.QRect(1350, 50, 250, 700))
self.verticalLayoutWidget_2.setObjectName("verticalLayoutWidget_2")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget_2)
self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.verticalLayout_2.setSpacing(30)
self.pushButton_find_camera = QtWidgets.QPushButton(self.verticalLayoutWidget_2)
self.pushButton_find_camera.setObjectName("pushButton_find_camera")
self.verticalLayout_2.addWidget(self.pushButton_find_camera)
self.pushButton_open_camera = QtWidgets.QPushButton(self.verticalLayoutWidget_2)
self.pushButton_open_camera.setObjectName("pushButton_open_camera")
self.verticalLayout_2.addWidget(self.pushButton_open_camera)
self.pushButton_open_Local_video = QtWidgets.QPushButton(self.verticalLayoutWidget_2)
self.pushButton_open_Local_video.setObjectName("pushButton_open_Local_video")
self.verticalLayout_2.addWidget(self.pushButton_open_Local_video)
self.comboBox_1 = QtWidgets.QComboBox(self.verticalLayoutWidget_2)
self.comboBox_1.setObjectName("comboBox_1")
self.verticalLayout_2.addWidget(self.comboBox_1)
self.comboBox_1.addItems([' 颜色选择', ' 红色', ' 绿色'])
self.comboBox_2 = QtWidgets.QComboBox(self.verticalLayoutWidget_2)
self.comboBox_2.setObjectName("comboBox_2")
self.verticalLayout_2.addWidget(self.comboBox_2)
self.comboBox_2.addItems([' 形状选择', ' 矩形', ' 圆形'])
self.pushButton_Start_or_pause = QtWidgets.QPushButton(self.verticalLayoutWidget_2)
self.pushButton_Start_or_pause.setObjectName("pushButton_Start_or_pause")
self.verticalLayout_2.addWidget(self.pushButton_Start_or_pause)
self.pushButton_save = QtWidgets.QPushButton(self.verticalLayoutWidget_2)
self.pushButton_save.setObjectName("pushButton_save")
self.verticalLayout_2.addWidget(self.pushButton_save)
self.label = QtWidgets.QLabel(self.verticalLayoutWidget_2)
font = QtGui.QFont()
font.setPointSize(15)
self.label.setFont(font)
self.label.setObjectName("label")
self.verticalLayout_2.addWidget(self.label)
self.label_2 = QtWidgets.QLabel(self.verticalLayoutWidget_2)
font = QtGui.QFont()
font.setPointSize(15)
self.label_2.setFont(font)
self.label_2.setText("")
self.label_2.setObjectName("label_2")
self.verticalLayout_2.addWidget(self.label_2)
self.tableWidget = QtWidgets.QTableWidget(self.verticalLayoutWidget_2)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(3)
self.tableWidget.setRowCount(100000)
self.tableWidget.setHorizontalHeaderLabels(['帧号', '时刻', '状态'])
self.verticalLayout_2.addWidget(self.tableWidget)
self.msg_box = QtWidgets.QMessageBox
self.tableWidget.horizontalHeader().resizeSection(0, 55)
self.tableWidget.horizontalHeader().resizeSection(1, 265)
self.tableWidget.horizontalHeader().resizeSection(2, 140)
self.tableWidget.verticalHeader().setVisible(False)
self.timer_camera = QtCore.QTimer()
self.cap = cv.VideoCapture()
self.CAM_NUM = 0
self.__flag_work = 0
self.x = 0
self.count = 0
self.pushButton_find_camera.clicked.connect(self.button_find_camera_click)
self.pushButton_open_camera.clicked.connect(self.button_open_camera_click)
self.timer_camera.timeout.connect(self.deep_sort)
self.pushButton_open_Local_video.clicked.connect(self.pushButton_open_Local_video_click)
self.pushButton_Start_or_pause.clicked.connect(self.pushButton_Start_or_pause_click)
self.pushButton_save.clicked.connect(self.pushButton_save_click)
self.comboBox_1.currentIndexChanged[str].connect(self.print_value_1)
self.comboBox_1.currentIndexChanged[int].connect(self.print_value_1)
self.comboBox_2.currentIndexChanged[str].connect(self.print_value_2)
self.comboBox_2.currentIndexChanged[int].connect(self.print_value_2)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
name_picture = 0
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "pyqt通用界面"))
self.pushButton_find_camera.setText(_translate("MainWindow", "检查设备"))
self.pushButton_open_camera.setText(_translate("MainWindow", "打开摄像头识别"))
self.pushButton_open_Local_video.setText(_translate("MainWindow", "选择本地视频识别"))
self.pushButton_Start_or_pause.setText(_translate("MainWindow", "开始识别"))
self.pushButton_save.setText(_translate("MainWindow", "保存结果"))
image = None
def button_find_camera_click(self):
cam = Camera()
cam_num = cam.get_cam_num()
print(cam_num)
new_num=str(cam_num)
self.label.setText( "当前设备摄像头个数为:")
self.label_2.setText(new_num)
def button_open_camera_click(self):
global camera_or_local_flag
if self.timer_camera.isActive() == False:
flag = self.cap.open(self.CAM_NUM)
if flag == False:
msg = QtWidgets.QMessageBox.Warning(self, u'Warning', u'请检测相机与电脑是否连接正确',
buttons=QtWidgets.QMessageBox.Ok,
defaultButton=QtWidgets.QMessageBox.Ok)
else:
self.timer_camera.start(30)
camera_or_local_flag = 1
self.pushButton_open_camera.setText(u'关闭相机')
else:
self.timer_camera.stop()
self.cap.release()
camera_or_local_flag = 0
self.label_ShowPicture.clear()
self.pushButton_open_camera.setText(u'打开相机')
def pushButton_select_pcture_click(self):
filename = QFileDialog.getOpenFileName(None, 'Open file', 'C:/Users/Desktop/testpicture/')
src0 = cv.imread(filename[0])
resized0 = cv.resize(src0, (1280, 720), interpolation=cv.INTER_AREA)
cv.imwrite("./temp/temp0.jpg", resized0)
self.label_ShowPicture.setPixmap(QPixmap("./temp/temp0.jpg"))
print("filename[0]=", filename[0])
self.image = Image.open(filename[0])
def pushButton_open_Local_video_click(self):
global camera_or_local_flag
self.timer_camera.stop()
self.cap.release()
camera_or_local_flag = 0
self.label_ShowPicture.clear()
self.pushButton_open_camera.setText(u'打开相机')
if self.timer_camera.isActive() == False:
print("打开本地视频")
self.fileName, self.fileType = QFileDialog.getOpenFileName(None, 'Choose file', '', '*.mp4')
self.cap_Local_video = cv.VideoCapture(self.fileName)
camera_or_local_flag = 2
ret, self.frame = self.cap_Local_video.read()
img = cv.resize(self.frame, (1280, 720), interpolation=cv.INTER_AREA)
height, width, bytesPerComponent = img.shape
bytesPerLine = 3 * width
cv.cvtColor(img, cv.COLOR_BGR2RGB, img)
QImg = QImage(img.data, width, height, bytesPerLine, QImage.Format_RGB888)
pixmap = QPixmap.fromImage(QImg)
self.label_ShowPicture.setPixmap(QPixmap(pixmap))
else:
self.timer_camera.stop()
self.cap_Local_video.release()
camera_or_local_flag = 0
self.label_ShowPicture.clear()
self.pushButton_open_Local_video.setText(u'打开本地视频')
def pushButton_Start_or_pause_click(self):
global camera_or_local_flag
global Start_or_pause_flag
print(camera_or_local_flag, Start_or_pause_flag)
print(254)
if camera_or_local_flag == 1:
if Start_or_pause_flag == 0:
Start_or_pause_flag = 1
print(258)
self.timer_camera.start(30)
self.pushButton_Start_or_pause.setText(u'识别中')
else:
Start_or_pause_flag = 0
self.timer_camera.stop(30)
self.pushButton_Start_or_pause.setText(u'开始识别')
elif camera_or_local_flag == 2:
if Start_or_pause_flag == 0:
Start_or_pause_flag = 1
self.timer_camera.start(30)
print(269)
print(camera_or_local_flag, Start_or_pause_flag)
self.pushButton_Start_or_pause.setText(u'识别中')
else:
Start_or_pause_flag = 0
self.timer_camera.stop(30)
self.pushButton_Start_or_pause.setText(u'开始识别')
print(" 2 camera_or_local_flag =%d Start_or_pause_flag =%d", camera_or_local_flag, Start_or_pause_flag)
def pushButton_save_click(self):
print("保存成功")
def print_value_1(self, i):
global type_seting_yanse
if i==0:
print("请选择等级")
type_seting_yanse = -1
if i == 1:
print("等级为红色")
type_seting_yanse=0
if i == 2:
print("等级为绿色")
type_seting_yanse = 1
def print_value_2(self, i):
global type_seting_xingzhuang
if i==0:
print("请选择等级")
type_seting_xingzhuang = -1
if i == 1:
print("等级为矩形")
type_seting_xingzhuang=0
if i == 2:
print("等级为圆形")
type_seting_xingzhuang = 1
def select_shipin(self):
global camera_or_local_flag
global Start_or_pause_flag
global result_image
print("选择视频中")
def deep_sort(self):
global camera_or_local_flag
global Start_or_pause_flag
global result_image
global counter_zhenhao
global counter_jueduizhenhao
global fps
global len_last
i = int(0)
ret = False
if camera_or_local_flag == 1 and Start_or_pause_flag == 0:
ret, self.frame = self.cap.read()
elif camera_or_local_flag == 2 and Start_or_pause_flag == 0:
ret, self.frame = self.cap_Local_video.read()
if camera_or_local_flag == 1 and Start_or_pause_flag == 1:
ret, self.frame = self.cap.read()
elif camera_or_local_flag == 2 and Start_or_pause_flag == 1:
ret, self.frame = self.cap_Local_video.read()
if ret != True:
print("打开图像失败 or 识别结束")
return
if Start_or_pause_flag == 1:
t1 = time.time()
frame0 = cv.resize(self.frame, (1280, 720), interpolation=cv.INTER_AREA)
frame = frame0.copy()
draw_frame = frame0.copy()
img_hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
img = cv.inRange(img_hsv, red_lower, red_upper)
if Picture_display_flag == 1:
cv.namedWindow('img', 0)
cv.imshow("img", img)
dilation = cv.dilate(img, kernel_1, iterations=1)
closing = cv.morphologyEx(dilation, cv.MORPH_CLOSE, kernel_1)
closing = cv.GaussianBlur(closing, (5, 5), 0)
if Picture_display_flag == 1:
cv.namedWindow('closing', 0)
cv.imshow("closing", img)
contour, hierarchy = cv.findContours(closing, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)
new_contour = []
if len(contour) > 0:
if Picture_display_flag == 1:
drawlk = cv.drawContours(draw_frame, contour, -1, (0, 255, 255),
2)
s = []
max_index = 0
(contour, boundingBoxes) = contours.sort_contours(contour)
for cnt in contour:
s.append(cv.contourArea(cnt))
max_index = s.index(max(s))
epsilon = 0.01 * cv.arcLength(contour[max_index], True)
approx = cv.approxPolyDP(contour[max_index], epsilon, True)
cv.polylines(draw_frame, [approx], True, (255, 255, 0), 4)
fps = (fps + (1. / (time.time() - t1))) / 2
draw_frame = cv.putText(draw_frame, "fps= %.2f" % (fps), (0, 40), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
frame0 = draw_frame.copy()
else:
frame0 = self.frame.copy()
img = cv.resize(frame0, (1280, 720), interpolation=cv.INTER_AREA)
height, width, bytesPerComponent = img.shape
bytesPerLine = 3 * width
cv.cvtColor(img, cv.COLOR_BGR2RGB, img)
QImg = QImage(img.data, width, height, bytesPerLine, QImage.Format_RGB888)
pixmap = QPixmap.fromImage(QImg)
self.label_ShowPicture.setPixmap(QPixmap(pixmap))
if __name__ == "__main__":
counter_zhenhao = 3
counter_jueduizhenhao = 0
green_lower = np.array([35, 43, 35])
green_upper = np.array([90, 255, 255])
red_lower = np.array([160, 20, 70])
red_upper = np.array([190, 255, 255])
kernel = np.ones((5, 5), np.uint8)
kernel_1 = np.ones((7, 7), np.uint8)
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())