-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ui_step3.bak.py
359 lines (303 loc) · 16.3 KB
/
Ui_step3.bak.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
# -*- 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.timer_camera1.timeout.connect(self.show_camera)
self.timer_camera2.timeout.connect(self.show_camera1)
self.cap = cv.VideoCapture()
self.CAM_NUM = 0
self.frame_s = 2
self.waring = 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(275, 110, 680, 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("AcadEref")
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(980, 500, 580, 377))
#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("AcadEref")
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(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_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.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.image1, cv.COLOR_BGR2RGB)
height, width, bytesPerComponent = self.image1.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 % 1 == 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())
"""
if(conf>0.5):
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("shishi", 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(conf>0.5 and 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
"""
for box in bounds:
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 != 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))
"""
class step4UI(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super(step4UI, self).__init__()
self.setupUi(self)
def main():
QApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
app = QtWidgets.QApplication(sys.argv)
step4 = step4UI()
step4.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
"""