落水人员检测
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

268 linhas
11KB

  1. '''
  2. 这个版本增加了船舶过滤功能
  3. '''
  4. import time
  5. import sys
  6. from core.models.bisenet import BiSeNet
  7. from models.AIDetector_pytorch import Detector
  8. from models.AIDetector_pytorch import plot_one_box,Colors
  9. from utils.postprocess_utils import center_coordinate,fourcorner_coordinate,remove_simivalue,remove_sameeleme_inalist
  10. import os
  11. os.environ['CUDA_VISIBLE_DEVICES'] = '1'
  12. from models.model_stages import BiSeNet
  13. import cv2
  14. import torch
  15. import torch.nn.functional as F
  16. from PIL import Image
  17. import numpy as np
  18. import torchvision.transforms as transforms
  19. from utils.segutils import colour_code_segmentation
  20. from utils.segutils import get_label_info
  21. os.environ['KMP_DUPLICATE_LIB_OK']='TRUE'
  22. os.environ["CUDA_VISIBLE_DEVICES"] = "0"
  23. sys.path.append("../") # 为了导入上级目录的,添加一个新路径
  24. def AI_postprocess(pred,_img_cv,_mask_cv):
  25. '''还未考虑船上人过滤'''
  26. '''输入:落水人员的结果(类别+坐标)、原图、mask图像
  27. 过程:获得mask的轮廓,判断人员是否在轮廓内。
  28. 在,则保留且绘制;不在,舍弃。
  29. 返回:最终绘制的结果图、最终落水人员(坐标、类别、置信度),
  30. '''
  31. '''1、最大分割水域作为判断依据'''
  32. t4 = time.time()
  33. img_gray = cv2.cvtColor(_mask_cv, cv2.COLOR_BGR2GRAY)
  34. contours, thresh = cv2.threshold(img_gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
  35. t5=time.time()
  36. # 寻找轮廓(多边界)
  37. contours, hierarchy = cv2.findContours(thresh, cv2.RETR_LIST, 2)
  38. contour_info = []
  39. for c in contours:
  40. contour_info.append((
  41. c,
  42. cv2.isContourConvex(c),
  43. cv2.contourArea(c),
  44. ))
  45. contour_info = sorted(contour_info, key=lambda c: c[2], reverse=True)
  46. t6 = time.time()
  47. print('t5-t4',t5-t4)
  48. '''新增模块:如果水域为空,则返回原图、无落水人员等。'''
  49. if contour_info==[]:
  50. final_img=_img_cv
  51. final_head_person_filterwater=[]
  52. return final_img, final_head_person_filterwater
  53. else:
  54. max_contour = contour_info[0]
  55. print(max_contour)
  56. t7 = time.time()
  57. '''2.1、pred中head+person取出,boat取出。'''
  58. init_head_person=[]
  59. init_boat = []
  60. for i in range(len(pred[1])):
  61. if pred[1][i][4]=='head' or pred[1][i][4]=='person':
  62. init_head_person.append(pred[1][i])
  63. else:
  64. init_boat.append(pred[1][i])
  65. t8 = time.time()
  66. '''新增模块:2.2、pred中head+person取出,过滤掉head与person中指向同一人的部分,保留同一人的person标签。'''
  67. init_head=[]
  68. init_person=[]
  69. #head与person标签分开
  70. for i in range(len(init_head_person)):
  71. if init_head_person[i][4]=='head':
  72. init_head.append(init_head_person[i])
  73. else:
  74. init_person.append(init_head_person[i])
  75. # person的框形成contours
  76. person_contour=[]
  77. for i in range(len(init_person)):
  78. boundbxs_temp=[init_person[i][0],init_person[i][1],init_person[i][2],init_person[i][3]]
  79. contour_temp_person=fourcorner_coordinate(boundbxs_temp) #得到person预测框的顺序contour
  80. contour_temp_person=np.array(contour_temp_person)
  81. contour_temp_person=np.float32(contour_temp_person)
  82. person_contour.append(np.array(contour_temp_person))
  83. # head是否在person的contours内,在说明是同一人,过滤掉。
  84. list_head=[]
  85. for i in range(len(init_head)):
  86. for j in range(len(person_contour)):
  87. center_x, center_y=center_coordinate(init_head[i])
  88. flag = cv2.pointPolygonTest(person_contour[j], (center_x, center_y), False) #若为False,会找点是否在内,外,或轮廓上(相应返回+1, -1, 0)。
  89. if flag==1:
  90. pass
  91. else:
  92. list_head.append(init_head[i])
  93. # person和最终head合并起来
  94. init_head_person_temp=init_person+list_head
  95. '''3、pred中head+person,通过1中水域过滤'''
  96. init_head_person_filterwater=init_head_person_temp
  97. final_head_person_filterwater=[]
  98. for i in range(len(init_head_person_filterwater)):
  99. center_x, center_y=center_coordinate(init_head_person_filterwater[i])
  100. flag = cv2.pointPolygonTest(max_contour[0], (center_x, center_y), False) #若为False,会找点是否在内,外,或轮廓上(相应返回+1, -1, 0)。
  101. if flag==1:
  102. final_head_person_filterwater.append(init_head_person_filterwater[i])
  103. else:
  104. pass
  105. t9 = time.time()
  106. '''4、水域过滤后的head+person,再通过船舶范围过滤'''
  107. init_head_person_filterboat=final_head_person_filterwater
  108. # final_head_person_filterboat=[]
  109. #获取船舶范围
  110. boat_contour=[]
  111. for i in range(len(init_boat)):
  112. boundbxs1=[init_boat[i][0],init_boat[i][1],init_boat[i][2],init_boat[i][3]]
  113. contour_temp=fourcorner_coordinate(boundbxs1) #得到boat预测框的顺序contour
  114. contour_temp_=np.array(contour_temp)
  115. contour_temp_=np.float32(contour_temp_)
  116. boat_contour.append(np.array(contour_temp_))
  117. t10 = time.time()
  118. # 遍历船舶范围,取出在船舶范围内的head和person(可能有重复元素)
  119. list_headperson_inboat=[]
  120. for i in range(len(init_head_person_filterboat)):
  121. for j in range(len(boat_contour)):
  122. center_x, center_y=center_coordinate(init_head_person_filterboat[i])
  123. # yyyyyyyy=boat_contour[j]
  124. flag = cv2.pointPolygonTest(boat_contour[j], (center_x, center_y), False) #若为False,会找点是否在内,外,或轮廓上(相应返回+1, -1, 0)。
  125. if flag==1:
  126. list_headperson_inboat.append(init_head_person_filterboat[i])
  127. else:
  128. pass
  129. print('list_headperson_inboat',list_headperson_inboat)
  130. if len(list_headperson_inboat)==0:
  131. pass
  132. else:
  133. list_headperson_inboat=remove_sameeleme_inalist(list_headperson_inboat) #将重复嵌套列表元素删除
  134. # 过滤船舶范围内的head和person
  135. final_head_person_filterboat=remove_simivalue(init_head_person_filterboat,list_headperson_inboat)
  136. t11 = time.time()
  137. '''5、输出最终落水人员,并绘制保存检测图'''
  138. colors = Colors()
  139. if final_head_person_filterwater is not None:
  140. for i in range(len(final_head_person_filterboat)):
  141. # lbl = self.names[int(cls_id)]
  142. lbl = final_head_person_filterboat[i][4]
  143. xyxy=[final_head_person_filterboat[i][0],final_head_person_filterboat[i][1],final_head_person_filterboat[i][2],final_head_person_filterboat[i][3]]
  144. c = int(5)
  145. plot_one_box(xyxy, _img_cv, label=lbl, color=colors(c, True), line_thickness=3)
  146. final_img=_img_cv
  147. t12 = time.time()
  148. # cv2.imwrite('final_result.png', _img_cv)
  149. t13 = time.time()
  150. print('存图:%s, 过滤标签:%s ,遍历船舶范围:%s,水域过滤后的head+person:%s,水域过滤:%s,head+person、boat取出:%s,新增如果水域为空:%s,找contours:%s,图像改变:%s'
  151. %((t13-t12) * 1000,(t12-t11) * 1000,(t11-t10) * 1000,(t10-t9) * 1000,(t9-t8) * 1000,(t8-t7) * 1000,(t7-t6) * 1000,(t6-t5) * 1000,(t5-t4) * 1000 ) )
  152. return final_img,final_head_person_filterwater #返回最终绘制的结果图、最终落水人员(坐标、类别、置信度)
  153. def AI_process(model, segmodel, args1,path1):
  154. '''对原图进行目标检测和水域分割'''
  155. '''输入:检测模型、分割模型、配置参数、路径
  156. 返回:返回目标检测结果、原图像、分割图像,
  157. '''
  158. '''检测图片'''
  159. t21=time.time()
  160. _img_cv = cv2.imread(path1) # 将这里的送入yolov5
  161. t22 = time.time()
  162. # _img_cv=_img_cv.numpy()
  163. pred = model.detect(_img_cv) # 检测结果
  164. print('pred', pred)
  165. t23 = time.time()
  166. '''分割图片'''
  167. img = Image.open(path1).convert('RGB')
  168. t231 = time.time()
  169. transf1 = transforms.ToTensor()
  170. transf2 = transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
  171. imgs = transf1(img)
  172. imgs = transf2(imgs)
  173. print(path1) # numpy数组格式为(H,W,C)
  174. size = [360, 640]
  175. imgs = imgs.unsqueeze(0)
  176. imgs = imgs.cuda()
  177. N, C, H, W = imgs.size()
  178. self_scale = 360 / H
  179. new_hw = [int(H * self_scale), int(W * self_scale)]
  180. print("line50", new_hw)
  181. imgs = F.interpolate(imgs, new_hw, mode='bilinear', align_corners=True)
  182. t24 = time.time()
  183. with torch.no_grad():
  184. logits = segmodel(imgs)[0]
  185. t241 = time.time()
  186. logits = F.interpolate(logits, size=size, mode='bilinear', align_corners=True)
  187. probs = torch.softmax(logits, dim=1)
  188. preds = torch.argmax(probs, dim=1)
  189. preds_squeeze = preds.squeeze(0)
  190. preds_squeeze_predict = colour_code_segmentation(np.array(preds_squeeze.cpu()), args1['label_info'])
  191. preds_squeeze_predict = cv2.resize(np.uint8(preds_squeeze_predict), (W, H))
  192. predict_mask = cv2.cvtColor(np.uint8(preds_squeeze_predict), cv2.COLOR_RGB2BGR)
  193. _mask_cv =predict_mask
  194. t25 = time.time()
  195. cv2.imwrite('seg_result.png', _mask_cv)
  196. t26 = time.time()
  197. print('存分割图:%s, 分割后处理:%s ,分割推理:%s ,分割图变小:%s,分割图读图:%s,检测模型推理:%s,读图片:%s'
  198. %((t26-t25) * 1000,(t25-t241) * 1000,(t241-t24) * 1000,(t24-t231) * 1000,(t231-t23) * 1000,(t23-t22) * 1000,(t22-t21) * 1000 ) )
  199. return pred, _img_cv, _mask_cv #返回目标检测结果、原图像、分割图像
  200. def main():
  201. '''配置参数'''
  202. label_info = get_label_info('utils/class_dict.csv')
  203. args1={'cuda':'0','crop_size':512,'input_dir':'input_dir','output_dir':'output_dir','workers':16,'label_info':label_info,
  204. 'dspth':'./data/','backbone':'STDCNet813','use_boundary_2':False, 'use_boundary_4':False, 'use_boundary_8':True, 'use_boundary_16':False,'use_conv_last':False}
  205. dete_weights='weights/best_luoshui20230608.pt'
  206. '''分割模型权重路径'''
  207. seg_weights = 'weights/model_final.pth'
  208. '''初始化目标检测模型'''
  209. model = Detector(dete_weights)
  210. '''初始化分割模型2'''
  211. n_classes = 2
  212. segmodel = BiSeNet(backbone=args1['backbone'], n_classes=n_classes,
  213. use_boundary_2=args1['use_boundary_2'], use_boundary_4=args1['use_boundary_4'],
  214. use_boundary_8=args1['use_boundary_8'], use_boundary_16=args1['use_boundary_16'],
  215. use_conv_last=args1['use_conv_last'])
  216. segmodel.load_state_dict(torch.load(seg_weights))
  217. segmodel.cuda()
  218. segmodel.eval()
  219. '''图像测试'''
  220. folders = os.listdir(args1['input_dir'])
  221. for i in range(len(folders)):
  222. path1 = args1['input_dir'] + '/' + folders[i]
  223. t1=time.time()
  224. '''对原图进行目标检测和水域分割'''
  225. pred, _img_cv, _mask_cv=AI_process(model,segmodel, args1,path1)
  226. t2 = time.time()
  227. '''进入后处理,判断水域内有落水人员'''
  228. hhh=AI_postprocess(pred, _img_cv, _mask_cv)
  229. t3 = time.time()
  230. print('总时间分布:前处理t2-t1,后处理t3-t2',t2-t1,t3-t2)
  231. if __name__ == "__main__":
  232. main()