renwu.py 85 KB

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