代码拉取完成,页面将自动刷新
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'e:\Py\demo\step3.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
import time
from PyQt5.QtChart import QChartView
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
from PyQt5.QtGui import QPainter, QPen
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtChart import (QChartView, QChart, QBarSeries, QBarSet, QLineSeries, QPieSeries,
QLegend, QBarCategoryAxis, QValueAxis)
import cv2 as cv
from PyQt5.QtCore import QTimer
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import random
import cv2 as cv
import numpy as np
import os
import sys
import xml.dom.minidom as xmldom
import argparse
from nms import py_cpu_nms
import time as T
import re
import linecache
import matplotlib.pyplot as plt
from utils.torch_utils import select_device, time_sync
from models.common import DetectMultiBackend
from util import plot_one_box, cal_iou, xyxy_to_xywh, xywh_to_xyxy, updata_trace_list, draw_trace
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams
from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh)
from utils.plots import Annotator, colors, save_one_box
from utils.augmentations import Albumentations, augment_hsv, copy_paste, letterbox, mixup, random_perspective
from utils.general import (DATASETS_DIR, LOGGER, NUM_THREADS, check_dataset, check_requirements, check_yaml, clean_str,
cv2, is_colab, is_kaggle, segments2boxes, xyn2xy, xywh2xyxy, xywhn2xyxy, xyxy2xywhn)
from utils.torch_utils import torch_distributed_zero_first
from pathlib import Path
import ipdb
import torch
import torch.backends.cudnn as cudnn
from model import Model as md
class Ui_MainWindow(object):
def setupUi(self, MainWindow, model):
#self.frame = [] # 存图片
#self.detectFlag = False # 检测flag
#self.cap = []
#self.timer_camera = QTimer() # 定义定时器
self.model = model
self.timer_camera1 = QtCore.QTimer()
self.timer_camera2 = QtCore.QTimer()
self.waring_time = QtCore.QTimer()
self.waring_time.timeout.connect(self.warning_func)
self.timer_camera1.timeout.connect(self.show_camera)
self.timer_camera2.timeout.connect(self.show_camera1)
self.cap = cv.VideoCapture()
self.CAM_NUM = 0
self.waring_flag = True
self.frame_s = 2
self.waring = 0
self.count = 0
self.i = 0
self.u = random.randint(20,50)
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1600, 960)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
#实时监测窗口
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(280, 110, 615, 705))
#self.label.setStyleSheet("background-color: rgb(255, 255, 255);\n""")
self.label.setText("")
self.label.setObjectName("label")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(295, 845, 250, 60))
font = QtGui.QFont()
font.setFamily("Microsoft YaHei")
font.setPointSize(12)
self.pushButton.setFont(font)
self.pushButton.setObjectName("pushButton")
self.pushButton.setFlat(True)
#self.label_2 = QtWidgets.QLabel(self.centralwidget)
#self.label_2.setGeometry(QtCore.QRect(130, 30, 200, 40))
#font = QtGui.QFont()
#font.setFamily("AcadEref")
#font.setPointSize(11)
#self.label_2.setFont(font)
#self.label_2.setStyleSheet("color: rgb(255, 255, 255);\n"
# "font: 87 14pt \"Arial Black\";")
#self.label_2.setObjectName("label_2")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(35, 35, 205, 60))
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_2.setFlat(True)
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_3.setGeometry(QtCore.QRect(35, 110, 205, 60))
self.pushButton_3.setObjectName("pushButton_3")
self.pushButton_3.setFlat(True)
self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_4.setGeometry(QtCore.QRect(35, 260, 205, 60))
self.pushButton_4.setObjectName("pushButton_4")
self.pushButton_4.setFlat(True)
self.pushButton_5 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_5.setGeometry(QtCore.QRect(35, 187, 205, 60))
self.pushButton_5.setObjectName("pushButton_4")
self.pushButton_5.setFlat(True)
self.textBrowser = QtWidgets.QTextBrowser(self.centralwidget)
self.textBrowser.setGeometry(QtCore.QRect(980, 100, 580, 377))
self.textBrowser.setObjectName("textBrowser")
self.textBrowser.setStyleSheet("background-color: rgba(255, 0, 0, 0);\n"
"border:0px;")
#self.label_3 = QtWidgets.QLabel(self.centralwidget)
#self.label_3.setGeometry(QtCore.QRect(1200, 30, 200, 40))
#self.label_3.setStyleSheet("color: rgb(255, 255, 255);\n"
# "font: 87 14pt \"Arial Black\";")
#self.label_3.setObjectName("label_3")
self.label_4 = QtWidgets.QLabel(self.centralwidget)
self.label_4.setGeometry(QtCore.QRect(930, 500, 628, 375))
#self.label_4.setStyleSheet("background-color: rgb(255, 255, 255);\n""")
self.label_4.setText("")
self.label_4.setObjectName("label")
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.pushButton.clicked.connect(self.button_open_camera_click)
self.pushButton_2.clicked.connect(MainWindow.close)
self.pushButton_3.clicked.connect(MainWindow.close)
self.pushButton_4.clicked.connect(MainWindow.close)
self.pushButton_5.clicked.connect(MainWindow.close)
self.setWindowIcon(QIcon(os.getcwd() + '/img/logo.ico'))
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def paintEvent(self, event):
painter = QPainter(self)
pixmap = QPixmap("img/main.jpg")
painter.drawPixmap(self.rect(), pixmap)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "实时监测"))
#self.pushButton.setText(_translate("MainWindow", "连接摄像头"))
#self.label_2.setText(_translate("MainWindow", "实时监控窗口"))
#self.pushButton_2.setText(_translate("MainWindow", "数据分析"))
#self.pushButton_3.setText(_translate("MainWindow", "视频分析"))
#self.pushButton_4.setText(_translate("MainWindow", "退出"))
#self.label_3.setText(_translate("MainWindow", "监测结果输出"))
def printf(self, mes):
self.textBrowser.append(mes) # 在指定的区域显示提示信息
font = QtGui.QFont()
font.setFamily("Microsoft YaHei")
font.setPointSize(18)
self.textBrowser.setFont(font)
self.cursot = self.textBrowser.textCursor()
self.textBrowser.moveCursor(self.cursot.End)
QtWidgets.QApplication.processEvents()
def button_open_camera_click(self):
if self.timer_camera1.isActive() == False and self.timer_camera2.isActive() == False:
flag = self.cap.open('video/MyVideo_1.mp4')
if flag == False:
msg = QtWidgets.QMessageBox.warning(self, u"Warning", u"请检测摄像头与电脑是否连接正确",
buttons=QtWidgets.QMessageBox.Ok,
defaultButton=QtWidgets.QMessageBox.Ok)
else:
self.timer_camera1.start(30)
self.timer_camera2.start(30)
#self.pushButton.setText(u'关闭摄像头')
else:
self.timer_camera1.stop()
self.cap.release()
self.label.clear()
self.label_4.clear()
self.timer_camera2.stop()
self.waring_time.stop()
self.label_4.clear()
#self.pushButton.setText(u'打开摄像头')
def show_camera(self): #摄像头左边
flag, self.image = self.cap.read()
#dir_path=os.getcwd()
#camera_source =dir_path+ "\\data\\test\\2.jpg"
#cv2.imwrite(camera_source, self.image)
frame = cv.cvtColor(self.image, cv.COLOR_BGR2RGB)
height, width, bytesPerComponent = self.image.shape
bytesPerLine = bytesPerComponent * width
q_image = QImage(frame.data, width, height, bytesPerLine, QImage.Format_RGB888).scaled(self.label.width(), self.label.height())
self.label.setPixmap(QtGui.QPixmap.fromImage(q_image))
def show_camera1(self):
flag, self.image1 = self.cap.read()
self.frame_s += 1
if flag==True:
if self.frame_s % 3 == 0: #抽帧
fgMask = self.model.backSub.apply(self.image1)
fgMask = cv.cvtColor(fgMask, cv.COLOR_GRAY2RGB)
frame1 = self.image1
frame2 = self.image1
self.model.framenum = self.model.framenum + 1
img = letterbox(self.image1, self.model.imgsz, stride=self.model.stride, auto=True)[0]
mask = letterbox(fgMask, self.model.imgsz, stride=self.model.stride, auto=True)[0]
# Convert
img = np.concatenate((img, mask), axis=2)
mask = mask.transpose((2, 0, 1))[::-1]
img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
mask = np.ascontiguousarray(mask)
img = np.ascontiguousarray(img)
ma = mask
im = img
ma = torch.from_numpy(ma).to(self.model.device)
im = torch.from_numpy(im).to(self.model.device)
ma = ma.half() if self.model.fp16 else ma.float()
im = im.half() if self.model.fp16 else im.float() # uint8 to fp16/32
ma /= 255
im /= 255 # 0 - 255 to 0.0 - 1.0
if len(im.shape) == 3:
im = im[None] # expand for batch dim
ma = ma[None]
# example shape of img(torch.Size([1, 3, 384, 640]))
# slice_img = []
pred = self.model.model(im, ma, augment=False, visualize=False)
# pred shape[1, x, 6]
pred = non_max_suppression(pred, self.model.conf_thres, self.model.iou_thres, classes=None, agnostic=False, max_det=50)
# import ipdb
bounds = []
for i, det in enumerate(pred):
im0 = self.image1.copy()
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]
if len(det):
initial = True
det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
#print(det)
#print("1")
for *xyxy, conf, cls in reversed(det):
bounds.append((torch.tensor(xyxy).view(1, 4)).view(-1).tolist())
for box in bounds:
self.count += 1
if self.count < 3: continue
frame1 = cv.rectangle(frame1, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), color=self.model.box_color,
thickness=1)
#t = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
#x = time.asctime(t)
#self.printf(str(t) + "发现抛物")
#t = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
Ti = time.strftime('%Y-%m-%d', time.localtime(time.time()))
visual_file_root = os.path.join("history_img", Ti)
if not os.path.exists(visual_file_root):
os.mkdir(visual_file_root)
visual_file = os.path.join(visual_file_root,
"detframe{}.jpg".format(self.model.framenum))
cv.imwrite(visual_file, frame1)
#self.printf(t + "发现抛物")
if self.waring_flag and self.count == 3:
self.waring_flag = False
self.waring_time.start(30)
#if (self.waring != QtWidgets.QMessageBox.Ok):
# self.waring = QtWidgets.QMessageBox.warning(self, u"Warning", u"小心抛物!",
# buttons=QtWidgets.QMessageBox.Ok,
# defaultButton=QtWidgets.QMessageBox.Ok)
#else:
# self.waring = 0
visual_file_root = os.path.join("shishi","1")
if not os.path.exists(visual_file_root):
os.mkdir(visual_file_root)
visual_file = os.path.join(visual_file_root,"detframe{}.jpg".format(self.model.framenum))
cv.imwrite(visual_file, frame1)
video_out_root = os.path.join("shishi", "2")
if not os.path.exists(video_out_root):
os.mkdir(video_out_root)
video_out = os.path.join(video_out_root,"outframe{}.jpg".format(self.model.framenum))
cv.imwrite(video_out, frame1)
height, width, bytesPerComponent = self.image1.shape
bytesPerLine = bytesPerComponent * width
q_image = QImage(self.image1.data, width, height, bytesPerLine, QImage.Format_RGB888).scaled(self.label_4.width(), self.label_4.height())
#print(f"self.video_box.width:{self.video_box.width()}, self.label.width():{self.label.width()}")
#q_image = QImage(frame.data, width, height, bytesPerLine,
# QImage.Format_RGB888).scaled(self.video_box.width(), self.video_box.height())
self.label_4.setPixmap(QPixmap.fromImage(q_image))
def warning_func(self):
t = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
self.printf(t + "发现抛物")
if (self.waring != QtWidgets.QMessageBox.Ok):
self.waring = QtWidgets.QMessageBox.warning(self, u"Warning", u"小心抛物!",
buttons=QtWidgets.QMessageBox.Ok,
defaultButton=QtWidgets.QMessageBox.Ok)
else:
self.waring = 0
self.waring_time.stop()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。