renwu.py 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526
  1. from pathlib import Path
  2. import matplotlib.path as mat
  3. from ultralytics.models.utils import ops
  4. from utils.general import strtolstl
  5. from utils.general import compute_IOU
  6. from torchvision import transforms
  7. from PIL import Image
  8. import torch
  9. import torch.nn.functional as F
  10. import numpy as np
  11. import torch.nn as nn
  12. from ultralytics.engine.results import Results
  13. from shapely.geometry import Point
  14. from shapely.geometry.polygon import Polygon
  15. from pydantic import BaseModel
  16. mean, std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]
  17. test = transforms.Compose([transforms.Resize((224,224)),
  18. #transforms.CenterCrop(224),
  19. transforms.ToTensor(),
  20. transforms.Normalize(mean=mean, std=std)
  21. ])
  22. def clapre(modelcla,claimg,clapoint):
  23. imgten = torch.stack(claimg,dim=0)
  24. clapoint = torch.stack(clapoint,dim=0)
  25. imgten = imgten.to(0)
  26. result = modelcla(imgten)
  27. result = F.softmax(result)
  28. print(result)
  29. index = result.argmax(1)
  30. index = index.cpu().numpy()
  31. index = np.argwhere(index<5)
  32. index = index.reshape(-1)
  33. print(index)
  34. if len(index)>0:
  35. print(clapoint[index])
  36. return clapoint[index]
  37. else:
  38. return None
  39. class Model(nn.Module):
  40. def __init__(self, A, nnode, nfeature, nclass):
  41. super().__init__()
  42. self.fc1 = nn.Linear(nnode * nfeature, 512)
  43. self.fc2 = nn.Linear(512, nclass)
  44. def forward(self, x):
  45. x = x.view(-1, int(x.size(1) * x.size(2)))
  46. x = F.relu(self.fc1(x))
  47. x = F.dropout(x, 0.7, training=self.training)
  48. return self.fc2(x)
  49. class GetKeypoint(BaseModel):
  50. NOSE: int = 0
  51. LEFT_EYE: int = 1
  52. RIGHT_EYE: int = 2
  53. LEFT_EAR: int = 3
  54. RIGHT_EAR: int = 4
  55. LEFT_SHOULDER: int = 5
  56. RIGHT_SHOULDER: int = 6
  57. LEFT_ELBOW: int = 7
  58. RIGHT_ELBOW: int = 8
  59. LEFT_WRIST: int = 9
  60. RIGHT_WRIST: int = 10
  61. LEFT_HIP: int = 11
  62. RIGHT_HIP: int = 12
  63. LEFT_KNEE: int = 13
  64. RIGHT_KNEE: int = 14
  65. LEFT_ANKLE: int = 15
  66. RIGHT_ANKLE: int = 16
  67. def extract_keypoint(get_keypoint, keypoint):
  68. # nose
  69. nose_x, nose_y = keypoint[get_keypoint.NOSE]
  70. # eye
  71. # left_eye_x, left_eye_y = keypoint[get_keypoint.LEFT_EYE]
  72. # right_eye_x, right_eye_y = keypoint[get_keypoint.RIGHT_EYE]
  73. # # ear
  74. # left_ear_x, left_ear_y = keypoint[get_keypoint.LEFT_EAR]
  75. # right_ear_x, right_ear_y = keypoint[get_keypoint.RIGHT_EAR]
  76. # shoulder
  77. left_shoulder_x, left_shoulder_y = keypoint[get_keypoint.LEFT_SHOULDER]
  78. right_shoulder_x, right_shoulder_y = keypoint[get_keypoint.RIGHT_SHOULDER]
  79. # elbow
  80. left_elbow_x, left_elbow_y = keypoint[get_keypoint.LEFT_ELBOW]
  81. right_elbow_x, right_elbow_y = keypoint[get_keypoint.RIGHT_ELBOW]
  82. # wrist
  83. left_wrist_x, left_wrist_y = keypoint[get_keypoint.LEFT_WRIST]
  84. right_wrist_x, right_wrist_y = keypoint[get_keypoint.RIGHT_WRIST]
  85. # hip
  86. left_hip_x, left_hip_y = keypoint[get_keypoint.LEFT_HIP]
  87. right_hip_x, right_hip_y = keypoint[get_keypoint.RIGHT_HIP]
  88. # knee
  89. left_knee_x, left_knee_y = keypoint[get_keypoint.LEFT_KNEE]
  90. right_knee_x, right_knee_y = keypoint[get_keypoint.RIGHT_KNEE]
  91. # ankle
  92. left_ankle_x, left_ankle_y = keypoint[get_keypoint.LEFT_ANKLE]
  93. right_ankle_x, right_ankle_y = keypoint[get_keypoint.RIGHT_ANKLE]
  94. return [
  95. nose_x, nose_y,
  96. left_shoulder_x, left_shoulder_y,
  97. right_shoulder_x, right_shoulder_y,
  98. left_elbow_x, left_elbow_y,
  99. right_elbow_x, right_elbow_y,
  100. left_wrist_x, left_wrist_y,
  101. right_wrist_x, right_wrist_y,
  102. left_hip_x, left_hip_y,
  103. right_hip_x, right_hip_y,
  104. left_knee_x, left_knee_y,
  105. right_knee_x, right_knee_y,
  106. left_ankle_x, left_ankle_y,
  107. right_ankle_x, right_ankle_y
  108. ]
  109. class Helmet:
  110. def __init__(self):
  111. self.flag = False
  112. def getflag(self,det,persondet,annotator,fence=0,point=None,names=None,rname=None,num=1):
  113. #print(type(det))
  114. self.flag = False
  115. for *xyxy, conf, cls in reversed(det):
  116. c = int(cls)
  117. labelname = names[c]
  118. if labelname in rname:
  119. if fence == 1:
  120. pointa = strtolstl(point)
  121. for poi in pointa:
  122. p1 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3),
  123. xyxy[3].cpu().item())
  124. p2 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3 * 2),
  125. xyxy[3].cpu().item())
  126. pt = [p1, p2]
  127. inflag = mat.Path(poi).contains_points(pt)
  128. if inflag.any():
  129. if persondet is None:
  130. self.flag = True
  131. # c = int(cls) # integer class
  132. # label = f'{self.names[c]} {conf:.2f}'
  133. label = None
  134. annotator.box_label(xyxy, None, color=(0, 0, 255))
  135. else:
  136. for person in persondet:
  137. personinflag = mat.Path(person).contains_points(pt)
  138. if personinflag.any():
  139. annotator.box_label(xyxy, None, color=(0, 0, 255))
  140. self.flag = True
  141. else:
  142. if persondet is None:
  143. self.flag = True
  144. # c = int(cls) # integer class
  145. # label = f'{self.names[c]} {conf:.2f}'
  146. label = None
  147. annotator.box_label(xyxy, None, color=(0, 0, 255))
  148. else:
  149. for person in persondet:
  150. p1 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3),
  151. xyxy[3].cpu().item())
  152. p2 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3 * 2),
  153. xyxy[3].cpu().item())
  154. pt = [p1, p2]
  155. personinflag = mat.Path(person).contains_points(pt)
  156. if personinflag.any():
  157. annotator.box_label(xyxy, None, color=(0, 0, 255))
  158. self.flag = True
  159. return self.flag
  160. class Uniform:
  161. def __init__(self):
  162. self.flag = False
  163. def getflag(self, det, persondet,annotator, fence=0, point=None, names=None, rname=None,num=1):
  164. self.flag = False
  165. for *xyxy, conf, cls in reversed(det):
  166. c = int(cls)
  167. labelname = names[c]
  168. if labelname in rname:
  169. if fence == 1:
  170. pointa = strtolstl(point)
  171. for poi in pointa:
  172. p1 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3),
  173. xyxy[3].cpu().item())
  174. p2 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3 * 2),
  175. xyxy[3].cpu().item())
  176. pt = [p1, p2]
  177. inflag = mat.Path(poi).contains_points(pt)
  178. if inflag.any():
  179. if persondet is None:
  180. self.flag = True
  181. # c = int(cls) # integer class
  182. # label = f'{self.names[c]} {conf:.2f}'
  183. label = None
  184. annotator.box_label(xyxy, None, color=(0, 0, 255))
  185. else:
  186. for person in persondet:
  187. p1 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3),
  188. xyxy[3].cpu().item())
  189. p2 = (
  190. int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3 * 2),
  191. xyxy[3].cpu().item())
  192. pt = [p1, p2]
  193. personinflag = mat.Path(person).contains_points(pt)
  194. if personinflag.any():
  195. annotator.box_label(xyxy, None, color=(0, 0, 255))
  196. self.flag = True
  197. else:
  198. if persondet is None:
  199. self.flag = True
  200. # c = int(cls) # integer class
  201. # label = f'{self.names[c]} {conf:.2f}'
  202. label = None
  203. annotator.box_label(xyxy, None, color=(0, 0, 255))
  204. else:
  205. for person in persondet:
  206. p1 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3),
  207. xyxy[3].cpu().item())
  208. p2 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3 * 2),
  209. xyxy[3].cpu().item())
  210. pt = [p1, p2]
  211. personinflag = mat.Path(person).contains_points(pt)
  212. if personinflag.any():
  213. annotator.box_label(xyxy, None, color=(0, 0, 255))
  214. self.flag = True
  215. return self.flag
  216. class Fall:
  217. def __init__(self):
  218. self.flag = False
  219. def getflag(self, det, persondet,annotator, fence=0, point=None, names=None, rname=None,num=1):
  220. self.flag = False
  221. for *xyxy, conf, cls in reversed(det):
  222. c = int(cls)
  223. labelname = names[c]
  224. if labelname in rname:
  225. if fence == 1:
  226. pointa = strtolstl(point)
  227. for poi in pointa:
  228. p1 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3),
  229. xyxy[3].cpu().item())
  230. p2 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3 * 2),
  231. xyxy[3].cpu().item())
  232. pt = [p1, p2]
  233. inflag = mat.Path(poi).contains_points(pt)
  234. if inflag.any():
  235. if persondet is None:
  236. self.flag = True
  237. # c = int(cls) # integer class
  238. # label = f'{self.names[c]} {conf:.2f}'
  239. label = None
  240. annotator.box_label(xyxy, None, color=(0, 0, 255))
  241. else:
  242. for person in persondet:
  243. personinflag = mat.Path(person).contains_points(pt)
  244. if personinflag.any():
  245. annotator.box_label(xyxy, None, color=(0, 0, 255))
  246. self.flag = True
  247. else:
  248. if persondet is None:
  249. self.flag = True
  250. # c = int(cls) # integer class
  251. # label = f'{self.names[c]} {conf:.2f}'
  252. label = None
  253. annotator.box_label(xyxy, None, color=(0, 0, 255))
  254. else:
  255. for person in persondet:
  256. p1 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3),
  257. xyxy[3].cpu().item())
  258. p2 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3 * 2),
  259. xyxy[3].cpu().item())
  260. pt = [p1, p2]
  261. personinflag = mat.Path(person).contains_points(pt)
  262. if personinflag.any():
  263. annotator.box_label(xyxy, None, color=(0, 0, 255))
  264. self.flag = True
  265. return self.flag
  266. class newFall:
  267. def __init__(self):
  268. self.flag = False
  269. self.pose_classfier_model = Model(None, 13, 2, 2)
  270. self.pose_classfier_model.load_state_dict(torch.load("posefallcls.pt"))
  271. self.pose_classfier_model.eval()
  272. self.pose_classfier_model.to(0)
  273. def getflag(self, det, persondet,annotator, fence=0, point=None, names=None, rname=None,num=1,imshape=None):
  274. self.flag = False
  275. kptshape = [17,3]
  276. pred_kpts = det[:, 6:].view(len(det), *kptshape) if len(det) else det[:, 6:]
  277. pred_kpts = ops.scale_coords(imshape, pred_kpts, annotator.result().shape)
  278. results =Results(annotator.result(), path=None, names=names, boxes=det[:, :6], keypoints=pred_kpts)
  279. print(results.boxes)
  280. if len(point) > 1:
  281. self.polygon_areas = [Polygon(strtolstl(point)[0])]
  282. print(self.polygon_areas)
  283. else:
  284. self.polygon_areas = None
  285. tmppersondet = []
  286. if self.polygon_areas is not None:
  287. for person in persondet:
  288. polygon_box = Polygon(
  289. [(person[0], person[1]), (person[2], person[3]), (person[4], person[5]), (person[6], person[7])])
  290. intersection_areas = [polygon_area.intersection(polygon_box).area for polygon_area in
  291. self.polygon_areas]
  292. if sum(intersection_areas) == 0:
  293. continue
  294. intersection_areas_ratio = sorted(
  295. [intersection_area / polygon_box.area for intersection_area in intersection_areas])
  296. # print(intersection_areas_ratio)
  297. if intersection_areas_ratio[-1] < 0.9:
  298. continue
  299. tmppersondet.append(person)
  300. persondet = tmppersondet
  301. boxes = results.boxes.xyxy.cpu().numpy().tolist()
  302. confs = results.boxes.conf.cpu().numpy().tolist()
  303. all_keypoints = results.keypoints.data.cpu().numpy().tolist()
  304. pose_classfier_results = []
  305. for box, conf, keypoints in zip(boxes, confs, all_keypoints):
  306. iouflag = False
  307. for personbox in persondet:
  308. iou, _ = compute_IOU(box, personbox)
  309. print(f'judgeiou = {iou}')
  310. if iou > 0.5:
  311. iouflag = True
  312. break;
  313. if not iouflag:
  314. break
  315. x1, y1, x2, y2 = box
  316. x, y, w, h = x1, y1, x2 - x1, y2 - y1
  317. n_keypoints = [[(kp[0] - x) / w - 0.5, (kp[1] - y) / h - 0.5] if kp[0] > 0 and kp[1] > 0 else kp[:2] for kp
  318. in keypoints]
  319. n_keypoints = extract_keypoint(self.get_keypoint, n_keypoints)
  320. if n_keypoints[-12:].count(0) >= 2 * 2:
  321. continue
  322. if n_keypoints.count(0) >= 4 * 2:
  323. continue
  324. if w < h:
  325. continue
  326. pose_data = torch.Tensor([n_keypoints]).to(self.device)
  327. pose_data = pose_data.reshape(1, 13, 2)
  328. with torch.no_grad():
  329. p = self.pose_classfier_model(pose_data)
  330. prob = F.softmax(p)
  331. index = prob.argmax()
  332. if index == 0:
  333. score = float(prob[0][index].cpu().numpy())
  334. pose_classfier_results.append(box)
  335. if len(pose_classfier_results)>0:
  336. for xyxy in pose_classfier_results:
  337. annotator.box_label(xyxy, None, color=(0, 0, 255))
  338. self.flag = True
  339. return self.flag
  340. class Personcount:
  341. def __init__(self):
  342. self.flag = False
  343. def getflag(self, det,persondet, annotator, fence=0, point=None, names=None, rname=None,num=1):
  344. self.flag = False
  345. detnum = 0
  346. for *xyxy, conf, cls in reversed(det):
  347. c = int(cls)
  348. labelname = names[c]
  349. if labelname in rname:
  350. if fence == 1:
  351. pointa = strtolstl(point)
  352. for poi in pointa:
  353. p1 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3),
  354. xyxy[3].cpu().item())
  355. p2 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3 * 2),
  356. xyxy[3].cpu().item())
  357. pt = [p1, p2]
  358. inflag = mat.Path(poi).contains_points(pt)
  359. if inflag.any():
  360. if persondet is None:
  361. #self.flag = True
  362. detnum = detnum+1
  363. # c = int(cls) # integer class
  364. # label = f'{self.names[c]} {conf:.2f}'
  365. label = None
  366. annotator.box_label(xyxy, None, color=(0, 0, 255))
  367. else:
  368. for person in persondet:
  369. personinflag = mat.Path(person).contains_points(pt)
  370. if personinflag.any():
  371. detnum = detnum+1
  372. annotator.box_label(xyxy, None, color=(0, 0, 255))
  373. #self.flag = True
  374. else:
  375. if persondet is None:
  376. #self.flag = True
  377. detnum = detnum+1
  378. # c = int(cls) # integer class
  379. # label = f'{self.names[c]} {conf:.2f}'
  380. label = None
  381. annotator.box_label(xyxy, None, color=(0, 0, 255))
  382. else:
  383. for person in persondet:
  384. p1 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3),
  385. xyxy[3].cpu().item())
  386. p2 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3 * 2),
  387. xyxy[3].cpu().item())
  388. pt = [p1, p2]
  389. personinflag = mat.Path(person).contains_points(pt)
  390. if personinflag.any():
  391. detnum = detnum+1
  392. annotator.box_label(xyxy, None, color=(0, 0, 255))
  393. #self.flag = True
  394. if detnum >= num:
  395. self.flag = True
  396. return self.flag
  397. class Arm:
  398. def __init__(self):
  399. self.flag = False
  400. def getflag(self, det, persondet,annotator, fence=0, point=None, names=None, rname=None,num=1):
  401. self.flag = False
  402. for *xyxy, conf, cls in reversed(det):
  403. c = int(cls)
  404. labelname = names[c]
  405. if labelname in rname:
  406. if fence == 1:
  407. pointa = strtolstl(point)
  408. for poi in pointa:
  409. p1 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3),
  410. xyxy[3].cpu().item())
  411. p2 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3 * 2),
  412. xyxy[3].cpu().item())
  413. pt = [p1, p2]
  414. inflag = mat.Path(poi).contains_points(pt)
  415. if inflag.any():
  416. if persondet is None:
  417. self.flag = True
  418. # c = int(cls) # integer class
  419. # label = f'{self.names[c]} {conf:.2f}'
  420. label = None
  421. annotator.box_label(xyxy, None, color=(0,0,255))
  422. else:
  423. for person in persondet:
  424. personinflag = mat.Path(person).contains_points(pt)
  425. if personinflag.any():
  426. annotator.box_label(xyxy, None, color=(0, 0, 255))
  427. self.flag = True
  428. else:
  429. if persondet is None:
  430. self.flag = True
  431. # c = int(cls) # integer class
  432. # label = f'{self.names[c]} {conf:.2f}'
  433. label = None
  434. annotator.box_label(xyxy, None, color=(0, 0, 255))
  435. else:
  436. for person in persondet:
  437. p1 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3),
  438. xyxy[3].cpu().item())
  439. p2 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3 * 2),
  440. xyxy[3].cpu().item())
  441. pt = [p1, p2]
  442. personinflag = mat.Path(np.array(person).reshape(-1,2)).contains_points(pt)
  443. if personinflag.any():
  444. annotator.box_label(xyxy, None, color=(0, 0, 255))
  445. self.flag = True
  446. return self.flag
  447. class Bag:
  448. def __init__(self):
  449. self.flag = False
  450. def getflag(self, det, persondet,annotator, fence=0, point=None, names=None, rname=None,num=1):
  451. self.flag = False
  452. for *xyxy, conf, cls in reversed(det):
  453. c = int(cls)
  454. labelname = names[c]
  455. if labelname in rname:
  456. if fence == 1:
  457. pointa = strtolstl(point)
  458. for poi in pointa:
  459. p1 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3),
  460. xyxy[3].cpu().item())
  461. p2 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3 * 2),
  462. xyxy[3].cpu().item())
  463. pt = [p1, p2]
  464. inflag = mat.Path(poi).contains_points(pt)
  465. if inflag.any():
  466. if persondet is None:
  467. self.flag = True
  468. # c = int(cls) # integer class
  469. # label = f'{self.names[c]} {conf:.2f}'
  470. label = None
  471. annotator.box_label(xyxy, None, color=(0, 0, 255))
  472. else:
  473. for person in persondet:
  474. personinflag = mat.Path(person).contains_points(pt)
  475. if personinflag.any():
  476. annotator.box_label(xyxy, None, color=(0, 0, 255))
  477. self.flag = True
  478. else:
  479. if persondet is None:
  480. self.flag = True
  481. # c = int(cls) # integer class
  482. # label = f'{self.names[c]} {conf:.2f}'
  483. label = None
  484. annotator.box_label(xyxy, None, color=(0, 0, 255))
  485. else:
  486. for person in persondet:
  487. p1 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3),
  488. xyxy[3].cpu().item())
  489. p2 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3 * 2),
  490. xyxy[3].cpu().item())
  491. pt = [p1, p2]
  492. personinflag = mat.Path(person).contains_points(pt)
  493. if personinflag.any():
  494. annotator.box_label(xyxy, None, color=(0, 0, 255))
  495. self.flag = True
  496. return self.flag
  497. class Cross:
  498. def __init__(self):
  499. self.flag = False
  500. def getflag(self, det, persondet,annotator, fence=0, point=None, names=None, rname=None,num=1):
  501. self.flag = False
  502. detnum = 0
  503. for *xyxy, conf, cls in reversed(det):
  504. c = int(cls)
  505. labelname = names[c]
  506. if labelname in rname:
  507. if fence == 1:
  508. pointa = strtolstl(point)
  509. for poi in pointa:
  510. p1 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3),
  511. xyxy[3].cpu().item())
  512. p2 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3 * 2),
  513. xyxy[3].cpu().item())
  514. pt = [p1, p2]
  515. inflag = mat.Path(poi).contains_points(pt)
  516. if inflag.any():
  517. if persondet is None:
  518. detnum = detnum+1
  519. self.flag = True
  520. # c = int(cls) # integer class
  521. # label = f'{self.names[c]} {conf:.2f}'
  522. label = None
  523. annotator.box_label(xyxy, None, color=(0, 0, 255))
  524. else:
  525. for person in persondet:
  526. personinflag = mat.Path(person).contains_points(pt)
  527. if personinflag.any():
  528. detnum = detnum+1
  529. annotator.box_label(xyxy, None, color=(0, 0, 255))
  530. self.flag = True
  531. else:
  532. if persondet is None:
  533. self.flag = True
  534. # c = int(cls) # integer class
  535. # label = f'{self.names[c]} {conf:.2f}'
  536. detnum = detnum+1
  537. label = None
  538. annotator.box_label(xyxy, None, color=(0, 0, 255))
  539. else:
  540. for person in persondet:
  541. p1 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3),
  542. xyxy[3].cpu().item())
  543. p2 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3 * 2),
  544. xyxy[3].cpu().item())
  545. pt = [p1, p2]
  546. personinflag = mat.Path(person).contains_points(pt)
  547. if personinflag.any():
  548. detnum = detnum +1
  549. annotator.box_label(xyxy, None, color=(0, 0, 255))
  550. self.flag = True
  551. return self.flag
  552. class Extinguisher:
  553. def __init__(self):
  554. self.flag = False
  555. def getflag(self, det, persondet,annotator, fence=0, point=None, names=None, rname=None,num=1):
  556. self.flag = False
  557. for *xyxy, conf, cls in reversed(det):
  558. c = int(cls)
  559. labelname = names[c]
  560. if labelname in rname:
  561. if fence == 1:
  562. pointa = strtolstl(point)
  563. for poi in pointa:
  564. p1 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3),
  565. xyxy[3].cpu().item())
  566. p2 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3 * 2),
  567. xyxy[3].cpu().item())
  568. pt = [p1, p2]
  569. inflag = mat.Path(poi).contains_points(pt)
  570. if inflag.any():
  571. if persondet is None:
  572. self.flag = True
  573. # c = int(cls) # integer class
  574. # label = f'{self.names[c]} {conf:.2f}'
  575. label = None
  576. annotator.box_label(xyxy, None, color=(0, 0, 255))
  577. else:
  578. for person in persondet:
  579. personinflag = mat.Path(person).contains_points(pt)
  580. if personinflag.any():
  581. annotator.box_label(xyxy, None, color=(0, 0, 255))
  582. self.flag = True
  583. else:
  584. if persondet is None:
  585. self.flag = True
  586. # c = int(cls) # integer class
  587. # label = f'{self.names[c]} {conf:.2f}'
  588. label = None
  589. annotator.box_label(xyxy, None, color=(0, 0, 255))
  590. else:
  591. for person in persondet:
  592. p1 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3),
  593. xyxy[3].cpu().item())
  594. p2 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3 * 2),
  595. xyxy[3].cpu().item())
  596. pt = [p1, p2]
  597. personinflag = mat.Path(person).contains_points(pt)
  598. if personinflag.any():
  599. annotator.box_label(xyxy, None, color=(0, 0, 255))
  600. self.flag = True
  601. return self.flag
  602. def calculate_iou(box1, box2):
  603. # 计算交集区域 也就是找到次左上 次右下
  604. x1_int = max(box1[0], box2[0])
  605. y1_int = max(box1[1], box2[1])
  606. x2_int = min(box1[2], box2[2])
  607. y2_int = min(box1[3], box2[3])
  608. # 交集区域的宽高
  609. width_int = max(0, x2_int - x1_int)
  610. height_int = max(0, y2_int - y1_int)
  611. area_int = width_int * height_int
  612. # 计算两个框的面积
  613. area_box1 = (box1[2] - box1[0]) * (box1[3] - box1[1])
  614. area_box2 = (box2[2] - box2[0]) * (box2[3] - box1[1])
  615. # 计算并集面积
  616. area_union = area_box1 + area_box2 - area_int
  617. # 计算IoU
  618. iou = area_int / area_union if area_union > 0 else 0
  619. return iou
  620. def check_cls4_overlap(person_box, target_box, cls4_boxes):
  621. """
  622. 检查是否有 cls4 物体在目标框与人物框交集区域内,并计算交集面积与 cls4 物体面积的重叠比率。
  623. 返回重叠比率最大值以及其对应的交集区域坐标和 cls4 框。
  624. 参数:
  625. person_box (tuple): 人物框 (x_min, y_min, x_max, y_max)
  626. target_box (tuple): 目标框 (x_min, y_min, x_max, y_max)
  627. cls4_boxes (list): cls4 物体框的列表,每个框为 (x_min, y_min, x_max, y_max)
  628. 返回:
  629. tuple:
  630. - 最大的重叠比率 (float),如果没有符合条件的物体则为 None。
  631. - 最大重叠比率对应的交集区域的坐标 (inter_x1, inter_y1)。
  632. - 对应的 cls4 框 (tuple),如果没有符合条件的物体则为 None。
  633. """
  634. # 计算目标框与人物框的交集区域
  635. min_x = max(person_box[0], target_box[0])
  636. min_y = max(person_box[1], target_box[1])
  637. max_x = min(person_box[2], target_box[2])
  638. max_y = min(person_box[3], target_box[3])
  639. target_area = (min_x, min_y, max_x, max_y) # 交集区域
  640. max_overlap_ratio = -1 # 用于存储最大的重叠比率 这设置为-1有助于区别是否计算了
  641. best_inter_x1 = 0 # 用于存储最大重叠比率对应的交集坐标
  642. best_inter_y1 = 0
  643. best_cls4_box = [] # 用于存储对应的 cls4 框 不能初始化为整数0 整数不可迭代 后序不能添加
  644. # 检查是否有 cls4 物体在交集区域内
  645. for cls4_box in cls4_boxes:
  646. # 判断 cls4 框是否与交集区域有交集
  647. inter_x1 = max(cls4_box[0], target_area[0])
  648. inter_y1 = max(cls4_box[1], target_area[1])
  649. inter_x2 = min(cls4_box[2], target_area[2])
  650. inter_y2 = min(cls4_box[3], target_area[3])
  651. if inter_x1 < inter_x2 and inter_y1 < inter_y2:
  652. # 计算交集区域的面积
  653. intersection_area = (inter_x2 - inter_x1) * (inter_y2 - inter_y1)
  654. #print("交集的面积", intersection_area)
  655. # 计算 cls4_box 的面积
  656. cls4_area = (cls4_box[2] - cls4_box[0]) * (cls4_box[3] - cls4_box[1])
  657. #print("cls4_area的面积是", cls4_area)
  658. # 计算交集区域占 cls4_box 面积的比例
  659. overlap_ratio = intersection_area / cls4_area
  660. # 更新最大重叠比率及其相关信息
  661. if max_overlap_ratio == 0 or overlap_ratio > max_overlap_ratio:
  662. max_overlap_ratio = overlap_ratio
  663. best_inter_x1 = inter_x1
  664. best_inter_y1 = inter_y1
  665. best_cls4_box = cls4_box
  666. return max_overlap_ratio, (best_inter_x1, best_inter_y1), best_cls4_box
  667. class Persontre1:
  668. def __init__(self):
  669. self.flag = False
  670. self.classifier_model = torch.load('/home/h3c/yolo/persontrecls.pt')
  671. def getflag(self, det, persondet,annotator, fence=0, point=None, names=None, rname=None,num=1,im0=None):
  672. self.flag = False
  673. dirp = {}
  674. dirf = {}
  675. for *xyxy, conf, cls in reversed(det):
  676. c = int(cls)
  677. labelname = names[c]
  678. if labelname in rname:
  679. if fence == 1:
  680. pointa = strtolstl(point)
  681. for poi in pointa:
  682. p1 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3),
  683. xyxy[3].cpu().item())
  684. p2 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3 * 2),
  685. xyxy[3].cpu().item())
  686. pt = [p1, p2]
  687. inflag = mat.Path(poi).contains_points(pt)
  688. if inflag.any():
  689. if persondet is None:
  690. self.flag = True
  691. # c = int(cls) # integer class
  692. # label = f'{self.names[c]} {conf:.2f}'
  693. label = None
  694. if c==0:
  695. dirp.setdefault(0,[])
  696. dirp[0].append(xyxy)
  697. elif c in [1,2]:
  698. dirp.setdefault(1,[])
  699. dirp[1].append(xyxy)
  700. dirf.setdefault(1,[])
  701. dirf[1].append(xyxy)
  702. elif c==3:
  703. dirp.setdefault(1,[])
  704. dirp[1].append(xyxy)
  705. elif c==4:
  706. dirf.setdefault(0,[])
  707. dirf[0].append(xyxy)
  708. #annotator.box_label(xyxy, None, color=(0, 0, 255))
  709. else:
  710. for person in persondet:
  711. personinflag = mat.Path(person).contains_points(pt)
  712. if personinflag.any():
  713. #annotator.box_label(xyxy, None, color=(0, 0, 255))
  714. #self.flag = True
  715. if c==0:
  716. dirp.setdefault(0,[])
  717. dirp[0].append(xyxy)
  718. elif c in [1,2]:
  719. dirp.setdefault(1,[])
  720. dirp[1].append(xyxy)
  721. dirf.setdefault(1,[])
  722. dirf[1].append(xyxy)
  723. elif c==3:
  724. dirp.setdefault(1,[])
  725. dirp[1].append(xyxy)
  726. elif c==4:
  727. dirf.setdefault(0,[])
  728. dirf[0].append(xyxy)
  729. else:
  730. if persondet is None:
  731. #self.flag = True
  732. # c = int(cls) # integer class
  733. # label = f'{self.names[c]} {conf:.2f}'
  734. #label = None
  735. #annotator.box_label(xyxy, None, color=(0, 0, 255))
  736. if c==0:
  737. dirp.setdefault(0,[])
  738. dirp[0].append(xyxy)
  739. elif c in [1,2]:
  740. dirp.setdefault(1,[])
  741. dirp[1].append(xyxy)
  742. dirf.setdefault(1,[])
  743. dirf[1].append(xyxy)
  744. elif c==3:
  745. dirp.setdefault(1,[])
  746. dirp[1].append(xyxy)
  747. elif c==4:
  748. dirf.setdefault(0,[])
  749. dirf[0].append(xyxy)
  750. else:
  751. for person in persondet:
  752. p1 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3),
  753. xyxy[3].cpu().item())
  754. p2 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3 * 2),
  755. xyxy[3].cpu().item())
  756. pt = [p1, p2]
  757. personinflag = mat.Path(person).contains_points(pt)
  758. if personinflag.any():
  759. #annotator.box_label(xyxy, None, color=(0, 0, 255))
  760. #self.flag = True
  761. if c==0:
  762. dirp.setdefault(0,[])
  763. dirp[0].append(xyxy)
  764. elif c in [1,2]:
  765. dirp.setdefault(1,[])
  766. dirp[1].append(xyxy)
  767. dirf.setdefault(1,[])
  768. dirf[1].append(xyxy)
  769. elif c==3:
  770. dirp.setdefault(1,[])
  771. dirp[1].append(xyxy)
  772. elif c==4:
  773. dirf.setdefault(0,[])
  774. dirf[0].append(xyxy)
  775. if len(dirp.keys()) == 2:
  776. claimg = []
  777. clapoint = []
  778. for person in dirp[0]:
  779. for other in dirp[1]:
  780. iou, newxyxy = compute_IOU(person, other)
  781. if iou>0.1:
  782. print(newxyxy)
  783. imgtmp = im0[int(newxyxy[1]):int(newxyxy[3]),int(newxyxy[0]):int(newxyxy[2])]
  784. imgtmp = imgtmp[...,::-1]
  785. imgtmp = Image.fromarray(imgtmp)
  786. imgten1 = test(imgtmp)
  787. claimg.append(imgten1)
  788. clapoint.append((newxyxy))
  789. result = clapre(self.classifier_model,claimg,clapoint)
  790. #imgten = imgten1[None]
  791. #imgten = imgten.to(0)
  792. #result = modelcla(imgten)
  793. #result = F.softmax(result, dim=1)
  794. #cla = result.argmax(1)
  795. if result is not None:
  796. self.flag = True
  797. for res in result:
  798. print(res)
  799. annotator.box_label(res, None, color=(0,0,255))
  800. if len(dirp.keys()) == 2:
  801. claimg = []
  802. clapoint = []
  803. for person in dirp[0]:
  804. for other in dirp[1]:
  805. iou, newxyxy = compute_IOU(person, other)
  806. if iou>0.1:
  807. print(newxyxy)
  808. imgtmp = im0[int(newxyxy[1]):int(newxyxy[3]),int(newxyxy[0]):int(newxyxy[2])]
  809. imgtmp = imgtmp[...,::-1]
  810. imgtmp = Image.fromarray(imgtmp)
  811. imgten1 = test(imgtmp)
  812. claimg.append(imgten1)
  813. clapoint.append((newxyxy))
  814. result = clapre(self.classifier_model,claimg,clapoint)
  815. #imgten = imgten1[None]
  816. #imgten = imgten.to(0)
  817. #result = modelcla(imgten)
  818. #result = F.softmax(result, dim=1)
  819. #cla = result.argmax(1)
  820. if result is not None:
  821. self.flag = True
  822. for res in result:
  823. print(res)
  824. annotator.box_label(res, None, color=(0,0,255))
  825. return self.flag
  826. class Persontree:
  827. def __init__(self):
  828. self.flag = False
  829. self.classifier_model = torch.load('/home/h3c/yolo/persontrecls.pt')
  830. def getflag(self, det, persondet,annotator, fence=0, point=None, names=None, rname=None,num=1,im0=None):
  831. self.flag = False
  832. target_classes = [1, 2, 3]
  833. results = Results(annotator.result(),path=None,names=names,boxes=det)
  834. boxes = results.boxes
  835. person_boxes = []
  836. target_boxes = []
  837. cls4_boxes = []
  838. # 处理检测结果
  839. for i in range(len(boxes)):
  840. cls = int(boxes.cls[i].item())
  841. con = boxes.conf[i].item()
  842. if cls == 0 and con > 0.1: # 如果是 "person" 类别
  843. x1, y1, x2, y2 = boxes.xyxy[i].tolist()
  844. person_boxes.append([x1, y1, x2, y2])
  845. if cls in target_classes and con > 0.1: # 目标类别(bag, box, cart)
  846. x1, y1, x2, y2 = boxes.xyxy[i].tolist()
  847. target_boxes.append([x1, y1, x2, y2])
  848. if cls == 4 and con > 0.1: # 如果是 "cls 4" 类别
  849. x1, y1, x2, y2 = boxes.xyxy[i].tolist()
  850. cls4_boxes.append([x1, y1, x2, y2])
  851. # 如果检测到 "person" 类别和目标框,计算IoU
  852. if person_boxes and target_boxes:
  853. for i, person_box in enumerate(person_boxes):
  854. person_center_y = (person_box[1] + person_box[3]) / 2
  855. for j, target_box in enumerate(target_boxes):
  856. target_center_y = (target_box[1] + target_box[3]) / 2
  857. # 判断目标框的中心点是否在person框的下方
  858. if target_center_y + 20 > person_center_y: # 根据需要调整此阈值
  859. iou = calculate_iou(person_box, target_box)
  860. if iou > 0: # IoU大于0,进入新的判断
  861. # 创建一个包围person和target框的区域 本来思路是判断脚是否在这个大框框里面 但是这个不合理 应该判断脚是不是在这个交集里面,再检测脚和人与物交集有没有交集
  862. min_x = max(person_box[0], target_box[0])
  863. min_y = max(person_box[1], target_box[1])
  864. max_x = min(person_box[2], target_box[2])
  865. max_y = min(person_box[3], target_box[3])
  866. target_area = (min_x, min_y, max_x, max_y)
  867. # 检查是否有cls 4物体在这个区域内
  868. for cls4_box in cls4_boxes: #比较巧妙 提前存储这个变量 然后检测这个物体是不是在这里面
  869. # 判断cls 4框是否与这个区域有交集
  870. inter_x1 = max(cls4_box[0], target_area[0])
  871. inter_y1 = max(cls4_box[1], target_area[1])
  872. inter_x2 = min(cls4_box[2], target_area[2])
  873. inter_y2 = min(cls4_box[3], target_area[3])
  874. if inter_x1 < inter_x2 and inter_y1 < inter_y2:
  875. # 计算交集区域的面积
  876. intersection_area = (inter_x2 - inter_x1) * (inter_y2 - inter_y1)
  877. # 计算 cls4_box 的面积
  878. cls4_area = (cls4_box[2] - cls4_box[0]) * (cls4_box[3] - cls4_box[1])
  879. # 计算交集区域占 cls4_box 面积的比例
  880. overlap_ratio = intersection_area / cls4_area
  881. if overlap_ratio > 0.5:
  882. self.flag = True
  883. return self.flag
  884. class Persontre:
  885. def __init__(self):
  886. self.flag = False
  887. self.classifier_model = torch.load('/home/h3c/yolo/persontrecls.pt')
  888. def getflag(self, det, persondet,annotator, fence=0, point=None, names=None, rname=None,num=1,im0=None):
  889. self.flag = False
  890. cls3 =3 #对cart单独一类
  891. cls4 = 4 # 新增加的类别编号(假设为 4)
  892. target_classes = [1, 2, 3]
  893. results = Results(annotator.result(),path=None,names=names,boxes=det)
  894. boxes = results.boxes
  895. person_boxes = [] # 人 车子 脚 以及 指定区域内的脚
  896. cls3_boxes = []
  897. cls4_boxes = []
  898. best_cls4_box = []
  899. # 处理检测结果
  900. for i in range(len(boxes)):
  901. cls = int(boxes.cls[i].item())
  902. con = boxes.conf[i].item()
  903. if cls == 0 and con > 0.1: # 如果是 "person" 类别 先把对应类别添加上去 先把每一个识别物体输入上去
  904. x1, y1, x2, y2 = boxes.xyxy[i].tolist()
  905. person_boxes.append([x1, y1, x2, y2])
  906. if cls == cls3 and con > 0.1: # 目标类别 cart
  907. x1, y1, x2, y2 = boxes.xyxy[i].tolist()
  908. cls3_boxes.append([x1, y1, x2, y2])
  909. if cls == cls4 and con > 0.1: # 如果是 "cls 4" 类别
  910. x1, y1, x2, y2 = boxes.xyxy[i].tolist()
  911. cls4_boxes.append([x1, y1, x2, y2])
  912. # 如果检测到 "person" 类别和目标框,计算IoU
  913. if person_boxes and cls3_boxes: # 先查看这俩个类别有没有
  914. for i, person_box in enumerate(person_boxes):
  915. for j, cls3_box in enumerate(cls3_boxes):
  916. # 判断目标框的中心点是否在person框的下方
  917. iou = calculate_iou(person_box, cls3_box)
  918. # 踩的逻辑 一个是要求车子和人有交并比 其次判断脚是不是在这个交并比内 并且比重不能太低
  919. if iou > 0.2: # 用来判断坐 如果iou足够高 就视为是坐
  920. # 加载图像并绘制标注
  921. # 看看这个值大概有多少 好衡量一下
  922. #print(f"这个iou大于0.2的 这是第{frame_idx},iou是{iou}") # 写入介绍
  923. annotator.box_label(person_box, None, color=(0, 0, 255))
  924. annotator.box_label(cls3_box, None, color=(0, 0, 255))
  925. self.flag = True
  926. #print("这是坐",f"{saved_image_path}")
  927. elif iou > 0 : # IoU大于0,进入新的判断 代表不是坐
  928. # 创建一个包围person和target框的区域 本来思路是判断脚是否在这个大框框里面 但是这个不合理 应该判断脚是不是在这个交集里面,再检测脚和人与物交集有没有交集
  929. overlap_ratio, inter_xy, best_cls4_box1 = check_cls4_overlap(person_box, cls3_box,cls4_boxes)
  930. best_cls4_box.extend(best_cls4_box1) #拿到这四个点的坐标
  931. inter_x1, inter_y1 = inter_xy
  932. # 如果占比大于某个阈值,可以执行进一步的操作
  933. if overlap_ratio > 0.2:
  934. annotator.box_label(person_box, None, color=(0, 0, 255))
  935. annotator.box_label(cls3_box, None, color=(0, 0, 255))
  936. annotator.box_label(best_cls4_box, None, color=(0, 0, 255))
  937. self.flag = True
  938. class newPersontre:
  939. def __init__(self):
  940. self.flag = False
  941. self.classifier_model = torch.load('/home/h3c/yolo/persontrecls.pt')
  942. def getflag(self, det, persondet, annotator, fence=0, point=None, names=None, rname=None, num=1, im0=None):
  943. self.flag = False
  944. cls3 = 1 # 对cart单独一类
  945. # cls4 = 4 # 新增加的类别编号(假设为 4)
  946. # target_classes = [1, 2, 3]
  947. results = Results(annotator.result(), path=None, names=names, boxes=det)
  948. boxes = results.boxes
  949. print(boxes)
  950. person_boxes = [] # 人 车子 脚 以及 指定区域内的脚
  951. cls3_boxes = []
  952. # cls4_boxes = []
  953. # best_cls4_box = []
  954. # 处理检测结果
  955. for i in range(len(boxes)):
  956. cls = int(boxes.cls[i].item())
  957. con = boxes.conf[i].item()
  958. if cls == 0 and con > 0.1: # 如果是 "person" 类别 先把对应类别添加上去 先把每一个识别物体输入上去
  959. x1, y1, x2, y2 = boxes.xyxy[i].tolist()
  960. person_boxes.append([x1, y1, x2, y2])
  961. if cls == cls3 and con > 0.1: # 目标类别 cart
  962. x1, y1, x2, y2 = boxes.xyxy[i].tolist()
  963. cls3_boxes.append([x1, y1, x2, y2])
  964. print(person_boxes)
  965. print(cls3_boxes)
  966. # 如果检测到 "person" 类别和目标框,计算IoU
  967. if person_boxes and cls3_boxes: # 先查看这俩个类别有没有
  968. for i, person_box in enumerate(person_boxes):
  969. for j, cls3_box in enumerate(cls3_boxes):
  970. # 判断是否存在交集 而且不能低
  971. iou = calculate_iou(person_box, cls3_box)
  972. print(f"IOU的大小这是第", iou)
  973. if iou > 0.15: # 用来判断坐 如果iou足够高 就视为是坐
  974. # 加载图像并绘制标注
  975. # 看看这个值大概有多少 好衡量一下
  976. print(f"这个iou大于0.2的 这是第,iou是{iou}") # 写入介绍
  977. # img = Image.fromarray(cv2.cvtColor(frame,
  978. # cv2.COLOR_BGR2RGB)) # 注意 cap.read 获取到的帧是numpy形式 不能直接配合Draw函数 需要转换
  979. # 创建绘图上下文
  980. # draw = ImageDraw.Draw(img)
  981. # 继续进行绘制操作
  982. # 绘制 "person" 类别框
  983. annotator.box_label(person_box, None, color=(0, 0, 255))
  984. # 绘制目标框(bag, box, cart)
  985. annotator.box_label(cls3_box, None, color=(0, 0, 255))
  986. self.flag = True
  987. return self.flag
  988. class Danager:
  989. def __init__(self):
  990. self.flag = False
  991. def getflag(self, det, persondet,annotator, fence=0, point=None, names=None, rname=None,num=1):
  992. self.flag = False
  993. for *xyxy, conf, cls in reversed(det):
  994. c = int(cls)
  995. labelname = names[c]
  996. if labelname in rname:
  997. if fence == 1:
  998. pointa = strtolstl(point)
  999. for poi in pointa:
  1000. p1 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 2),
  1001. int(xyxy[1].cpu().item() + (xyxy[3].cpu().item() - xyxy[1].cpu().item()) / 2))
  1002. #p2 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3 * 2),
  1003. #xyxy[3].cpu().item())
  1004. pt = [p1]
  1005. inflag = mat.Path(poi).contains_points(pt)
  1006. if inflag.any():
  1007. if persondet is None:
  1008. self.flag = True
  1009. # c = int(cls) # integer class
  1010. # label = f'{self.names[c]} {conf:.2f}'
  1011. label = None
  1012. annotator.box_label(xyxy, None, color=(0, 0, 255))
  1013. else:
  1014. for person in persondet:
  1015. personinflag = mat.Path(person).contains_points(pt)
  1016. if personinflag.any():
  1017. annotator.box_label(xyxy, None, color=(0, 0, 255))
  1018. self.flag = True
  1019. else:
  1020. if persondet is None:
  1021. self.flag = True
  1022. # c = int(cls) # integer class
  1023. # label = f'{self.names[c]} {conf:.2f}'
  1024. label = None
  1025. annotator.box_label(xyxy, None, color=(0, 0, 255))
  1026. else:
  1027. for person in persondet:
  1028. p1 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3),
  1029. xyxy[3].cpu().item())
  1030. p2 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3 * 2),
  1031. xyxy[3].cpu().item())
  1032. pt = [p1, p2]
  1033. personinflag = mat.Path(person).contains_points(pt)
  1034. if personinflag.any():
  1035. annotator.box_label(xyxy, None, color=(0, 0, 255))
  1036. self.flag = True
  1037. return self.flag
  1038. class CarHelmetBelt:
  1039. def __init__(self):
  1040. self.flag = False
  1041. def selectNoBeltPerson(self, person_objs, belt_objs):
  1042. objs = []
  1043. polygon_person = [Polygon(
  1044. [(left, top), (right, top), (right, bottom), (left, bottom)]) for left, top, right, bottom, _, _ in person_objs]
  1045. polygon_belt = [Polygon(
  1046. [(left, top), (right, top), (right, bottom), (left, bottom)]) for left, top, right, bottom, _, _ in belt_objs]
  1047. for person_obj, person in zip(person_objs, polygon_person):
  1048. with_belt = False
  1049. for belt in polygon_belt:
  1050. if person.intersection(belt).area / belt.area > 0.5:
  1051. with_belt = True
  1052. break
  1053. if not with_belt:
  1054. objs.append(person_obj)
  1055. return objs
  1056. def selectWithPersonHead(self, person_objs, head_objs):
  1057. objs = []
  1058. polygon_person = [Polygon(
  1059. [(left, top), (right, top), (right, top + (bottom - top)/2), (left, top + (bottom - top)/2)]) for left, top, right, bottom, _, _ in person_objs]
  1060. polygon_head = [Polygon(
  1061. [(left, top), (right, top), (right, bottom), (left, bottom)]) for left, top, right, bottom, _, _ in head_objs]
  1062. for head_obj, head in zip(head_objs, polygon_head):
  1063. with_person = False
  1064. for person in polygon_person:
  1065. print('head')
  1066. if person.intersection(head).area / head.area > 0.5:
  1067. with_person = True
  1068. break
  1069. if with_person:
  1070. objs.append(head_obj)
  1071. return objs
  1072. def getflag(self, det, persondet,annotator, fence=0, point=None, names=None, rname=None,num=1):
  1073. self.flag = False
  1074. results = Results(annotator.result(),path=None,names=names,boxes=det)
  1075. person_objs = []
  1076. head_objs = []
  1077. belt_objs = []
  1078. self.polygon_areas = [Polygon(strtolstl(point)[0])]
  1079. for result in results:
  1080. boxes = result.boxes
  1081. for box in boxes:
  1082. #print(box.conf.cpu())
  1083. left, top, right, bottom = box.xyxy.cpu().numpy().tolist()[0]
  1084. polygon_box = Polygon([(left, top), (right, top), (right, bottom), (left, bottom)])
  1085. intersection_areas = [polygon_area.intersection(polygon_box).area for polygon_area in self.polygon_areas ]
  1086. if sum(intersection_areas) == 0:
  1087. continue
  1088. intersection_areas_ratio = sorted([intersection_area / polygon_box.area for intersection_area in intersection_areas])
  1089. if intersection_areas_ratio[-1] < 0.9:
  1090. continue
  1091. conf = box.conf.cpu().numpy().tolist()[0]
  1092. cls = box.cls.cpu().numpy().tolist()[0]
  1093. if cls == 0:
  1094. person_objs.append([left, top, right, bottom, conf, names[cls]])
  1095. elif cls == 1:
  1096. head_objs.append([left, top, right, bottom, conf, names[cls]])
  1097. elif cls == 3:
  1098. belt_objs.append([left, top, right, bottom, conf, names[cls]])
  1099. #print(head_objs)
  1100. #print(person_objs)
  1101. illegal_objs = self.selectNoBeltPerson(person_objs, belt_objs) + self.selectWithPersonHead(person_objs, head_objs)
  1102. if len(illegal_objs)>0:
  1103. for obj in illegal_objs:
  1104. annotator.box_label(obj[:4], None, color=(0, 0, 255))
  1105. self.flag = True
  1106. return self.flag
  1107. class newUniformi1:
  1108. def __init__(self):
  1109. self.flag = False
  1110. def selectNoUniformPerson(self, person_objs, uniform_objs):
  1111. objs = []
  1112. print(person_objs)
  1113. print(uniform_objs)
  1114. polygon_person = [Polygon(
  1115. [(left, top), (right, top), (right, bottom), (left, bottom)]) for left, top, right, bottom, _, _ in person_objs]
  1116. polygon_uniform = [Polygon(
  1117. [(left, top), (right, top), (right, bottom), (left, bottom)]) for left, top, right, bottom, _, _ in uniform_objs]
  1118. for person_obj, person in zip(person_objs, polygon_person):
  1119. with_uniform = False
  1120. for uniform in polygon_uniform:
  1121. if person.intersection(uniform).area / uniform.area > 0.3:
  1122. with_uniform = True
  1123. break
  1124. if not with_uniform:
  1125. print(f'illperson_obj {person_obj} illpolygon_uniform {polygon_uniform}')
  1126. objs.append(person_obj)
  1127. return objs
  1128. def getflag(self, det, persondet,annotator, fence=0, point=None, names=None, rname=None,num=1):
  1129. self.flag = False
  1130. results = Results(annotator.result(),path=None,names=names,boxes=det)
  1131. print(results.boxes)
  1132. person_objs = []
  1133. uniform_objs = []
  1134. #belt_objs = []
  1135. if len(point)>1:
  1136. self.polygon_areas = [Polygon(strtolstl(point)[0])]
  1137. else:
  1138. self.polygon_areas = None
  1139. if persondet is not None:
  1140. if self.polygon_areas is not None:
  1141. for left, top, right,top,right, bottom,left,bottom in persondet:
  1142. polygon_box = Polygon([(left, top), (right, top), (right, bottom), (left, bottom)])
  1143. intersection_areas = [polygon_area.intersection(polygon_box).area for polygon_area in
  1144. self.polygon_areas]
  1145. if sum(intersection_areas) == 0:
  1146. continue
  1147. intersection_areas_ratio = sorted(
  1148. [intersection_area / polygon_box.area for intersection_area in intersection_areas])
  1149. print(f'inter = {intersection_areas_ratio}')
  1150. if intersection_areas_ratio[-1] >= 0.3:
  1151. print("person in check space!!!")
  1152. width = right - left
  1153. height = bottom - top
  1154. print(f'{left}, {top}, {right},{top},{right}, {bottom},{left},{bottom}')
  1155. print(f'hw = {width* height}')
  1156. if width * height > 10000:
  1157. person_objs.append([left, top, right, bottom, 0.25, 'person'])
  1158. for result in results:
  1159. boxes = result.boxes
  1160. for box in boxes:
  1161. left, top, right, bottom = box.xyxy.cpu().numpy().tolist()[0]
  1162. # if self.polygon_areas is not None :
  1163. # if persondet is None and box.cls.cpu().numpy().tolist()[0] == 4:
  1164. # polygon_box = Polygon([(left, top), (right, top), (right, bottom), (left, bottom)])
  1165. #
  1166. # intersection_areas = [polygon_area.intersection(polygon_box).area for polygon_area in self.polygon_areas ]
  1167. # if sum(intersection_areas) == 0:
  1168. # continue
  1169. #
  1170. # intersection_areas_ratio = sorted([intersection_area / polygon_box.area for intersection_area in intersection_areas])
  1171. # print(f'inter = {intersection_areas_ratio}')
  1172. # if intersection_areas_ratio[-1] < 0.3:
  1173. # continue
  1174. conf = box.conf.cpu().numpy().tolist()[0]
  1175. cls = box.cls.cpu().numpy().tolist()[0]
  1176. # if persondet is not None:
  1177. # if cls == 4 and conf >=0.7:
  1178. # width = right - left
  1179. # height = bottom - top
  1180. # if width * height >10000:
  1181. # person_objs.append([left, top, right, bottom, conf, names[cls]])
  1182. if cls in [1,2]:
  1183. #width = right - left
  1184. #height = bottom - top
  1185. #if width * height >4096:
  1186. uniform_objs.append([left, top, right, bottom, conf, names[cls]])
  1187. print(f'personobjs = {person_objs}')
  1188. print(f'uniformobjs = {uniform_objs}')
  1189. illegal_objs = self.selectNoUniformPerson(person_objs, uniform_objs)
  1190. if len(illegal_objs)>0:
  1191. for obj in illegal_objs:
  1192. annotator.box_label(obj[:4], None, color=(0, 0, 255))
  1193. self.flag = True
  1194. return self.flag
  1195. class newHelmet:
  1196. def __init__(self):
  1197. self.flag = False
  1198. def selectNoHelmetPerson(self, person_objs, head_objs):
  1199. objs = []
  1200. polygon_person = [Polygon(
  1201. [(left, top), (right, top), (right, bottom), (left, bottom)]) for left, top, right, bottom, _, _ in person_objs]
  1202. polygon_head = [Polygon(
  1203. [(left, top), (right, top), (right, bottom), (left, bottom)]) for left, top, right, bottom, _, _ in head_objs]
  1204. for person_obj, person in zip(person_objs, polygon_person):
  1205. with_head = False
  1206. for head in polygon_head:
  1207. print('head')
  1208. if person.intersection(head).area / head.area > 0.3:
  1209. with_head = True
  1210. break
  1211. if with_head:
  1212. objs.append(person_obj)
  1213. return objs
  1214. def getflag(self, det, persondet,annotator, fence=0, point=None, names=None, rname=None,num=1):
  1215. self.flag = False
  1216. results = Results(annotator.result(),path=None,names=names,boxes=det)
  1217. person_objs = []
  1218. head_objs = []
  1219. helmet_objs = []
  1220. headtmp = []
  1221. #belt_objs = []
  1222. if len(point)>1:
  1223. self.polygon_areas = [Polygon(strtolstl(point)[0])]
  1224. else:
  1225. self.polygon_areas = None
  1226. for result in results:
  1227. boxes = result.boxes
  1228. for box in boxes:
  1229. left, top, right, bottom = box.xyxy.cpu().numpy().tolist()[0]
  1230. if self.polygon_areas is not None:
  1231. polygon_box = Polygon([(left, top), (right, top), (right, bottom), (left, bottom)])
  1232. intersection_areas = [polygon_area.intersection(polygon_box).area for polygon_area in self.polygon_areas ]
  1233. if sum(intersection_areas) == 0:
  1234. continue
  1235. intersection_areas_ratio = sorted([intersection_area / polygon_box.area for intersection_area in intersection_areas])
  1236. if intersection_areas_ratio[-1] < 0.9:
  1237. continue
  1238. conf = box.conf.cpu().numpy().tolist()[0]
  1239. cls = box.cls.cpu().numpy().tolist()[0]
  1240. #print(f'{conf} {cls}')
  1241. #print(cls in [5,6,7,8,9,10])
  1242. if cls == 4 and conf >=0.7:
  1243. width = right - left
  1244. height = bottom - top
  1245. if width * height >4096:
  1246. person_objs.append([left, top, right, bottom, conf, names[cls]])
  1247. elif cls == 0 and conf >= 0.5:
  1248. #width = right - left
  1249. #height = bottom - top
  1250. #if width * height >4096:
  1251. print('------')
  1252. headtmp.append([left, top, right, bottom, conf, names[cls]])
  1253. elif cls in [5,6,7,8,9,10]:
  1254. helmet_objs.append([(left, top), (right, top), (right, bottom), (left, bottom)])
  1255. print(f'headtmp= {headtmp}')
  1256. print(f'helmet_objs = {helmet_objs}')
  1257. for left, top, right, bottom, conf, name in headtmp:
  1258. flag = False
  1259. pt = [(int((left+right)/2),int((top+bottom)/2))]
  1260. for helmet in helmet_objs:
  1261. pflag = mat.Path(helmet).contains_points(pt)
  1262. if pflag.any():
  1263. flag = True
  1264. break
  1265. if not flag:
  1266. head_objs.append([left, top, right, bottom, conf, name])
  1267. illegal_objs = self.selectNoHelmetPerson(person_objs, head_objs)
  1268. if len(illegal_objs)>0:
  1269. for obj in illegal_objs:
  1270. annotator.box_label(obj[:4], None, color=(0, 0, 255))
  1271. self.flag = True
  1272. return self.flag
  1273. class newHelmetn:
  1274. def __init__(self):
  1275. self.flag = False
  1276. def selectNoHelmetPerson(self, person_objs, head_objs):
  1277. objs = []
  1278. polygon_person = [Polygon(
  1279. [(left, top), (right, top), (right, bottom), (left, bottom)]) for left, top, right, bottom, _, _ in person_objs]
  1280. polygon_head = [Polygon(
  1281. [(left, top), (right, top), (right, bottom), (left, bottom)]) for left, top, right, bottom, _, _ in head_objs]
  1282. for person_obj, person in zip(person_objs, polygon_person):
  1283. with_head = False
  1284. for head in polygon_head:
  1285. if person.intersection(head).area / head.area > 0.3:
  1286. with_head = True
  1287. break
  1288. if with_head:
  1289. objs.append(person_obj)
  1290. return objs
  1291. def getflag(self, det, persondet,annotator, fence=0, point=None, names=None, rname=None,num=1):
  1292. self.flag = False
  1293. results = Results(annotator.result(),path=None,names=names,boxes=det)
  1294. person_objs = []
  1295. head_objs = []
  1296. #belt_objs = []
  1297. if len(point)>1:
  1298. self.polygon_areas = [Polygon(strtolstl(point)[0])]
  1299. else:
  1300. self.polygon_areas = None
  1301. for result in results:
  1302. boxes = result.boxes
  1303. for box in boxes:
  1304. left, top, right, bottom = box.xyxy.cpu().numpy().tolist()[0]
  1305. if self.polygon_areas is not None:
  1306. polygon_box = Polygon([(left, top), (right, top), (right, bottom), (left, bottom)])
  1307. intersection_areas = [polygon_area.intersection(polygon_box).area for polygon_area in self.polygon_areas ]
  1308. if sum(intersection_areas) == 0:
  1309. continue
  1310. intersection_areas_ratio = sorted([intersection_area / polygon_box.area for intersection_area in intersection_areas])
  1311. if intersection_areas_ratio[-1] < 0.9:
  1312. continue
  1313. conf = box.conf.cpu().numpy().tolist()[0]
  1314. cls = box.cls.cpu().numpy().tolist()[0]
  1315. if cls == 4:
  1316. width = right - left
  1317. height = bottom - top
  1318. if width * height >4096:
  1319. person_objs.append([left, top, right, bottom, conf, names[cls]])
  1320. elif cls == 0:
  1321. #width = right - left
  1322. #height = bottom - top
  1323. #if width * height >4096:
  1324. head_objs.append([left, top, right, bottom, conf, names[cls]])
  1325. illegal_objs = self.selectNoHelmetPerson(person_objs, head_objs)
  1326. if len(illegal_objs)>0:
  1327. for obj in illegal_objs:
  1328. annotator.box_label(obj[:4], None, color=(0, 0, 255))
  1329. self.flag = True
  1330. return self.flag
  1331. class newUniformt:
  1332. def __init__(self):
  1333. self.flag = False
  1334. def selectNoUniformPerson(self, person_objs, uniform_objs):
  1335. objs = []
  1336. print(person_objs)
  1337. print(uniform_objs)
  1338. polygon_person = [Polygon(
  1339. [(left, top), (right, top), (right, bottom), (left, bottom)]) for left, top, right, bottom, _, _ in person_objs]
  1340. polygon_uniform = [Polygon(
  1341. [(left, top), (right, top), (right, bottom), (left, bottom)]) for left, top, right, bottom, _, _ in uniform_objs]
  1342. for person_obj, person in zip(person_objs, polygon_person):
  1343. with_uniform = False
  1344. for uniform in polygon_uniform:
  1345. if person.intersection(uniform).area / uniform.area > 0.3:
  1346. with_uniform = True
  1347. break
  1348. if not with_uniform:
  1349. print(f'illperson_obj {person_obj} illpolygon_uniform {polygon_uniform}')
  1350. objs.append(person_obj)
  1351. return objs
  1352. def selectHeadPerson(self, person_objs, head_objs):
  1353. objs = []
  1354. print(person_objs)
  1355. print(head_objs)
  1356. #personlist = []
  1357. polygon_person = [Polygon(
  1358. [(left, top), (right, top), (right, bottom), (left, bottom)]) for left, top, right, bottom, _, _ in person_objs]
  1359. polygon_head = [Polygon(
  1360. [(left, top), (right, top), (right, bottom), (left, bottom)]) for left, top, right, bottom, _, _ in uniform_objs]
  1361. for person_obj, person in zip(person_objs, polygon_person):
  1362. #with_uniform = False
  1363. for head in polygon_head:
  1364. if person.intersection(head).area / head.area > 0.3:
  1365. #with_uniform = True
  1366. #break
  1367. #if not with_uniform:
  1368. # print(f'illperson_obj {person_obj} illpolygon_uniform {polygon_uniform}')
  1369. objs.append(person_obj)
  1370. break
  1371. return objs
  1372. def getflag(self, det, persondet,annotator, fence=0, point=None, names=None, rname=None,num=1):
  1373. self.flag = False
  1374. results = Results(annotator.result(),path=None,names=names,boxes=det)
  1375. print(results.boxes)
  1376. person_objs = []
  1377. uniform_objs = []
  1378. head_objs = []
  1379. #belt_objs = []
  1380. if len(point)>1:
  1381. self.polygon_areas = [Polygon(strtolstl(point)[0])]
  1382. else:
  1383. self.polygon_areas = None
  1384. for result in results:
  1385. boxes = result.boxes
  1386. for box in boxes:
  1387. left, top, right, bottom = box.xyxy.cpu().numpy().tolist()[0]
  1388. if self.polygon_areas is not None:
  1389. polygon_box = Polygon([(left, top), (right, top), (right, bottom), (left, bottom)])
  1390. intersection_areas = [polygon_area.intersection(polygon_box).area for polygon_area in self.polygon_areas ]
  1391. if sum(intersection_areas) == 0:
  1392. continue
  1393. intersection_areas_ratio = sorted([intersection_area / polygon_box.area for intersection_area in intersection_areas])
  1394. if intersection_areas_ratio[-1] < 0.9:
  1395. continue
  1396. conf = box.conf.cpu().numpy().tolist()[0]
  1397. cls = box.cls.cpu().numpy().tolist()[0]
  1398. if cls == 4:
  1399. width = right - left
  1400. height = bottom - top
  1401. if width * height >4096:
  1402. person_objs.append([left, top, right, bottom, conf, names[cls]])
  1403. elif cls in [1,2]:
  1404. #width = right - left
  1405. #height = bottom - top
  1406. #if width * height >4096:
  1407. uniform_objs.append([left, top, right, bottom, conf, names[cls]])
  1408. elif cls != 3:
  1409. head_objs.append([left, top, right, bottom, conf, names[cls]])
  1410. person_objs = self.selectNoUniformPerson(person_objs, head_objs)
  1411. illegal_objs = self.selectNoUniformPerson(person_objs, uniform_objs)
  1412. if len(illegal_objs)>0:
  1413. for obj in illegal_objs:
  1414. annotator.box_label(obj[:4], None, color=(0, 0, 255))
  1415. self.flag = True
  1416. return self.flag
  1417. class newUniform:
  1418. def __init__(self):
  1419. self.flag = False
  1420. def selectNoUniformPerson(self, person_objs, uniform_objs):
  1421. objs = []
  1422. print(person_objs)
  1423. print(uniform_objs)
  1424. polygon_person = [Polygon(
  1425. [(left, top), (right, top), (right, bottom), (left, bottom)]) for left, top, right, bottom, _, _ in person_objs]
  1426. polygon_uniform = [Polygon(
  1427. [(left, top), (right, top), (right, bottom), (left, bottom)]) for left, top, right, bottom, _, _ in uniform_objs]
  1428. for person_obj, person in zip(person_objs, polygon_person):
  1429. with_uniform = False
  1430. for uniform in polygon_uniform:
  1431. if person.intersection(uniform).area / uniform.area > 0.3:
  1432. with_uniform = True
  1433. break
  1434. if not with_uniform:
  1435. print(f'illperson_obj {person_obj} illpolygon_uniform {polygon_uniform}')
  1436. objs.append(person_obj)
  1437. return objs
  1438. def getflag(self, det, persondet,annotator, fence=0, point=None, names=None, rname=None,num=1):
  1439. self.flag = False
  1440. results = Results(annotator.result(),path=None,names=names,boxes=det)
  1441. print(results.boxes)
  1442. person_objs = []
  1443. uniform_objs = []
  1444. print(f'persondet = {persondet}')
  1445. #belt_objs = []
  1446. if len(point)>1:
  1447. self.polygon_areas = [Polygon(strtolstl(point)[0])]
  1448. print(self.polygon_areas)
  1449. else:
  1450. self.polygon_areas = None
  1451. tmppersondet = []
  1452. if self.polygon_areas is not None:
  1453. for person in persondet:
  1454. polygon_box = Polygon([(person[0], person[1]), (person[2], person[3]), (person[4], person[5]), (person[6], person[7])])
  1455. intersection_areas = [polygon_area.intersection(polygon_box).area for polygon_area in self.polygon_areas ]
  1456. if sum(intersection_areas) == 0:
  1457. continue
  1458. intersection_areas_ratio = sorted([intersection_area / polygon_box.area for intersection_area in intersection_areas])
  1459. #print(intersection_areas_ratio)
  1460. if intersection_areas_ratio[-1] < 0.9:
  1461. continue
  1462. tmppersondet.append(person)
  1463. persondet = tmppersondet
  1464. print(f'tmppersondet = {tmppersondet}')
  1465. #persondet = tmppersondet
  1466. for result in results:
  1467. boxes = result.boxes
  1468. for box in boxes:
  1469. left, top, right, bottom = box.xyxy.cpu().numpy().tolist()[0]
  1470. conf = box.conf.cpu().numpy().tolist()[0]
  1471. cls = box.cls.cpu().numpy().tolist()[0]
  1472. #if self.polygon_areas is not None and cls == 4:
  1473. # polygon_box = Polygon([(left, top), (right, top), (right, bottom), (left, bottom)])
  1474. # intersection_areas = [polygon_area.intersection(polygon_box).area for polygon_area in self.polygon_areas ]
  1475. # if sum(intersection_areas) == 0:
  1476. # continue
  1477. # intersection_areas_ratio = sorted([intersection_area / polygon_box.area for intersection_area in intersection_areas])
  1478. # if intersection_areas_ratio[-1] < 0.9:
  1479. # continue
  1480. #conf = box.conf.cpu().numpy().tolist()[0]
  1481. #cls = box.cls.cpu().numpy().tolist()[0]
  1482. print(conf)
  1483. print(cls)
  1484. if cls == 4 and conf >=0.7:
  1485. width = right - left
  1486. height = bottom - top
  1487. print(width*height)
  1488. if width * height >10000:
  1489. for person in persondet:
  1490. #p1 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3),
  1491. #xyxy[3].cpu().item())
  1492. #p2 = (int(xyxy[0].cpu().item() + (xyxy[2].cpu().item() - xyxy[0].cpu().item()) / 3 * 2),
  1493. # xyxy[3].cpu().item())
  1494. personcenterx = int((person[0]+person[2])/2)
  1495. personcentery = int((person[1]+person[7])/2)
  1496. p1 = (personcenterx,personcentery)
  1497. print(p1)
  1498. pt = [p1]
  1499. print(f'p1 = {p1}')
  1500. print(f'person = {person}')
  1501. personinflag = mat.Path([(left, top), (right, top), (right, bottom), (left, bottom)]).contains_points(pt)
  1502. if personinflag.any():
  1503. person_objs.append([left, top, right, bottom, conf, names[cls]])
  1504. elif cls in [1,2]:
  1505. #width = right - left
  1506. #height = bottom - top
  1507. #if width * height >4096:
  1508. uniform_objs.append([left, top, right, bottom, conf, names[cls]])
  1509. illegal_objs = self.selectNoUniformPerson(person_objs, uniform_objs)
  1510. if len(illegal_objs)>0:
  1511. for obj in illegal_objs:
  1512. annotator.box_label(obj[:4], None, color=(0, 0, 255))
  1513. self.flag = True
  1514. return self.flag