You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

969 lines
57KB

  1. import sys, yaml
  2. from easydict import EasyDict as edict
  3. from concurrent.futures import ThreadPoolExecutor
  4. sys.path.extend(['..','../AIlib2' ])
  5. from AI import AI_process,AI_process_forest,get_postProcess_para,get_postProcess_para_dic,ocr_process,AI_det_track,AI_det_track_batch,AI_det_track_batch_N,get_images_videos,default_mix
  6. import cv2,os,time
  7. from segutils.segmodel import SegModel
  8. from yolov5 import yolov5Model
  9. from stdc import stdcModel
  10. from segutils.trafficUtils import tracfficAccidentMixFunction
  11. from models.experimental import attempt_load
  12. from utils.torch_utils import select_device
  13. from utilsK.queRiver import get_labelnames,get_label_arrays,save_problem_images,riverDetSegMixProcess
  14. from ocrUtils.ocrUtils import CTCLabelConverter,AlignCollate
  15. from trackUtils.sort import Sort,track_draw_boxAndTrace,track_draw_trace_boxes,moving_average_wang,drawBoxTraceSimplied
  16. from trackUtils.sort_obb import OBB_Sort,obbTohbb,track_draw_all_boxes,track_draw_trace
  17. from obbUtils.shipUtils import OBB_infer,OBB_tracker,draw_obb,OBB_tracker_batch
  18. from utilsK.noParkingUtils import mixNoParking_road_postprocess
  19. from obbUtils.load_obb_model import load_model_decoder_OBB
  20. import numpy as np
  21. import torch,glob
  22. import tensorrt as trt
  23. from utilsK.masterUtils import get_needed_objectsIndex
  24. from copy import deepcopy
  25. from scipy import interpolate
  26. from utilsK.drownUtils import mixDrowing_water_postprocess
  27. #import warnings
  28. #warnings.filterwarnings("error")
  29. rainbows=[ [0,0,255],[0,255,0],[255,0,0],[255,0,255],[255,255,0],[255,129,0],[255,0,127],[127,255,0],[0,255,127],[0,127,255],[127,0,255],[255,127,255],[255,255,127],[127,255,255],[0,255,255],[255,127,255],[127,255,255], [0,127,0],[0,0,127],[0,255,255]]
  30. def get_drawPar(par):
  31. labelnames = par['labelnames']
  32. names=get_labelnames(labelnames)
  33. mode_paras=par['detModelpara']
  34. allowedList,allowedList_string=get_needed_objectsIndex(mode_paras)
  35. outfontsize=int(1080/1920*40);###
  36. label_arraylist = get_label_arrays(names,rainbows,outfontsize=par['txtFontSize'],fontpath="../AIlib2/conf/platech.ttf")
  37. drawPar={'names':names,'label_arraylist':label_arraylist,'rainbows':rainbows,'font': par['digitFont'],'allowedList':allowedList}
  38. return drawPar
  39. def view_bar(num, total,time1,prefix='prefix'):
  40. rate = num / total
  41. time_n=time.time()
  42. rate_num = int(rate * 30)
  43. rate_nums = np.round(rate * 100)
  44. r = '\r %s %d / %d [%s%s] %.2f s'%(prefix,num,total, ">" * rate_num, " " * (30 - rate_num), time_n-time1 )
  45. sys.stdout.write(r)
  46. sys.stdout.flush()
  47. '''
  48. 多线程
  49. '''
  50. def process_v1(frame):
  51. #try:
  52. print('demo.py beging to :',frame[8])
  53. time00 = time.time()
  54. H,W,C = frame[0][0].shape
  55. p_result,timeOut = AI_process(frame[0],frame[1],frame[2],frame[3],frame[4],frame[5],objectPar=frame[6],font=frame[7],segPar=frame[9],mode=frame[10],postPar=frame[11])
  56. time11 = time.time()
  57. image_array = p_result[1]
  58. cv2.imwrite(os.path.join('images/results/',frame[8] ) ,image_array)
  59. bname = frame[8].split('.')[0]
  60. if len(p_result)==5:
  61. image_mask = p_result[4]
  62. cv2.imwrite(os.path.join('images/results/',bname+'_mask.png' ) , (image_mask).astype(np.uint8))
  63. boxes=p_result[2]
  64. with open( os.path.join('images/results/',bname+'.txt' ),'w' ) as fp:
  65. for box in boxes:
  66. box_str=[str(x) for x in box]
  67. out_str=','.join(box_str)+'\n'
  68. fp.write(out_str)
  69. time22 = time.time()
  70. print('%s,%d*%d,AI-process: %.1f,image save:%.1f , %s'%(frame[8],H,W, (time11 - time00) * 1000.0, (time22-time11)*1000.0,timeOut), boxes)
  71. return 'success'
  72. #except Exception as e:
  73. # return 'failed:'+str(e)
  74. def process_video(video,par0,mode='detSeg'):
  75. cap=cv2.VideoCapture(video)
  76. if not cap.isOpened():
  77. print('#####error url:',video)
  78. return False
  79. bname=os.path.basename(video).split('.')[0]
  80. fps = int(cap.get(cv2.CAP_PROP_FPS)+0.5)
  81. width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH )+0.5)
  82. height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)+0.5)
  83. framecnt=int(cap.get(7)+0.5)
  84. save_path_AI = os.path.join(par0['outpth'],os.path.basename(video))
  85. problem_image_dir= os.path.join( par0['outpth'], 'probleImages' )
  86. os.makedirs(problem_image_dir,exist_ok=True)
  87. vid_writer_AI = cv2.VideoWriter(save_path_AI, cv2.VideoWriter_fourcc(*'mp4v'), fps, (width,height))
  88. num=0
  89. iframe=0;post_results=[];fpsample=30*10
  90. imgarray_list = []; iframe_list = []
  91. patch_cnt = par0['trackPar']['patchCnt']
  92. ##windowsize 对逐帧插值后的结果做平滑,windowsize为平滑的长度,没隔det_cnt帧做一次跟踪。
  93. trackPar={'det_cnt':10,'windowsize':29 }
  94. ##track_det_result_update= np.empty((0,8)) ###每100帧跑出来的结果,放在track_det_result_update,只保留当前100帧里有的tracker Id.
  95. while cap.isOpened():
  96. ret, imgarray = cap.read() #读取摄像头画面
  97. iframe +=1
  98. if not ret:break
  99. if mode=='detSeg':
  100. p_result,timeOut = AI_process([imgarray],par0['model'],par0['segmodel'],par0['names'],par0['label_arraylist'],par0['rainbows'],objectPar=par0['objectPar'],font=par0['digitFont'],segPar=par0['segPar'])
  101. elif mode == 'track':
  102. #sampleCount=10
  103. imgarray_list.append( imgarray )
  104. iframe_list.append(iframe )
  105. if iframe%patch_cnt==0:
  106. time_patch0 = time.time()
  107. #retResults,timeInfos = AI_det_track_batch(imgarray_list, iframe_list ,par0['modelPar'],par0['processPar'],par0['sort_tracker'] ,par0['trackPar'],segPar=par0['segPar'])
  108. retResults,timeInfos = AI_det_track_batch_N(imgarray_list, iframe_list ,par0['modelList'],par0['postProcess'],par0['sort_tracker'],par0['trackPar'])
  109. #print('###line111:',retResults[2])
  110. ###需要保存成一个二维list,每一个list是一帧检测结果。
  111. ###track_det_result 内容格式:x1, y1, x2, y2, conf, cls,iframe,trackId
  112. time_patch2 = time.time()
  113. frame_min = iframe_list[0];frame_max=iframe_list[-1]
  114. for iiframe in range(frame_min,frame_max+1):
  115. img_draw = imgarray_list[ iiframe- frame_min ]
  116. img_draw = drawBoxTraceSimplied(retResults[1] ,iiframe, img_draw,rainbows=par0['drawPar']['rainbows'],boxFlag=True,traceFlag=True,names=par0['drawPar']['names'] )
  117. ret = vid_writer_AI.write(img_draw)
  118. view_bar(iiframe, framecnt,time.time(),prefix=os.path.basename(video))
  119. imgarray_list=[];iframe_list=[]
  120. elif mode =='obbTrack':
  121. imgarray_list.append( imgarray )
  122. iframe_list.append(iframe )
  123. if iframe%patch_cnt==0:
  124. time_patch0 = time.time()
  125. track_det_results, timeInfos = OBB_tracker_batch(imgarray_list,iframe_list,par0['modelPar'],par0['obbModelPar'],par0['sort_tracker'],par0['trackPar'],segPar=None)
  126. print( timeInfos )
  127. #对结果画图
  128. track_det_np = track_det_results[1]
  129. frame_min = iframe_list[0];frame_max=iframe_list[-1]
  130. for iiframe in range(frame_min,frame_max+1):
  131. img_draw = imgarray_list[ iiframe- frame_min ]
  132. if len( track_det_results[2][ iiframe- frame_min]) > 0:
  133. img_draw = draw_obb( track_det_results[2][iiframe- frame_min ] ,img_draw,par0['drawPar'])
  134. if True:
  135. frameIdex=12;trackIdex=13;
  136. boxes_oneFrame = track_det_np[ track_det_np[:,frameIdex]==iiframe ]
  137. ###在某一帧上,画上轨迹
  138. track_ids = boxes_oneFrame[:,trackIdex].tolist()
  139. boxes_before_oneFrame = track_det_np[ track_det_np[:,frameIdex]<=iiframe ]
  140. for trackId in track_ids:
  141. boxes_before_oneFrame_oneId = boxes_before_oneFrame[boxes_before_oneFrame[:,trackIdex]==trackId]
  142. xcs = boxes_before_oneFrame_oneId[:,8]
  143. ycs = boxes_before_oneFrame_oneId[:,9]
  144. [cv2.line(img_draw, ( int(xcs[i]) , int(ycs[i]) ),
  145. ( int(xcs[i+1]),int(ycs[i+1]) ),(255,0,0), thickness=2)
  146. for i,_ in enumerate(xcs) if i < len(xcs)-1 ]
  147. ret = vid_writer_AI.write(img_draw)
  148. #sys.exit(0)
  149. #print('vide writer ret:',ret)
  150. imgarray_list=[];iframe_list=[]
  151. view_bar(iframe, framecnt,time.time(),prefix=os.path.basename(video))
  152. else:
  153. p_result,timeOut = AI_process_forest([imgarray],par0['model'],par0['segmodel'],par0['names'],par0['label_arraylist'],par0['rainbows'],par0['half'],par0['device'],par0['conf_thres'], par0['iou_thres'],par0['allowedList'],font=par0['digitFont'],trtFlag_det=par0['trtFlag_det'])
  154. if mode not in [ 'track','obbTrack']:
  155. image_array = p_result[1];num+=1
  156. ret = vid_writer_AI.write(image_array)
  157. view_bar(num, framecnt,time.time(),prefix=os.path.basename(video))
  158. ##每隔 fpsample帧处理一次,如果有问题就保存图片
  159. if (iframe % fpsample == 0) and (len(post_results)>0) :
  160. parImage=save_problem_images(post_results,iframe,par0['names'],streamName=bname,outImaDir=problem_image_dir,imageTxtFile=False)
  161. post_results=[]
  162. if len(p_result[2] )>0:
  163. post_results.append(p_result)
  164. vid_writer_AI.release();
  165. def det_track_demo_N(business ):
  166. ####河道巡检的跟踪模型参数
  167. if opt['business'] == 'river' or opt['business'] == 'river2' :
  168. from utilsK.queRiver import riverDetSegMixProcess_N
  169. par={
  170. 'device':'0', ###显卡号,如果用TRT模型,只支持0(单显卡)
  171. 'labelnames':"../AIlib2/weights/conf/%s/labelnames.json"%(opt['business']), ###检测类别对照表
  172. 'max_workers':1, ###并行线程数
  173. 'trackPar':{'sort_max_age':2,'sort_min_hits':3,'sort_iou_thresh':0.2,'det_cnt':10,'windowsize':29,'patchCnt':100},
  174. 'postProcess':{'function':riverDetSegMixProcess_N,'pars':{'slopeIndex':[1,3,4,7], 'riverIou':0.1}}, #分割和检测混合处理的函数
  175. 'models':
  176. [
  177. {
  178. 'weight':"../weights/%s/AIlib2/%s/yolov5_%s_fp16.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###检测模型路径
  179. #'weight':'../AIlib2/weights/conf/%s/yolov5.pt'%(opt['business'] ),
  180. 'name':'yolov5',
  181. 'model':yolov5Model,
  182. 'par':{ 'half':True,'device':'cuda:0' ,'conf_thres':0.25,'iou_thres':0.45,'allowedList':[0,1,2,3],'segRegionCnt':1, 'trtFlag_det':False,'trtFlag_seg':False, "score_byClass":{"0":0.25,"1":0.3,"2":0.3,"3":0.3 } },
  183. },
  184. {
  185. #'weight':"../weights/%s/AIlib2/%s/dmpr_%s.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###检测模型路径
  186. 'weight':'../AIlib2/weights/conf/%s/stdc_360X640.pth'%(opt['business'] ),
  187. 'par':{
  188. 'modelSize':(640,360),'mean':(0.485, 0.456, 0.406),'std' :(0.229, 0.224, 0.225),'numpy':False, 'RGB_convert_first':True,'seg_nclass':2},###分割模型预处理参数
  189. 'model':stdcModel,
  190. 'name':'stdc'
  191. }
  192. ],
  193. 'detModelpara':[{"id":str(x),"config":{"k1":"v1","k2":"v2"}} for x in [0,1,2,3,4,5,6] ],###控制哪些检测类别显示、输出
  194. 'postFile': '../AIlib2/weights/conf/%s/para.json'%( opt['business'] ),###后处理参数文件
  195. 'txtFontSize':80,###文本字符的大小
  196. 'digitFont': { 'line_thickness':2,'boxLine_thickness':1, 'fontSize':1.0,'waterLineColor':(0,255,255),'waterLineWidth':3},###显示框、线设置
  197. #'testImgPath':'images/videos/river',###测试图像的位置
  198. 'testImgPath':'images/river2',###测试图像的位置
  199. 'testOutPath':'images/results/',###输出测试图像位置
  200. }
  201. if opt['business'] == 'highWay2':
  202. from segutils.trafficUtils import tracfficAccidentMixFunction_N
  203. par={
  204. 'device':'0', ###显卡号,如果用TRT模型,只支持0(单显卡)
  205. 'labelnames':"../AIlib2/weights/conf/%s/labelnames.json"%( opt['business'] ), ###检测类别对照表
  206. 'max_workers':1, ###并行线程数
  207. 'trackPar':{'sort_max_age':2,'sort_min_hits':3,'sort_iou_thresh':0.2,'det_cnt':5,'windowsize':29,'patchCnt':100},
  208. 'postProcess':{'function':tracfficAccidentMixFunction_N,
  209. 'pars':{ 'RoadArea': 16000, 'vehicleArea': 10, 'roadVehicleAngle': 15, 'speedRoadVehicleAngleMax': 75,'radius': 50 , 'roundness': 1.0, 'cls': 9, 'vehicleFactor': 0.1,'cls':9, 'confThres':0.25,'roadIou':0.6,'vehicleFlag':False,'distanceFlag': False }
  210. },
  211. 'models':
  212. [
  213. {
  214. 'weight':"../weights/%s/AIlib2/%s/yolov5_%s_fp16.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###检测模型路径
  215. #'weight':'../AIlib2/weights/conf/%s/yolov5.pt'%(opt['business'] ),
  216. 'name':'yolov5',
  217. 'model':yolov5Model,
  218. 'par':{ 'half':True,'device':'cuda:0' ,'conf_thres':0.25,'iou_thres':0.45,'allowedList':[0,1,2,3],'segRegionCnt':1, 'trtFlag_det':False,'trtFlag_seg':False, "score_byClass":{"0":0.25,"1":0.3,"2":0.3,"3":0.3 } },
  219. },
  220. {
  221. #'weight':"../weights/%s/AIlib2/%s/dmpr_%s.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###检测模型路径
  222. 'weight':'../AIlib2/weights/conf/%s/stdc_360X640.pth'%(opt['business'] ),
  223. 'par':{
  224. 'modelSize':(640,360),'mean':(0.485, 0.456, 0.406),'std' :(0.229, 0.224, 0.225),'predResize':True,'numpy':False, 'RGB_convert_first':True,'seg_nclass':3},###分割模型预处理参数
  225. 'model':stdcModel,
  226. 'name':'stdc'
  227. }
  228. ],
  229. 'detModelpara':[{"id":str(x),"config":{"k1":"v1","k2":"v2"}} for x in [0,1,2,3,5,6,7,8,9] ],###控制哪些检测类别显示、输出
  230. 'postFile': '../AIlib2/weights/conf/%s/para.json'%(opt['business'] ),###后处理参数文件
  231. 'txtFontSize':20,###文本字符的大小
  232. 'digitFont': { 'line_thickness':2,'boxLine_thickness':1, 'fontSize':0.5,'waterLineColor':(0,255,255),'segLineShow':True,'waterLineWidth':2},###显示框、线设置
  233. #'testImgPath':'images/trafficAccident/8.png',###测试图像的位置
  234. 'testImgPath':'/home/chenyukun/777-7-42.mp4',###测试图像的位置
  235. 'testOutPath':'images/results/',###输出测试图像位置
  236. }
  237. par['postProcess']['pars']['modelSize'] = par['models'][1]['par']['modelSize']
  238. if opt['business'] == 'noParking':
  239. from utilsK.noParkingUtils import mixNoParking_road_postprocess_N
  240. par={
  241. 'device':'0', ###显卡号,如果用TRT模型,只支持0(单显卡)
  242. 'labelnames':"../AIlib2/weights/conf/%s/labelnames.json"%( opt['business'] ), ###检测类别对照表
  243. 'max_workers':1, ###并行线程数
  244. 'trackPar':{'sort_max_age':2,'sort_min_hits':3,'sort_iou_thresh':0.2,'det_cnt':10,'windowsize':29,'patchCnt':100},
  245. 'postProcess':{'function':mixNoParking_road_postprocess_N,
  246. 'pars': { 'roundness': 0.3, 'cls': 9, 'laneArea': 10, 'laneAngleCha': 5 ,'RoadArea': 16000,'fitOrder':2}
  247. } ,
  248. 'models':
  249. [
  250. {
  251. 'weight':"../weights/%s/AIlib2/%s/yolov5_%s_fp16.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###检测模型路径
  252. #'weight':'../AIlib2/weights/conf/%s/yolov5.pt'%(opt['business'] ),
  253. 'name':'yolov5',
  254. 'model':yolov5Model,
  255. 'par':{ 'half':True,'device':'cuda:0' ,'conf_thres':0.25,'iou_thres':0.45,'allowedList':[0,1,2,3],'segRegionCnt':1, 'trtFlag_det':False,'trtFlag_seg':False, "score_byClass":{"0":0.25,"1":0.3,"2":0.3,"3":0.3 } },
  256. },
  257. {
  258. #'weight':"../weights/%s/AIlib2/%s/dmpr_%s.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###检测模型路径
  259. 'weight':'../AIlib2/weights/conf/%s/stdc_360X640.pth'%(opt['business'] ),
  260. 'par':{
  261. 'modelSize':(640,360),'mean':(0.485, 0.456, 0.406),'std' :(0.229, 0.224, 0.225),'predResize':True,'numpy':False, 'RGB_convert_first':True,'seg_nclass':4},###分割模型预处理参数
  262. 'model':stdcModel,
  263. 'name':'stdc'
  264. }
  265. ],
  266. 'detModelpara':[{"id":str(x),"config":{"k1":"v1","k2":"v2"}} for x in [0,1,2,3,5,6,7,8,9] ],###控制哪些检测类别显示、输出
  267. 'postFile': '../AIlib2/weights/conf/%s/para.json'%('highWay2' ),###后处理参数文件
  268. 'txtFontSize':20,###文本字符的大小
  269. 'digitFont': { 'line_thickness':2,'boxLine_thickness':1, 'fontSize':1.0,'waterLineColor':(0,255,255),'segLineShow':True,'waterLineWidth':2},###显示框、线设置
  270. 'testImgPath':'images/noParking/',###测试图像的位置
  271. 'testOutPath':'images/results/',###输出测试图像位置
  272. }
  273. par['postProcess']['pars']['modelSize'] = par['models'][1]['par']['modelSize']
  274. if opt['business'] == 'drowning':
  275. from utilsK.drownUtils import mixDrowing_water_postprocess_N
  276. par={
  277. 'device':'0', ###显卡号,如果用TRT模型,只支持0(单显卡)
  278. 'labelnames':"../AIlib2/weights/conf/%s/labelnames.json"%( opt['business'] ), ###检测类别对照表
  279. 'max_workers':1, ###并行线程数
  280. 'trackPar':{'sort_max_age':2,'sort_min_hits':3,'sort_iou_thresh':0.2,'det_cnt':10,'windowsize':29,'patchCnt':100},
  281. 'postProcess':{'function':mixDrowing_water_postprocess_N,
  282. 'pars':{ }},
  283. 'models':
  284. [
  285. {
  286. 'weight':"../weights/%s/AIlib2/%s/yolov5_%s_fp16.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###检测模型路径
  287. #'weight':'../AIlib2/weights/conf/%s/yolov5.pt'%(opt['business'] ),
  288. 'name':'yolov5',
  289. 'model':yolov5Model,
  290. 'par':{ 'half':True,'device':'cuda:0' ,'conf_thres':0.25,'iou_thres':0.45,'allowedList':[0,1,2,3],'segRegionCnt':1, 'trtFlag_det':False,'trtFlag_seg':False, "score_byClass":{"0":0.25,"1":0.3,"2":0.3,"3":0.3 } },
  291. },
  292. {
  293. #'weight':"../weights/%s/AIlib2/%s/dmpr_%s.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###检测模型路径
  294. 'weight':'../AIlib2/weights/conf/%s/stdc_360X640.pth'%(opt['business'] ),
  295. 'par':{
  296. 'modelSize':(640,360),'mean':(0.485, 0.456, 0.406),'std' :(0.229, 0.224, 0.225),'predResize':True,'numpy':False, 'RGB_convert_first':True,'seg_nclass':2},###分割模型预处理参数
  297. 'model':stdcModel,
  298. 'name':'stdc'
  299. }
  300. ],
  301. 'detModelpara':[{"id":str(x),"config":{"k1":"v1","k2":"v2"}} for x in [0,1,2,3,5,6,7,8,9] ],###控制哪些检测类别显示、输出
  302. 'postFile': '../AIlib2/weights/conf/%s/para.json'%('highWay2' ),###后处理参数文件
  303. 'txtFontSize':20,###文本字符的大小
  304. 'digitFont': { 'line_thickness':2,'boxLine_thickness':1, 'fontSize':1.0,'waterLineColor':(0,255,255),'segLineShow':True,'waterLineWidth':2},###显示框、线设置
  305. 'testImgPath':'images/drowning/',###测试图像的位置
  306. 'testOutPath':'images/results/',###输出测试图像位置
  307. }
  308. par['postProcess']['pars']['modelSize'] = par['models'][1]['par']['modelSize']
  309. if opt['business'] == 'cityMangement2':
  310. from DMPR import DMPRModel
  311. from DMPRUtils.jointUtil import dmpr_yolo_stdc
  312. par={
  313. 'device':'0', ###显卡号,如果用TRT模型,只支持0(单显卡)
  314. 'labelnames':"../AIlib2/weights/conf/%s/labelnames.json"%(opt['business']), ###检测类别对照表
  315. 'max_workers':1, ###并行线程数
  316. 'trackPar':{'sort_max_age':2,'sort_min_hits':3,'sort_iou_thresh':0.2,'det_cnt':10,'windowsize':29,'patchCnt':100},
  317. 'postProcess':{
  318. 'function':dmpr_yolo_stdc,
  319. 'pars':{'carCls':0 ,'illCls':3,'scaleRatio':0.5,'border':80}
  320. },
  321. 'models':
  322. [
  323. {
  324. #'weight':"../weights/%s/AIlib2/%s/yolov5_%s_fp16.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###检测模型路径
  325. 'weight':'../AIlib2/weights/conf/%s/yolov5.pt'%(opt['business'] ),
  326. 'name':'yolov5',
  327. 'model':yolov5Model,
  328. 'par':{ 'half':True,'device':'cuda:0' ,'conf_thres':0.25,'iou_thres':0.45,'allowedList':[0,1,2,3],'segRegionCnt':1, 'trtFlag_det':False,'trtFlag_seg':False, "score_byClass":{"0":0.25,"1":0.3,"2":0.3,"3":0.3 } }
  329. },
  330. {
  331. #'weight':"../weights/%s/AIlib2/%s/dmpr_%s.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###检测模型路径
  332. 'weight':'../AIlib2/weights/conf/%s/dmpr.pth'%(opt['business'] ),
  333. 'par':{
  334. 'depth_factor':32,'NUM_FEATURE_MAP_CHANNEL':6,'dmpr_thresh':0.3, 'dmprimg_size':640,
  335. 'name':'dmpr'
  336. },
  337. 'model':DMPRModel,
  338. 'name':'dmpr'
  339. }
  340. ] ,
  341. 'detModelpara':[{"id":str(x),"config":{"k1":"v1","k2":"v2"}} for x in [0,1,2,3,5,6,7,8,9] ],###控制哪些检测类别显示、输出
  342. 'postFile': '../AIlib2/weights/conf/%s/para.json'%(opt['business'] ),###后处理参数文件
  343. 'txtFontSize':20,###文本字符的大小
  344. 'digitFont': { 'line_thickness':2,'boxLine_thickness':1, 'fontSize':1.0,'waterLineColor':(0,255,255),'segLineShow':True,'waterLineWidth':2},###显示框、线设置
  345. #'testImgPath':'/mnt/thsw2/DSP2/demoImages/illParking',###测试图像的位置
  346. 'testImgPath':'/mnt/thsw2/DSP2/weights/cityMangement2_0916/images/input',
  347. #'testImgPath':'images/cityMangement/',
  348. 'testOutPath':'images/results/',###输出测试图像位置
  349. }
  350. if opt['business'] == 'cityMangement3':
  351. from DMPR import DMPRModel
  352. from DMPRUtils.jointUtil import dmpr_yolo_stdc
  353. par={
  354. 'device':'0', ###显卡号,如果用TRT模型,只支持0(单显卡)
  355. 'labelnames':"../AIlib2/weights/conf/%s/labelnames.json"%(opt['business']), ###检测类别对照表
  356. 'max_workers':1, ###并行线程数
  357. 'trackPar':{'sort_max_age':2,'sort_min_hits':3,'sort_iou_thresh':0.2,'det_cnt':10,'windowsize':29,'patchCnt':100},
  358. 'postProcess':{
  359. 'function':dmpr_yolo_stdc,
  360. 'pars':{'carCls':0 ,'illCls':3,'scaleRatio':0.5,'border':80}
  361. },
  362. 'models':[
  363. {
  364. 'weight':"../weights/%s/AIlib2/%s/yolov5_%s_fp16.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###检测模型路径
  365. #'weight':'../AIlib2/weights/conf/%s/yolov5.pt'%(opt['business'] ),
  366. 'name':'yolov5',
  367. 'model':yolov5Model,
  368. 'par':{ 'half':True,'device':'cuda:0' ,'conf_thres':0.25,'iou_thres':0.45,'allowedList':[0,1,2,3],'segRegionCnt':1, 'trtFlag_det':False,'trtFlag_seg':False, "score_byClass":{"0":0.25,"1":0.3,"2":0.3,"3":0.3 } }
  369. },
  370. {
  371. 'weight':"../weights/%s/AIlib2/%s/dmpr_%s.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###DMPR模型路径
  372. #'weight':'../AIlib2/weights/conf/%s/dmpr.pth'%(opt['business'] ),
  373. 'par':{
  374. 'depth_factor':32,'NUM_FEATURE_MAP_CHANNEL':6,'dmpr_thresh':0.3, 'dmprimg_size':640,
  375. 'name':'dmpr'
  376. },
  377. 'model':DMPRModel,
  378. 'name':'dmpr'
  379. },
  380. {
  381. 'weight':"../weights/%s/AIlib2/%s/stdc_360X640_%s_fp16.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###分割模型路径
  382. #'weight':'../AIlib2/weights/conf/%s/stdc_360X640.pth'%(opt['business'] ),
  383. 'par':{
  384. 'modelSize':(640,360),'mean':(0.485, 0.456, 0.406),'std' :(0.229, 0.224, 0.225),'predResize':True,'numpy':False, 'RGB_convert_first':True,'seg_nclass':2},###分割模型预处理参数
  385. 'model':stdcModel,
  386. 'name':'stdc'
  387. }
  388. ],
  389. 'detModelpara':[{"id":str(x),"config":{"k1":"v1","k2":"v2"}} for x in [0,1,2,3,5,6,7,8,9] ],###控制哪些检测类别显示、输出
  390. 'postFile': '../AIlib2/weights/conf/%s/para.json'%(opt['business'] ),###后处理参数文件
  391. 'txtFontSize':20,###文本字符的大小
  392. 'digitFont': { 'line_thickness':2,'boxLine_thickness':1, 'fontSize':1.0,'waterLineColor':(0,255,255),'segLineShow':True,'waterLineWidth':2},###显示框、线设置
  393. #'testImgPath':'images/%s/'%(opt['business']),
  394. 'testImgPath':'/mnt/thsw2/DSP2/weights/cityMangement3/images/debug',
  395. 'testOutPath':'images/results/',###输出测试图像位置
  396. }
  397. if opt['business'] == 'forest2':
  398. par={
  399. 'device':'0', ###显卡号,如果用TRT模型,只支持0(单显卡)
  400. 'labelnames':"../AIlib2/weights/conf/forest2/labelnames.json", ###检测类别对照表
  401. 'max_workers':1, ###并行线程数
  402. 'trackPar':{'sort_max_age':2,'sort_min_hits':3,'sort_iou_thresh':0.2,'det_cnt':10,'windowsize':29,'patchCnt':100},
  403. 'postProcess':{'function':default_mix,'pars':{ }},
  404. 'models':
  405. [
  406. {
  407. 'weight':"../weights/%s/AIlib2/%s/yolov5_%s_fp16.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###检测模型路径
  408. #'weight':'../AIlib2/weights/conf/%s/yolov5.pt'%(opt['business'] ),
  409. 'name':'yolov5',
  410. 'model':yolov5Model,
  411. 'par':{ 'half':True,'device':'cuda:0' ,'conf_thres':0.25,'iou_thres':0.45,'allowedList':[0,1,2,3],'segRegionCnt':1, 'trtFlag_det':False,'trtFlag_seg':False, "score_byClass":{"0":0.25,"1":0.3,"2":0.3,"3":0.3 } },
  412. }
  413. ],
  414. 'detModelpara':[{"id":str(x),"config":{"k1":"v1","k2":"v2"}} for x in [] ],
  415. 'postFile': '../AIlib2/weights/conf/forest/para.json',###后处理参数文件
  416. 'txtFontSize':80,###文本字符的大小
  417. 'digitFont': { 'line_thickness':2,'boxLine_thickness':1, 'fontSize':1.0,'waterLineColor':(0,255,255),'waterLineWidth':3},###显示框、线设置
  418. 'testImgPath':'../AIdemo2/images/forest2/',###测试图像的位置
  419. 'testOutPath':'images/results/',###输出测试图像位置
  420. }
  421. ###车辆巡检参数
  422. if opt['business'] == 'vehicle':
  423. par={
  424. 'device':'0', ###显卡号,如果用TRT模型,只支持0(单显卡)
  425. 'labelnames':"../AIlib2/weights/conf/vehicle/labelnames.json", ###检测类别对照表
  426. 'max_workers':1, ###并行线程数
  427. 'trackPar':{'sort_max_age':2,'sort_min_hits':3,'sort_iou_thresh':0.2,'det_cnt':10,'windowsize':29,'patchCnt':100},
  428. 'postProcess':{'function':default_mix,'pars':{ }},
  429. 'models':
  430. [
  431. {
  432. 'weight':"../weights/%s/AIlib2/%s/yolov5_%s_fp16.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###检测模型路径
  433. #'weight':'../AIlib2/weights/conf/%s/yolov5.pt'%(opt['business'] ),
  434. 'name':'yolov5',
  435. 'model':yolov5Model,
  436. 'par':{ 'half':True,'device':'cuda:0' ,'conf_thres':0.25,'iou_thres':0.45,'allowedList':[0,1,2,3],'segRegionCnt':1, 'trtFlag_det':False,'trtFlag_seg':False, "score_byClass":{"0":0.25,"1":0.3,"2":0.3,"3":0.3 } },
  437. }
  438. ],
  439. 'detModelpara':[{"id":str(x),"config":{"k1":"v1","k2":"v2"}} for x in [0,1,2,3,4,5,6] ],###控制哪些检测类别显示、输出
  440. 'postFile': '../AIlib2/weights/conf/vehicle/para.json',###后处理参数文件
  441. 'txtFontSize':40,###文本字符的大小
  442. 'digitFont': { 'line_thickness':2,'boxLine_thickness':1, 'fontSize':1.0,'waterLineColor':(0,255,255),'waterLineWidth':3},###显示框、线设置
  443. 'testImgPath':'images/vehicle/',###测试图像的位置
  444. 'testOutPath':'images/results/',###输出测试图像位置
  445. }
  446. ###行人检测模型
  447. if opt['business'] == 'pedestrian':
  448. par={
  449. 'device':'0', ###显卡号,如果用TRT模型,只支持0(单显卡)
  450. 'labelnames':"../AIlib2/weights/conf/pedestrian/labelnames.json", ###检测类别对照表
  451. 'max_workers':1, ###并行线程数
  452. 'trackPar':{'sort_max_age':2,'sort_min_hits':3,'sort_iou_thresh':0.2,'det_cnt':10,'windowsize':29,'patchCnt':100},
  453. 'postProcess':{'function':default_mix,'pars':{ }},
  454. 'models':
  455. [
  456. {
  457. 'weight':"../weights/%s/AIlib2/%s/yolov5_%s_fp16.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###检测模型路径
  458. #'weight':'../AIlib2/weights/conf/%s/yolov5.pt'%(opt['business'] ),
  459. 'name':'yolov5',
  460. 'model':yolov5Model,
  461. 'par':{ 'half':True,'device':'cuda:0' ,'conf_thres':0.25,'iou_thres':0.45,'allowedList':[0,1,2,3],'segRegionCnt':1, 'trtFlag_det':False,'trtFlag_seg':False, "score_byClass":{"0":0.25,"1":0.3,"2":0.3,"3":0.3 } },
  462. }
  463. ],
  464. 'detModelpara':[{"id":str(x),"config":{"k1":"v1","k2":"v2"}} for x in [0,1,2,3,4,5,6] ],###控制哪些检测类别显示、输出
  465. 'postFile': '../AIlib2/weights/conf/pedestrian/para.json',###后处理参数文件
  466. 'txtFontSize':40,###文本字符的大小
  467. 'digitFont': { 'line_thickness':2,'boxLine_thickness':1, 'fontSize':1.0,'waterLineColor':(0,255,255),'waterLineWidth':3},###显示框、线设置
  468. 'testImgPath':'../AIdemo2/images/pedestrian/',###测试图像的位置
  469. 'testOutPath':'images/results/',###输出测试图像位置
  470. }
  471. if opt['business'] == 'smogfire':
  472. par={
  473. 'device':'0', ###显卡号,如果用TRT模型,只支持0(单显卡)
  474. 'labelnames':"../AIlib2/weights/conf/smogfire/labelnames.json", ###检测类别对照表
  475. 'max_workers':1, ###并行线程数
  476. 'trackPar':{'sort_max_age':2,'sort_min_hits':3,'sort_iou_thresh':0.2,'det_cnt':10,'windowsize':29,'patchCnt':100},
  477. 'postProcess':{'function':default_mix,'pars':{ }},
  478. 'models':
  479. [
  480. {
  481. 'weight':"../weights/%s/AIlib2/%s/yolov5_%s_fp16.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###检测模型路径
  482. #'weight':'../AIlib2/weights/conf/%s/yolov5.pt'%(opt['business'] ),
  483. 'name':'yolov5',
  484. 'model':yolov5Model,
  485. 'par':{ 'half':True,'device':'cuda:0' ,'conf_thres':0.25,'iou_thres':0.45,'allowedList':[0,1,2,3],'segRegionCnt':1, 'trtFlag_det':False,'trtFlag_seg':False, "score_byClass":{"0":0.25,"1":0.3,"2":0.3,"3":0.3 } },
  486. }
  487. ],
  488. 'detModelpara':[{"id":str(x),"config":{"k1":"v1","k2":"v2"}} for x in [0,1,2,3,4,5,6] ],###控制哪些检测类别显示、输出
  489. 'postFile': '../AIlib2/weights/conf/smogfire/para.json',###后处理参数文件
  490. 'txtFontSize':40,###文本字符的大小
  491. 'digitFont': { 'line_thickness':2,'boxLine_thickness':1, 'fontSize':1.0,'waterLineColor':(0,255,255),'waterLineWidth':3},###显示框、线设置
  492. 'testImgPath':'../AIdemo2/images/smogfire/',###测试图像的位置
  493. 'testOutPath':'images/results/',###输出测试图像位置
  494. }
  495. ###钓鱼游泳检测
  496. if opt['business'] == 'AnglerSwimmer':
  497. par={
  498. 'device':'0', ###显卡号,如果用TRT模型,只支持0(单显卡)
  499. 'labelnames':"../AIlib2/weights/conf/AnglerSwimmer/labelnames.json", ###检测类别对照表
  500. 'max_workers':1, ###并行线程数
  501. 'trackPar':{'sort_max_age':2,'sort_min_hits':3,'sort_iou_thresh':0.2,'det_cnt':10,'windowsize':29,'patchCnt':100},
  502. 'postProcess':{'function':default_mix,'pars':{ }},
  503. 'models':
  504. [
  505. {
  506. 'weight':"../weights/%s/AIlib2/%s/yolov5_%s_fp16.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###检测模型路径
  507. #'weight':'../AIlib2/weights/conf/%s/yolov5.pt'%(opt['business'] ),
  508. 'name':'yolov5',
  509. 'model':yolov5Model,
  510. 'par':{ 'half':True,'device':'cuda:0' ,'conf_thres':0.25,'iou_thres':0.45,'allowedList':[0,1,2,3],'segRegionCnt':1, 'trtFlag_det':False,'trtFlag_seg':False, "score_byClass":{"0":0.25,"1":0.3,"2":0.3,"3":0.3 } },
  511. }
  512. ],
  513. 'detModelpara':[{"id":str(x),"config":{"k1":"v1","k2":"v2"}} for x in [0,1,2,3,4,5,6] ],###控制哪些检测类别显示、输出
  514. 'postFile': '../AIlib2/weights/conf/AnglerSwimmer/para.json',###后处理参数文件
  515. 'txtFontSize':40,###文本字符的大小
  516. 'digitFont': { 'line_thickness':2,'boxLine_thickness':1, 'fontSize':1.0,'waterLineColor':(0,255,255),'waterLineWidth':3},###显示框、线设置
  517. 'testImgPath':'../AIdemo2/images/AnglerSwimmer/',###测试图像的位置
  518. 'testOutPath':'images/results/',###输出测试图像位置
  519. }
  520. ###航道应急,做落水人员检测, channelEmergency
  521. if opt['business'] == 'channelEmergency':
  522. par={
  523. 'device':'0', ###显卡号,如果用TRT模型,只支持0(单显卡)
  524. 'labelnames':"../AIlib2/weights/conf/channelEmergency/labelnames.json", ###检测类别对照表
  525. 'max_workers':1, ###并行线程数
  526. 'trackPar':{'sort_max_age':2,'sort_min_hits':3,'sort_iou_thresh':0.2,'det_cnt':10,'windowsize':29,'patchCnt':100},
  527. 'postProcess':{'function':default_mix,'pars':{ }},
  528. 'models':
  529. [
  530. {
  531. 'weight':"../weights/%s/AIlib2/%s/yolov5_%s_fp16.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###检测模型路径
  532. #'weight':'../AIlib2/weights/conf/%s/yolov5.pt'%(opt['business'] ),
  533. 'name':'yolov5',
  534. 'model':yolov5Model,
  535. 'par':{ 'half':True,'device':'cuda:0' ,'conf_thres':0.25,'iou_thres':0.45,'allowedList':[0,1,2,3],'segRegionCnt':1, 'trtFlag_det':False,'trtFlag_seg':False, "score_byClass":{"0":0.25,"1":0.3,"2":0.3,"3":0.3 } },
  536. }
  537. ],
  538. 'detModelpara':[{"id":str(x),"config":{"k1":"v1","k2":"v2"}} for x in [] ],###控制哪些检测类别显示、输出
  539. 'postFile': '../AIlib2/weights/conf/channelEmergency/para.json',###后处理参数文件
  540. 'txtFontSize':40,###文本字符的大小
  541. 'digitFont': { 'line_thickness':2,'boxLine_thickness':1, 'fontSize':1.0,'waterLineColor':(0,255,255),'waterLineWidth':3},###显示框、线设置
  542. 'testImgPath':'../AIdemo2/images/channelEmergency/',###测试图像的位置
  543. 'testOutPath':'images/results/',###输出测试图像位置
  544. }
  545. ###乡村路违法种植
  546. if opt['business'] == 'countryRoad':
  547. par={
  548. 'device':'0', ###显卡号,如果用TRT模型,只支持0(单显卡)
  549. 'labelnames':"../AIlib2/weights/conf/countryRoad/labelnames.json", ###检测类别对照表
  550. 'max_workers':1, ###并行线程数
  551. 'trackPar':{'sort_max_age':2,'sort_min_hits':3,'sort_iou_thresh':0.2,'det_cnt':10,'windowsize':29,'patchCnt':100},
  552. 'postProcess':{'function':default_mix,'pars':{ }},
  553. 'models':
  554. [
  555. {
  556. 'weight':"../weights/%s/AIlib2/%s/yolov5_%s_fp16.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###检测模型路径
  557. #'weight':'../AIlib2/weights/conf/%s/yolov5.pt'%(opt['business'] ),
  558. 'name':'yolov5',
  559. 'model':yolov5Model,
  560. 'par':{ 'half':True,'device':'cuda:0' ,'conf_thres':0.25,'iou_thres':0.45,'allowedList':[0,1,2,3],'segRegionCnt':1, 'trtFlag_det':False,'trtFlag_seg':False, "score_byClass":{"0":0.25,"1":0.3,"2":0.3,"3":0.3 } },
  561. }
  562. ],
  563. 'detModelpara':[{"id":str(x),"config":{"k1":"v1","k2":"v2"}} for x in [0,1,2,3,4,5,6] ],###控制哪些检测类别显示、输出
  564. 'postFile': '../AIlib2/weights/conf/countryRoad/para.json',###后处理参数文件
  565. 'txtFontSize':40,###文本字符的大小
  566. 'digitFont': { 'line_thickness':2,'boxLine_thickness':1, 'fontSize':1.0,'waterLineColor':(0,255,255),'waterLineWidth':3},###显示框、线设置
  567. 'testImgPath':'../AIdemo2/images/countryRoad/',###测试图像的位置
  568. 'testOutPath':'images/results/',###输出测试图像位置
  569. }
  570. ###城管项目,检测城市垃圾和车辆
  571. if opt['business'] == 'cityMangement':
  572. par={
  573. 'device':'0', ###显卡号,如果用TRT模型,只支持0(单显卡)
  574. 'labelnames':"../AIlib2/weights/conf/%s/labelnames.json"%(opt['business']), ###检测类别对照表
  575. 'max_workers':1, ###并行线程数
  576. 'trackPar':{'sort_max_age':2,'sort_min_hits':3,'sort_iou_thresh':0.2,'det_cnt':10,'windowsize':29,'patchCnt':100},
  577. 'postProcess':{'function':default_mix,'pars':{ }},
  578. 'models':
  579. [
  580. {
  581. 'weight':"../weights/%s/AIlib2/%s/yolov5_%s_fp16.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###检测模型路径
  582. #'weight':'../AIlib2/weights/conf/%s/yolov5.pt'%(opt['business'] ),
  583. 'name':'yolov5',
  584. 'model':yolov5Model,
  585. 'par':{ 'half':True,'device':'cuda:0' ,'conf_thres':0.25,'iou_thres':0.45,'allowedList':[0,1,2,3],'segRegionCnt':1, 'trtFlag_det':False,'trtFlag_seg':False, "score_byClass":{"0":0.25,"1":0.3,"2":0.3,"3":0.3 } },
  586. }
  587. ],
  588. 'detModelpara':[{"id":str(x),"config":{"k1":"v1","k2":"v2"}} for x in [0,1,2,3,4,5,6] ],###控制哪些检测类别显示、输出
  589. 'postFile': '../AIlib2/weights/conf/%s/para.json'%(opt['business']),###后处理参数文件
  590. 'txtFontSize':40,###文本字符的大小
  591. 'digitFont': { 'line_thickness':2,'boxLine_thickness':1, 'fontSize':1.0,'waterLineColor':(0,255,255),'waterLineWidth':3},###显示框、线设置
  592. 'testImgPath':'images/cityMangement',###测试图像的位置
  593. 'testOutPath':'images/results/',###输出测试图像位置
  594. }
  595. ###城管项目,检测道路情况,输入类别为五个:"护栏","交通标志","非交通标志","施工","施工“(第4,第5类别合并,名称相同)
  596. ###实际模型检测输出的类别为:"护栏","交通标志","非交通标志","锥桶","水马"
  597. if opt['business'] == 'cityRoad':
  598. par={
  599. 'device':'0', ###显卡号,如果用TRT模型,只支持0(单显卡)
  600. 'labelnames':"../AIlib2/weights/conf/%s/labelnames.json"%(opt['business']), ###检测类别对照表
  601. 'max_workers':1, ###并行线程数
  602. 'trackPar':{'sort_max_age':2,'sort_min_hits':3,'sort_iou_thresh':0.2,'det_cnt':10,'windowsize':29,'patchCnt':100},
  603. 'postProcess':{'function':default_mix,'pars':{ }},
  604. 'models':
  605. [
  606. {
  607. 'weight':"../weights/%s/AIlib2/%s/yolov5_%s_fp16.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###检测模型路径
  608. #'weight':'../AIlib2/weights/conf/%s/yolov5.pt'%(opt['business'] ),
  609. 'name':'yolov5',
  610. 'model':yolov5Model,
  611. 'par':{ 'half':True,'device':'cuda:0' ,'conf_thres':0.25,'iou_thres':0.45,'allowedList':[0,1,2,3],'segRegionCnt':1, 'trtFlag_det':False,'trtFlag_seg':False, "score_byClass":{"0":0.25,"1":0.3,"2":0.3,"3":0.3 } },
  612. }
  613. ],
  614. 'detModelpara':[{"id":str(x),"config":{"k1":"v1","k2":"v2"}} for x in [0,1,2,3,4,5,6] ],###控制哪些检测类别显示、输出
  615. 'postFile': '../AIlib2/weights/conf/%s/para.json'%(opt['business']),###后处理参数文件
  616. 'txtFontSize':40,###文本字符的大小
  617. 'digitFont': { 'line_thickness':2,'boxLine_thickness':1, 'fontSize':1.0,'waterLineColor':(0,255,255),'waterLineWidth':3},###显示框、线设置
  618. 'testImgPath':'images/%s'%(opt['business']),###测试图像的位置
  619. 'testOutPath':'images/results/',###输出测试图像位置
  620. }
  621. if opt['business'] == 'illParking':
  622. from utilsK.illParkingUtils import illParking_postprocess_N
  623. par={
  624. 'device':'0', ###显卡号,如果用TRT模型,只支持0(单显卡)
  625. 'labelnames':"../AIlib2/weights/conf/%s/labelnames.json"%(opt['business']), ###检测类别对照表
  626. 'trackPar':{'sort_max_age':2,'sort_min_hits':3,'sort_iou_thresh':0.2,'det_cnt':10,'windowsize':29,'patchCnt':100},
  627. 'postProcess':{'function':illParking_postprocess_N, 'pars':{ }},
  628. 'models':
  629. [
  630. {
  631. 'weight':"../weights/%s/AIlib2/%s/yolov5_%s_fp16.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###检测模型路径
  632. #'weight':'../AIlib2/weights/conf/%s/yolov5.pt'%(opt['business'] ),
  633. 'name':'yolov5',
  634. 'model':yolov5Model,
  635. 'par':{ 'half':True,'device':'cuda:0' ,'conf_thres':0.25,'iou_thres':0.45,'allowedList':[0,1,2,3],'segRegionCnt':1, 'trtFlag_det':False,'trtFlag_seg':False, "score_byClass":{"0":0.25,"1":0.3,"2":0.3,"3":0.3 } },
  636. }
  637. ],
  638. 'detModelpara':[{"id":str(x),"config":{"k1":"v1","k2":"v2"}} for x in [0,1,2,3,5,6,7,8,9] ],###控制哪些检测类别显示、输出
  639. 'postFile': '../AIlib2/weights/conf/%s/para.json'%(opt['business'] ),###后处理参数文件
  640. 'txtFontSize':20,###文本字符的大小
  641. 'digitFont': { 'line_thickness':2,'boxLine_thickness':1, 'fontSize':1.0,'waterLineColor':(0,255,255),'waterLineWidth':2},###显示框、线设置
  642. 'testImgPath':'images/cityMangement',###测试图像的位置
  643. 'testOutPath':'images/results/',###输出测试图像位置
  644. }
  645. #第一步加载模型
  646. modelList=[ modelPar['model'](weights=modelPar['weight'],par=modelPar['par']) for modelPar in par['models'] ]
  647. #第二步准备跟踪参数
  648. trackPar=par['trackPar']
  649. sort_tracker = Sort(max_age=trackPar['sort_max_age'],
  650. min_hits=trackPar['sort_min_hits'],
  651. iou_threshold=trackPar['sort_iou_thresh'])
  652. #第三步准备画图字体
  653. drawPar = get_drawPar(par)
  654. #第四步获取图像测试及视频
  655. imgpaths,videopaths = get_images_videos( par['testImgPath'])
  656. #第五步开始测试
  657. for i in range(len(imgpaths)):
  658. imgpath = imgpaths[i]
  659. bname = os.path.basename(imgpath )
  660. im0s=[cv2.imread(imgpath)]
  661. time00 = time.time()
  662. retResults,timeOut = AI_det_track_batch_N(im0s, [i] ,modelList,par['postProcess'],sort_tracker ,trackPar)
  663. time11 = time.time()
  664. if len(retResults[1])>0:
  665. retResults[0][0] = drawBoxTraceSimplied(retResults[1],i, retResults[0][0],rainbows=rainbows,boxFlag=True,traceFlag=False,names=drawPar['names'])
  666. image_array = retResults[0][0]
  667. '''
  668. 返回值retResults[2] --list,其中每一个元素为一个list,表示每一帧的检测结果,每一个结果是由多个list构成,每个list表示一个框,格式为[ x0 ,y0 ,x1 ,y1 ,conf,cls ,ifrmae,trackId ]
  669. --etc. retResults[2][j][k]表示第j帧的第k个框。
  670. '''
  671. cv2.imwrite( os.path.join( par['testOutPath'],bname ) ,image_array )
  672. print('----image:%s, Allprocess:%s %s ,save:%s , objcnt:%d'%(bname,(time11-time00) * 1000, timeOut,(time.time() - time11) * 1000 ,len(retResults[2])) )
  673. ##第五步开始测试视频
  674. print('##begin to process videos, total %d videos'%( len(videopaths)))
  675. for i,video in enumerate(videopaths):
  676. print('process video%d :%s '%(i,video))
  677. par0={'modelList':modelList,'postProcess':par['postProcess'],'drawPar':drawPar,'outpth':par['testOutPath'], 'sort_tracker':sort_tracker,'trackPar':trackPar}
  678. process_video(video,par0,mode='track')
  679. def OCR_demo2(opt):
  680. from ocrUtils2 import crnn_model
  681. from ocrUtils2.ocrUtils import get_cfg,recognition_ocr,strLabelConverter
  682. if opt['business'] == 'ocr2':
  683. par={
  684. 'image_dir':'images/ocr_en',
  685. 'outtxt':'images/results',
  686. 'weights':'../AIlib2/weights/conf/ocr2/crnn_448X32.pth',
  687. #'weights':'../weights/2080Ti/AIlib2/ocr2/crnn_2080Ti_fp16_448X32.engine',
  688. 'device':'cuda:0',
  689. 'cfg':'../AIlib2/weights/conf/ocr2/360CC_config.yaml',
  690. 'char_file':'../AIlib2/weights/conf/ocr2/chars.txt',
  691. 'imgH':32,
  692. 'imgW':448,
  693. 'workers':1
  694. }
  695. image_dir=par['image_dir']
  696. outtxt=par['outtxt']
  697. workers=par['workers']
  698. weights= par['weights']
  699. device=par['device']
  700. char_file=par['char_file']
  701. imgH=par['imgH']
  702. imgW=par['imgW']
  703. cfg = par['cfg']
  704. config = get_cfg(cfg, char_file)
  705. par['contextFlag']=False
  706. device = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu')
  707. if weights.endswith('.pth'):
  708. model = crnn_model.get_crnn(config,weights=weights).to(device)
  709. par['model_mode']='pth'
  710. else:
  711. logger = trt.Logger(trt.Logger.ERROR)
  712. with open(weights, "rb") as f, trt.Runtime(logger) as runtime:
  713. model = runtime.deserialize_cuda_engine(f.read())# 输入trt本地文件,返回ICudaEngine对象
  714. print('#####load TRT file:',weights,'success #####')
  715. context = model.create_execution_context()
  716. par['model_mode']='trt';par['contextFlag']=context
  717. converter = strLabelConverter(config.DATASET.ALPHABETS)
  718. img_urls=glob.glob('%s/*.jpg'%( image_dir ))
  719. img_urls.extend( glob.glob('%s/*.png'%( image_dir )) )
  720. cnt=len(img_urls)
  721. print('%s has %d images'%(image_dir ,len(img_urls) ) )
  722. # 准备数据
  723. parList=[]
  724. for i in range(cnt):
  725. img_patch=cv2.imread( img_urls[i] , cv2.IMREAD_GRAYSCALE)
  726. started = time.time()
  727. img = cv2.imread(img_urls[i])
  728. sim_pred = recognition_ocr(config, img, model, converter, device,par=par)
  729. finished = time.time()
  730. print('{0}: elapsed time: {1} prd:{2} '.format( os.path.basename( img_urls[i] ), finished - started, sim_pred ))
  731. def OBB_track_demo(opt):
  732. ###倾斜框(OBB)的ship目标检测
  733. par={
  734. 'obbModelPar':{
  735. 'model_size':(608,608),'K':100,'conf_thresh':0.3, 'down_ratio':4,'num_classes':15,'dataset':'dota',
  736. 'heads': {'hm': None,'wh': 10,'reg': 2,'cls_theta': 1},
  737. 'mean':(0.5, 0.5, 0.5),'std':(1, 1, 1), 'half': False,'decoder':None,
  738. 'weights':'../weights/%s/AIlib2/%s/obb_608X608_%s_fp16.engine'%(opt['gpu'],opt['business'],opt['gpu']),
  739. },
  740. 'outpth': 'images/results',
  741. 'trackPar':{'sort_max_age':2,'sort_min_hits':3,'sort_iou_thresh':0.2,'det_cnt':10,'windowsize':29,'patchCnt':100},
  742. 'device':"cuda:0",
  743. #'test_dir': '/mnt/thsw2/DSP2/videos/obbShips/DJI_20230208110806_0001_W_6M.MP4',
  744. 'test_dir':'/mnt/thsw2/DSP2/videos/obbShips/freighter2.mp4',
  745. 'test_flag':True,
  746. 'postFile': '../AIlib2/weights/conf/%s/para.json'%(opt['business'] ),###后处理参数文件
  747. 'drawBox':True,#####是否画框
  748. 'drawPar': { 'digitWordFont' :{'line_thickness':2,'boxLine_thickness':1,'wordSize':40, 'fontSize':1.0,'label_location':'leftTop'}} ,
  749. 'labelnames':"../AIlib2/weights/conf/%s/labelnames.json"%(opt['business'] ), ###检测类别对照表
  750. }
  751. #par['model_size'],par['mean'],par['std'],par['half'],par['saveType'],par['heads'],par['labelnames'],par['decoder'],par['down_ratio'],par['drawBox']
  752. #par['rainbows'],par['label_array'],par['digitWordFont']
  753. obbModelPar = par['obbModelPar']
  754. ####加载模型
  755. model,decoder2=load_model_decoder_OBB(obbModelPar)
  756. obbModelPar['decoder']=decoder2
  757. names=get_labelnames(par['labelnames']);obbModelPar['labelnames']=names
  758. _,_,_,rainbows=get_postProcess_para(par['postFile']);par['drawPar']['rainbows']=rainbows
  759. label_arraylist = get_label_arrays(names,rainbows,outfontsize=par['drawPar']['digitWordFont']['wordSize'],fontpath="../AIlib2/conf/platech.ttf")
  760. #par['label_array']=label_arraylist
  761. trackPar=par['trackPar']
  762. sort_tracker = OBB_Sort(max_age=trackPar['sort_max_age'],
  763. min_hits=trackPar['sort_min_hits'],
  764. iou_threshold=trackPar['sort_iou_thresh'])
  765. ##图像测试和视频
  766. impth = par['test_dir']
  767. img_urls=[]###获取文件里所有的图像
  768. video_urls=[]###获取文件里所有的视频
  769. img_postfixs = ['.jpg','.JPG','.PNG','.png'];
  770. vides_postfixs= ['.MP4','.mp4','.avi']
  771. if os.path.isdir(impth):
  772. for postfix in img_postfixs:
  773. img_urls.extend(glob.glob('%s/*%s'%(impth,postfix )) )
  774. for postfix in ['.MP4','.mp4','.avi']:
  775. video_urls.extend(glob.glob('%s/*%s'%(impth,postfix )) )
  776. else:
  777. postfix = os.path.splitext(impth)[-1]
  778. if postfix in img_postfixs: img_urls=[ impth ]
  779. if postfix in vides_postfixs: video_urls = [impth ]
  780. parIn = {'obbModelPar':obbModelPar,'modelPar':{'obbmodel': model},'sort_tracker':sort_tracker,'outpth':par['outpth'],'trackPar':trackPar,'drawPar':par['drawPar']}
  781. par['drawPar']['label_array']=label_arraylist
  782. for img_url in img_urls:
  783. #print(img_url)
  784. ori_image=cv2.imread(img_url)
  785. #ori_image_list,infos = OBB_infer(model,ori_image,obbModelPar)
  786. ori_image_list,infos = OBB_tracker_batch([ori_image],[0],parIn['modelPar'],parIn['obbModelPar'],None,parIn['trackPar'],None)
  787. ori_image_list[1] = draw_obb(ori_image_list[2] ,ori_image_list[1],par['drawPar'])
  788. imgName = os.path.basename(img_url)
  789. saveFile = os.path.join(par['outpth'], imgName)
  790. ret=cv2.imwrite(saveFile, ori_image_list[1])
  791. if not ret:
  792. print(saveFile, ' not created ')
  793. print( os.path.basename(img_url),':',infos,ori_image_list[2])
  794. ###处理视频
  795. for video_url in video_urls:
  796. process_video(video_url, parIn ,mode='obbTrack')
  797. def crowd_demo(opt):
  798. if opt['business']=='crowdCounting':
  799. from crowd import crowdModel as Model
  800. par={
  801. 'mean':[0.485, 0.456, 0.406], 'std':[0.229, 0.224, 0.225],'threshold':0.5,
  802. 'input_profile_shapes':[(1,3,256,256),(1,3,1024,1024),(1,3,2048,2048)],
  803. 'modelPar':{'backbone':'vgg16_bn', 'gpu_id':0,'anchorFlag':False, 'width':None,'height':None ,'line':2, 'row':2},
  804. 'weights':"../weights/%s/AIlib2/%s/crowdCounting_%s_dynamic.engine"%(opt['gpu'], opt['business'] ,opt['gpu'] ),###检测模型路径
  805. 'testImgPath':'images/%s'%(opt['business'] ),###测试图像的位置
  806. 'testOutPath':'images/results/',###输出测试图像位置
  807. }
  808. #weights='weights/best_mae.pth'
  809. cmodel = Model(par['weights'],par)
  810. img_path = par['testImgPath']
  811. File = os.listdir(img_path)
  812. targetList = []
  813. for file in File[0:]:
  814. COORlist = []
  815. imgPath = img_path + os.sep + file
  816. img_raw = cv2.cvtColor(cv2.imread(imgPath),cv2.COLOR_BGR2RGB)
  817. # cmodel.eval---
  818. # 输入读取的RGB数组
  819. # 输出:list,0--原图,1-人头坐标list,2-对接OBB的格式数据,其中4个坐标均相同,2-格式如下:
  820. # [ [ [ (x0,y0),(x1,y1),(x2,y2),(x3,y3) ],score, cls ], [ [ (x0,y0),(x1,y1),(x2,y2),(x3,y3) ],score ,cls ],........ ]
  821. prets, infos = cmodel.eval(img_raw)
  822. print(file,infos,' 人数:',len(prets[1]))
  823. img_to_draw = cv2.cvtColor(np.array(img_raw), cv2.COLOR_RGB2BGR)
  824. # 打印预测图像中人头的个数
  825. for p in prets[1]:
  826. img_to_draw = cv2.circle(img_to_draw, (int(p[0]), int(p[1])), 2, (0, 255, 0), -1)
  827. COORlist.append((int(p[0]), int(p[1])))
  828. # 将各测试图像中的人头坐标存储在targetList中, 格式:[[(x1, y1),(x2, y2),...], [(X1, Y1),(X2, Y2),..], ...]
  829. targetList.append(COORlist)
  830. #time.sleep(2)
  831. # 保存预测图片
  832. cv2.imwrite(os.path.join(par['testOutPath'], file), img_to_draw)
  833. if __name__=="__main__":
  834. #jkm_demo()
  835. businessAll=['river', 'river2','highWay2','noParking','drowning','forest2','vehicle','pedestrian','smogfire' , 'AnglerSwimmer','channelEmergency', 'countryRoad','cityMangement','ship2','cityMangement2','cityRoad','illParking',"crowdCounting",'cityMangement3']
  836. businessAll = [ 'cityMangement3' ]
  837. for busi in businessAll:
  838. print('-'*40,'beg to test:',busi,'-'*40)
  839. opt={'gpu':'2080Ti','business':busi}
  840. if busi in ['ship2']:
  841. OBB_track_demo(opt)
  842. elif opt['business'] in ['crowdCounting'] :
  843. crowd_demo(opt)
  844. else:
  845. #if opt['business'] in ['river','highWay2','noParking','drowning','']:
  846. det_track_demo_N(opt )