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.

437 lines
21KB

  1. import cv2,os,time,json
  2. from models.experimental import attempt_load
  3. from segutils.segmodel import SegModel,get_largest_contours
  4. from segutils.trtUtils import segtrtEval,yolov5Trtforward,OcrTrtForward
  5. from segutils.trafficUtils import tracfficAccidentMixFunction
  6. from utils.torch_utils import select_device
  7. from utilsK.queRiver import get_labelnames,get_label_arrays,post_process_,img_pad,draw_painting_joint,detectDraw,getDetections,getDetectionsFromPreds
  8. from trackUtils.sort import moving_average_wang
  9. from utils.datasets import letterbox
  10. import numpy as np
  11. import torch
  12. import math
  13. from PIL import Image
  14. import torch.nn.functional as F
  15. from copy import deepcopy
  16. from scipy import interpolate
  17. def xywh2xyxy(box,iW=None,iH=None):
  18. xc,yc,w,h = box[0:4]
  19. x0 =max(0, xc-w/2.0)
  20. x1 =min(1, xc+w/2.0)
  21. y0=max(0, yc-h/2.0)
  22. y1=min(1,yc+h/2.0)
  23. if iW: x0,x1 = x0*iW,x1*iW
  24. if iH: y0,y1 = y0*iH,y1*iH
  25. return [x0,y0,x1,y1]
  26. def get_ms(t2,t1):
  27. return (t2-t1)*1000.0
  28. def get_postProcess_para(parfile):
  29. with open(parfile) as fp:
  30. par = json.load(fp)
  31. assert 'post_process' in par.keys(), ' parfile has not key word:post_process'
  32. parPost=par['post_process']
  33. return parPost["conf_thres"],parPost["iou_thres"],parPost["classes"],parPost["rainbows"]
  34. def get_postProcess_para_dic(parfile):
  35. with open(parfile) as fp:
  36. par = json.load(fp)
  37. parPost=par['post_process']
  38. return parPost
  39. def AI_process(im0s,model,segmodel,names,label_arraylist,rainbows,objectPar={ '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 }, font={ 'line_thickness':None, 'fontSize':None,'boxLine_thickness':None,'waterLineColor':(0,255,255),'waterLineWidth':3} ,segPar={'modelSize':(640,360),'mean':(0.485, 0.456, 0.406),'std' :(0.229, 0.224, 0.225),'numpy':False, 'RGB_convert_first':True},mode='others',postPar=None):
  40. #输入参数
  41. # im0s---原始图像列表
  42. # model---检测模型,segmodel---分割模型(如若没有用到,则为None)
  43. #
  44. #输出:两个元素(列表,字符)构成的元组,[im0s[0],im0,det_xywh,iframe],strout
  45. # [im0s[0],im0,det_xywh,iframe]中,
  46. # im0s[0]--原始图像,im0--AI处理后的图像,iframe--帧号/暂时不需用到。
  47. # det_xywh--检测结果,是一个列表。
  48. # 其中每一个元素表示一个目标构成如:[ xc,yc,w,h, float(conf_c),float(cls_c) ] ,2023.08.03修改输出格式
  49. # #cls_c--类别,如0,1,2,3; xc,yc,w,h--中心点坐标及宽;conf_c--得分, 取值范围在0-1之间
  50. # #strout---统计AI处理个环节的时间
  51. # Letterbox
  52. half,device,conf_thres,iou_thres,allowedList = objectPar['half'],objectPar['device'],objectPar['conf_thres'],objectPar['iou_thres'],objectPar['allowedList']
  53. trtFlag_det,trtFlag_seg,segRegionCnt = objectPar['trtFlag_det'],objectPar['trtFlag_seg'],objectPar['segRegionCnt']
  54. if 'ovlap_thres_crossCategory' in objectPar.keys():
  55. ovlap_thres = objectPar['ovlap_thres_crossCategory']
  56. else:
  57. ovlap_thres = None
  58. time0=time.time()
  59. if trtFlag_det:
  60. img, padInfos = img_pad(im0s[0], size=(640,640,3)) ;img = [img]
  61. else:
  62. #print('####line72:',im0s[0][10:12,10:12,2])
  63. img = [letterbox(x, 640, auto=True, stride=32)[0] for x in im0s];padInfos=None
  64. #print('####line74:',img[0][10:12,10:12,2])
  65. # Stack
  66. img = np.stack(img, 0)
  67. # Convert
  68. img = img[:, :, :, ::-1].transpose(0, 3, 1, 2) # BGR to RGB, to bsx3x416x416
  69. img = np.ascontiguousarray(img)
  70. img = torch.from_numpy(img).to(device)
  71. img = img.half() if half else img.float() # uint8 to fp16/32
  72. img /= 255.0
  73. time01=time.time()
  74. if segmodel:
  75. seg_pred,segstr = segmodel.eval(im0s[0] )
  76. segFlag=True
  77. else:
  78. seg_pred = None;segFlag=False;segstr='Not implemented'
  79. time1=time.time()
  80. if trtFlag_det:
  81. pred = yolov5Trtforward(model,img)
  82. else:
  83. #print('####line96:',img[0,0,10:12,10:12])
  84. pred = model(img,augment=False)[0]
  85. time2=time.time()
  86. p_result, timeOut = getDetectionsFromPreds(pred,img,im0s[0],conf_thres=conf_thres,iou_thres=iou_thres,ovlap_thres=ovlap_thres,padInfos=padInfos)
  87. #if mode=='highWay3.0':
  88. #if segmodel:
  89. if segPar and segPar['mixFunction']['function']:
  90. mixFunction = segPar['mixFunction']['function'];H,W = im0s[0].shape[0:2]
  91. parMix = segPar['mixFunction']['pars'];#print('###line117:',parMix,p_result[2])
  92. parMix['imgSize'] = (W,H)
  93. #print(' -----------line110: ',p_result[2] ,'\n', seg_pred)
  94. p_result[2] , timeMixPost= mixFunction(p_result[2], seg_pred, pars=parMix )
  95. #print(' -----------line112: ',p_result[2] )
  96. p_result.append(seg_pred)
  97. else:
  98. timeMixPost=':0 ms'
  99. #print('#### line121: segstr:%s timeMixPost:%s timeOut:%s'%( segstr.strip(), timeMixPost,timeOut ))
  100. time_info = 'letterbox:%.1f, seg:%.1f , infer:%.1f,%s, seginfo:%s ,timeMixPost:%s '%( (time01-time0)*1000, (time1-time01)*1000 ,(time2-time1)*1000,timeOut , segstr.strip(),timeMixPost )
  101. #if mode=='highWay3.0':
  102. return p_result,time_info
  103. def AI_process_forest(im0s,model,segmodel,names,label_arraylist,rainbows,half=True,device=' cuda:0',conf_thres=0.25, iou_thres=0.45,allowedList=[0,1,2,3], font={ 'line_thickness':None, 'fontSize':None,'boxLine_thickness':None,'waterLineColor':(0,255,255),'waterLineWidth':3} ,trtFlag_det=False,SecNms=None):
  104. #输入参数
  105. # im0s---原始图像列表
  106. # model---检测模型,segmodel---分割模型(如若没有用到,则为None)
  107. #输出:两个元素(列表,字符)构成的元组,[im0s[0],im0,det_xywh,iframe],strout
  108. # [im0s[0],im0,det_xywh,iframe]中,
  109. # im0s[0]--原始图像,im0--AI处理后的图像,iframe--帧号/暂时不需用到。
  110. # det_xywh--检测结果,是一个列表。
  111. # 其中每一个元素表示一个目标构成如:[ xc,yc,w,h, float(conf_c),float(cls_c)],#2023.08.03,修改输出格式
  112. # #cls_c--类别,如0,1,2,3; xc,yc,w,h--中心点坐标及宽;conf_c--得分, 取值范围在0-1之间
  113. # #strout---统计AI处理个环节的时间
  114. # Letterbox
  115. time0=time.time()
  116. if trtFlag_det:
  117. img, padInfos = img_pad(im0s[0], size=(640,640,3)) ;img = [img]
  118. else:
  119. img = [letterbox(x, 640, auto=True, stride=32)[0] for x in im0s];padInfos=None
  120. #img = [letterbox(x, 640, auto=True, stride=32)[0] for x in im0s]
  121. # Stack
  122. img = np.stack(img, 0)
  123. # Convert
  124. img = img[:, :, :, ::-1].transpose(0, 3, 1, 2) # BGR to RGB, to bsx3x416x416
  125. img = np.ascontiguousarray(img)
  126. img = torch.from_numpy(img).to(device)
  127. img = img.half() if half else img.float() # uint8 to fp16/32
  128. img /= 255.0 # 0 - 255 to 0.0 - 1.0
  129. if segmodel:
  130. seg_pred,segstr = segmodel.eval(im0s[0] )
  131. segFlag=True
  132. else:
  133. seg_pred = None;segFlag=False
  134. time1=time.time()
  135. pred = yolov5Trtforward(model,img) if trtFlag_det else model(img,augment=False)[0]
  136. time2=time.time()
  137. datas = [[''], img, im0s, None,pred,seg_pred,10]
  138. ObjectPar={ 'object_config':allowedList, 'slopeIndex':[] ,'segmodel':segFlag,'segRegionCnt':0 }
  139. p_result,timeOut = post_process_(datas,conf_thres, iou_thres,names,label_arraylist,rainbows,10,ObjectPar=ObjectPar,font=font,padInfos=padInfos,ovlap_thres=SecNms)
  140. #print('###line274:',p_result[2])
  141. #p_result,timeOut = post_process_(datas,conf_thres, iou_thres,names,label_arraylist,rainbows,10,object_config=allowedList,segmodel=segFlag,font=font,padInfos=padInfos)
  142. time_info = 'letterbox:%.1f, infer:%.1f, '%( (time1-time0)*1000,(time2-time1)*1000 )
  143. return p_result,time_info+timeOut
  144. def AI_det_track( im0s_in,modelPar,processPar,sort_tracker,segPar=None):
  145. im0s,iframe=im0s_in[0],im0s_in[1]
  146. model = modelPar['det_Model']
  147. segmodel = modelPar['seg_Model']
  148. half,device,conf_thres, iou_thres,trtFlag_det = processPar['half'], processPar['device'], processPar['conf_thres'], processPar['iou_thres'],processPar['trtFlag_det']
  149. iou2nd = processPar['iou2nd']
  150. time0=time.time()
  151. if trtFlag_det:
  152. img, padInfos = img_pad(im0s[0], size=(640,640,3)) ;img = [img]
  153. else:
  154. img = [letterbox(x, 640, auto=True, stride=32)[0] for x in im0s];padInfos=None
  155. img = np.stack(img, 0)
  156. # Convert
  157. img = img[:, :, :, ::-1].transpose(0, 3, 1, 2) # BGR to RGB, to bsx3x416x416
  158. img = np.ascontiguousarray(img)
  159. img = torch.from_numpy(img).to(device)
  160. img = img.half() if half else img.float() # uint8 to fp16/32
  161. img /= 255.0 # 0 - 255 to 0.0 - 1.0
  162. seg_pred = None;segFlag=False
  163. time1=time.time()
  164. pred = yolov5Trtforward(model,img) if trtFlag_det else model(img,augment=False)[0]
  165. time2=time.time()
  166. #p_result,timeOut = getDetections(datas,conf_thres, iou_thres,names,label_arraylist,rainbows,10,ObjectPar=ObjectPar,font=font,padInfos=padInfos)
  167. p_result, timeOut = getDetectionsFromPreds(pred,img,im0s[0],conf_thres=conf_thres,iou_thres=iou_thres,ovlap_thres=iou2nd,padInfos=padInfos)
  168. if segmodel:
  169. seg_pred,segstr = segmodel.eval(im0s[0] )
  170. segFlag=True
  171. else:
  172. seg_pred = None;segFlag=False;segstr='No segmodel'
  173. if segPar and segPar['mixFunction']['function']:
  174. mixFunction = segPar['mixFunction']['function']
  175. H,W = im0s[0].shape[0:2]
  176. parMix = segPar['mixFunction']['pars'];#print('###line117:',parMix,p_result[2])
  177. parMix['imgSize'] = (W,H)
  178. p_result[2],timeInfos_post = mixFunction(p_result[2], seg_pred, pars=parMix )
  179. timeInfos_seg_post = 'segInfer:%s ,postMixProcess:%s'%( segstr, timeInfos_post )
  180. else:
  181. timeInfos_seg_post = ' '
  182. '''
  183. if segmodel:
  184. timeS1=time.time()
  185. #seg_pred,segstr = segtrtEval(segmodel,im0s[0],par=segPar) if segPar['trtFlag_seg'] else segmodel.eval(im0s[0] )
  186. seg_pred,segstr = segmodel.eval(im0s[0] )
  187. timeS2=time.time()
  188. mixFunction = segPar['mixFunction']['function']
  189. p_result[2],timeInfos_post = mixFunction(p_result[2], seg_pred, pars=segPar['mixFunction']['pars'] )
  190. timeInfos_seg_post = 'segInfer:%.1f ,postProcess:%s'%( (timeS2-timeS1)*1000, timeInfos_post )
  191. else:
  192. timeInfos_seg_post = ' '
  193. #print('######line341:',seg_pred.shape,np.max(seg_pred),np.min(seg_pred) , len(p_result[2]) )
  194. '''
  195. time_info = 'letterbox:%.1f, detinfer:%.1f, '%( (time1-time0)*1000,(time2-time1)*1000 )
  196. if sort_tracker:
  197. #在这里增加设置调用追踪器的频率
  198. #..................USE TRACK FUNCTION....................
  199. #pass an empty array to sort
  200. dets_to_sort = np.empty((0,7), dtype=np.float32)
  201. # NOTE: We send in detected object class too
  202. #for detclass,x1,y1,x2,y2,conf in p_result[2]:
  203. for x1,y1,x2,y2,conf, detclass in p_result[2]:
  204. #print('#######line342:',x1,y1,x2,y2,img.shape,[x1, y1, x2, y2, conf, detclass,iframe])
  205. dets_to_sort = np.vstack((dets_to_sort,
  206. np.array([x1, y1, x2, y2, conf, detclass,iframe],dtype=np.float32) ))
  207. # Run SORT
  208. tracked_dets = deepcopy(sort_tracker.update(dets_to_sort) )
  209. tracks =sort_tracker.getTrackers()
  210. p_result.append(tracked_dets) ###index=4
  211. p_result.append(tracks) ###index=5
  212. return p_result,time_info+timeOut+timeInfos_seg_post
  213. def AI_det_track_batch(imgarray_list, iframe_list ,modelPar,processPar,sort_tracker,trackPar,segPar=None):
  214. '''
  215. 输入:
  216. imgarray_list--图像列表
  217. iframe_list -- 帧号列表
  218. modelPar--模型参数,字典,modelPar={'det_Model':,'seg_Model':}
  219. processPar--字典,存放检测相关参数,'half', 'device', 'conf_thres', 'iou_thres','trtFlag_det'
  220. sort_tracker--对象,初始化的跟踪对象。为了保持一致,即使是单帧也要有。
  221. trackPar--跟踪参数,关键字包括:det_cnt,windowsize
  222. segPar--None,分割模型相关参数。如果用不到,则为None
  223. 输入:retResults,timeInfos
  224. retResults:list
  225. retResults[0]--imgarray_list
  226. retResults[1]--所有结果用numpy格式,所有的检测结果,包括8类,每列分别是x1, y1, x2, y2, conf, detclass,iframe,trackId
  227. retResults[2]--所有结果用list表示,其中每一个元素为一个list,表示每一帧的检测结果,每一个结果是由多个list构成,每个list表示一个框,格式为[ x0 ,y0 ,x1 ,y1 ,conf, cls ,ifrmae,trackId ],如 retResults[2][j][k]表示第j帧的第k个框。2023.08.03,修改输出格式
  228. '''
  229. det_cnt,windowsize = trackPar['det_cnt'] ,trackPar['windowsize']
  230. trackers_dic={}
  231. index_list = list(range( 0, len(iframe_list) ,det_cnt ));
  232. if len(index_list)>1 and index_list[-1]!= iframe_list[-1]:
  233. index_list.append( len(iframe_list) - 1 )
  234. if len(imgarray_list)==1: #如果是单帧图片,则不用跟踪
  235. retResults = []
  236. p_result,timeOut = AI_det_track( [ [imgarray_list[0]] ,iframe_list[0] ],modelPar,processPar,None,segPar )
  237. ##下面4行内容只是为了保持格式一致
  238. detArray = np.array(p_result[2])
  239. #print('##line371:',detArray)
  240. if len(p_result[2])==0:res=[]
  241. else:
  242. cnt = detArray.shape[0];trackIds=np.zeros((cnt,1));iframes = np.zeros((cnt,1)) + iframe_list[0]
  243. #detArray = np.hstack( (detArray[:,1:5], detArray[:,5:6] ,detArray[:,0:1],iframes, trackIds ) )
  244. detArray = np.hstack( (detArray[:,0:4], detArray[:,4:6] ,iframes, trackIds ) ) ##2023.08.03 修改输入格式
  245. res = [[ b[0],b[1],b[2],b[3],b[4],b[5],b[6],b[7] ] for b in detArray ]
  246. retResults=[imgarray_list,detArray,res ]
  247. #print('##line380:',retResults[2])
  248. return retResults,timeOut
  249. else:
  250. t0 = time.time()
  251. timeInfos_track=''
  252. for iframe_index, index_frame in enumerate(index_list):
  253. p_result,timeOut = AI_det_track( [ [imgarray_list[index_frame]] ,iframe_list[index_frame] ],modelPar,processPar,sort_tracker,segPar )
  254. timeInfos_track='%s:%s'%(timeInfos_track,timeOut)
  255. for tracker in p_result[5]:
  256. trackers_dic[tracker.id]=deepcopy(tracker)
  257. t1 = time.time()
  258. track_det_result = np.empty((0,8))
  259. for trackId in trackers_dic.keys():
  260. tracker = trackers_dic[trackId]
  261. bbox_history = np.array(tracker.bbox_history)
  262. if len(bbox_history)<2: continue
  263. ###把(x0,y0,x1,y1)转换成(xc,yc,w,h)
  264. xcs_ycs = (bbox_history[:,0:2] + bbox_history[:,2:4] )/2
  265. whs = bbox_history[:,2:4] - bbox_history[:,0:2]
  266. bbox_history[:,0:2] = xcs_ycs;bbox_history[:,2:4] = whs;
  267. arrays_box = bbox_history[:,0:7].transpose();frames=bbox_history[:,6]
  268. #frame_min--表示该批次图片的起始帧,如该批次是[1,100],则frame_min=1,[101,200]--frame_min=101
  269. #frames[0]--表示该目标出现的起始帧,如[1,11,21,31,41],则frames[0]=1,frames[0]可能会在frame_min之前出现,即一个横跨了多个批次。
  270. ##如果要最好化插值范围,则取内区间[frame_min,则frame_max ]和[frames[0],frames[-1] ]的交集
  271. #inter_frame_min = int(max(frame_min, frames[0])); inter_frame_max = int(min( frame_max, frames[-1] )) ##
  272. ##如果要求得到完整的目标轨迹,则插值区间要以目标出现的起始点为准
  273. inter_frame_min=int(frames[0]);inter_frame_max=int(frames[-1])
  274. new_frames= np.linspace(inter_frame_min,inter_frame_max,inter_frame_max-inter_frame_min+1 )
  275. f_linear = interpolate.interp1d(frames,arrays_box); interpolation_x0s = (f_linear(new_frames)).transpose()
  276. move_cnt_use =(len(interpolation_x0s)+1)//2*2-1 if len(interpolation_x0s)<windowsize else windowsize
  277. for im in range(4):
  278. interpolation_x0s[:,im] = moving_average_wang(interpolation_x0s[:,im],move_cnt_use )
  279. cnt = inter_frame_max-inter_frame_min+1; trackIds = np.zeros((cnt,1)) + trackId
  280. interpolation_x0s = np.hstack( (interpolation_x0s, trackIds ) )
  281. track_det_result = np.vstack(( track_det_result, interpolation_x0s) )
  282. #print('#####line116:',trackId,frame_min,frame_max,'----------',interpolation_x0s.shape,track_det_result.shape ,'-----')
  283. ##将[xc,yc,w,h]转为[x0,y0,x1,y1]
  284. x0s = track_det_result[:,0] - track_det_result[:,2]/2 ; x1s = track_det_result[:,0] + track_det_result[:,2]/2
  285. y0s = track_det_result[:,1] - track_det_result[:,3]/2 ; y1s = track_det_result[:,1] + track_det_result[:,3]/2
  286. track_det_result[:,0] = x0s; track_det_result[:,1] = y0s;
  287. track_det_result[:,2] = x1s; track_det_result[:,3] = y1s;
  288. detResults=[]
  289. for iiframe in iframe_list:
  290. boxes_oneFrame = track_det_result[ track_det_result[:,6]==iiframe ]
  291. res = [[ b[0],b[1],b[2],b[3],b[4],b[5],b[6],b[7] ] for b in boxes_oneFrame ]
  292. #[ x0 ,y0 ,x1 ,y1 ,conf,cls,ifrmae,trackId ]
  293. #[ifrmae, x0 ,y0 ,x1 ,y1 ,conf,cls,trackId ]
  294. detResults.append( res )
  295. retResults=[imgarray_list,track_det_result,detResults ]
  296. t2 = time.time()
  297. timeInfos = 'detTrack:%.1f TrackPost:%.1f, %s'%(get_ms(t1,t0),get_ms(t2,t1), timeInfos_track )
  298. return retResults,timeInfos
  299. def ocr_process(pars):
  300. img_patch,engine,context,converter,AlignCollate_normal,device=pars[0:6]
  301. time1 = time.time()
  302. img_tensor = AlignCollate_normal([ Image.fromarray(img_patch,'L') ])
  303. img_input = img_tensor.to('cuda:0')
  304. time2 = time.time()
  305. preds,trtstr=OcrTrtForward(engine,[img_input],context)
  306. time3 = time.time()
  307. batch_size = preds.size(0)
  308. preds_size = torch.IntTensor([preds.size(1)] * batch_size)
  309. ######## filter ignore_char, rebalance
  310. preds_prob = F.softmax(preds, dim=2)
  311. preds_prob = preds_prob.cpu().detach().numpy()
  312. pred_norm = preds_prob.sum(axis=2)
  313. preds_prob = preds_prob/np.expand_dims(pred_norm, axis=-1)
  314. preds_prob = torch.from_numpy(preds_prob).float().to(device)
  315. _, preds_index = preds_prob.max(2)
  316. preds_index = preds_index.view(-1)
  317. time4 = time.time()
  318. preds_str = converter.decode_greedy(preds_index.data.cpu().detach().numpy(), preds_size.data)
  319. time5 = time.time()
  320. info_str= ('pre-process:%.2f TRTforward:%.2f (%s) postProcess:%2.f decoder:%.2f, Total:%.2f , pred:%s'%(get_ms(time2,time1 ),get_ms(time3,time2 ),trtstr, get_ms(time4,time3 ), get_ms(time5,time4 ), get_ms(time5,time1 ), preds_str ) )
  321. return preds_str,info_str
  322. def main():
  323. ##预先设置的参数
  324. device_='1' ##选定模型,可选 cpu,'0','1'
  325. ##以下参数目前不可改
  326. Detweights = "weights/yolov5/class5/best_5classes.pt"
  327. seg_nclass = 2
  328. Segweights = "weights/BiSeNet/checkpoint.pth"
  329. conf_thres,iou_thres,classes= 0.25,0.45,5
  330. labelnames = "weights/yolov5/class5/labelnames.json"
  331. 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]]
  332. allowedList=[0,1,2,3]
  333. ##加载模型,准备好显示字符
  334. device = select_device(device_)
  335. names=get_labelnames(labelnames)
  336. label_arraylist = get_label_arrays(names,rainbows,outfontsize=40,fontpath="conf/platech.ttf")
  337. half = device.type != 'cpu' # half precision only supported on CUDA
  338. model = attempt_load(Detweights, map_location=device) # load FP32 model
  339. if half: model.half()
  340. segmodel = SegModel(nclass=seg_nclass,weights=Segweights,device=device)
  341. ##图像测试
  342. #url='images/examples/20220624_响水河_12300_1621.jpg'
  343. impth = 'images/examples/'
  344. outpth = 'images/results/'
  345. folders = os.listdir(impth)
  346. for i in range(len(folders)):
  347. imgpath = os.path.join(impth, folders[i])
  348. im0s=[cv2.imread(imgpath)]
  349. time00 = time.time()
  350. p_result,timeOut = AI_process(im0s,model,segmodel,names,label_arraylist,rainbows,half,device,conf_thres, iou_thres,allowedList,fontSize=1.0)
  351. time11 = time.time()
  352. image_array = p_result[1]
  353. cv2.imwrite( os.path.join( outpth,folders[i] ) ,image_array )
  354. #print('----process:%s'%(folders[i]), (time.time() - time11) * 1000)
  355. if __name__=="__main__":
  356. main()