# -*- coding: utf-8 -*-
"""
Created on Fri Nov 8 17:06:40 2019
@author: user
"""
import cv2
import os
import time
import argparse
import socket
import json
import requests
import sys
import glob
from datetime import datetime, timedelta
from utils import *
sys.path.append("/app/workdir/")
cameraLine_url = "http://10.20.2.20:32239/cameraLine/query"
from workdir.trace_back import *
from workdir.trace import *
tracker = Sort()
class memory():
cross_line_memory = {}
class box_target():
BT={}
Complete_trace={}
Un_Complete_trace={}
def isRayIntersectsSegment(poi,s_poi,e_poi): #[x,y]
#输入:判断点,边起点,边终点,
if s_poi[1]==e_poi[1]: #排除与射线平行、重合,线段首尾端点重合的情况
return False
if s_poi[1]>poi[1] and e_poi[1]>poi[1]: #线段在射线上边
return False
if s_poi[1]<poi[1] and e_poi[1]<poi[1]: #线段在射线下边
return False
if s_poi[1]==poi[1] and e_poi[1]>poi[1]: #交点为下端点,对应spoint
return False
if e_poi[1]==poi[1] and s_poi[1]>poi[1]: #交点为下端点,对应epoint
return False
if s_poi[0]<poi[0] and e_poi[1]<poi[1]: #线段在射线左边
return False
xseg=e_poi[0]-(e_poi[0]-s_poi[0])*(e_poi[1]-poi[1])/(e_poi[1]-s_poi[1]) #求交
if xseg<poi[0]: #交点在射线起点的左侧
return False
return True #排除上述情况之后
def isPoiWithinPoly(poi,poly):
#输入:点,多边形二维数组
sinsc=0 #交点个数
#循环每条边的曲线->each polygon 是二维数组[[x1,y1],…[xn,yn]]
for i in range(len(poly)-1): #[0,len-1]
s_poi=poly[i]
e_poi=poly[i+1]
if isRayIntersectsSegment(poi,s_poi,e_poi):
sinsc+=1 #有交点就加1
if sinsc%2==1:
return True
else:
return False
#判断越线
def intersect(A,B,C,D):
return ccw(A,C,D) != ccw(B,C,D) and ccw(A,B,C) != ccw(A,B,D)
def ccw(A,B,C):
return (C[1]-A[1]) * (B[0]-A[0]) > (B[1]-A[1]) * (C[0]-A[0])
def trace_sort(result,frame,frame_num,start_time,line):
rect_1 = (line[u'leftUpX'], line[u'leftUpY'])
rect_2 = (line[u'rightUpX'], line[u'rightUpY'])
rect_3 = (line[u'rightDownX'], line[u'rightDownY'])
rect_4 = (line[u'leftDownX'], line[u'leftDownY'])
straight_line = [(line[u'stop0X'], line[u'stop0Y']), (line[u'stop1X'], line[u'stop1Y'])]
line_left = [rect_1, rect_4]
line_top = [rect_1, rect_2]
line_right = [rect_2, rect_3]
line_bottom = [rect_3, rect_4]
poly = [rect_1, rect_4, rect_3, rect_2]
poly1 = [straight_line[0], rect_1, rect_2, straight_line[1]]
box_target.Complete_trace={}
box_target.Un_Complete_trace={}
car_cross_count=[]
classIDs = []
confidences = []
boxes = []
for jiance in result:
for output in jiance:
classID=output[0]
confidence=output[1]
if (classID=="b'person'") or (classID=="b'car'") or (classID=="b'bicycle'") or (classID=="b'truck'") or (classID=="b'motorbike'") and confidence > 0.5:
box=np.array(output[2])
(centerX, centerY, width, height) = box.astype("int")
x = int(centerX - (width / 2))
y = int(centerY - (height / 2))
boxes.append([x, y, int(width), int(height)])
confidences.append(float(confidence))
classIDs.append(classID)
idxs = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.3)
category_dets=[]
dets=[]
if len(idxs) > 0:
# loop over the indexes we are keeping
for i in idxs.flatten():
(x, y) = (boxes[i][0], boxes[i][1])
(w, h) = (boxes[i][2], boxes[i][3])
dets.append([x, y, x+w, y+h, confidences[i]])
category_dets.append([x, y, x+w, y+h, confidences[i],classIDs[i]])
np.set_printoptions(formatter={'float': lambda x: "{0:0.3f}".format(x)})
dets = np.asarray(dets)
target_tracks=tracker.update(dets)
boxes = []
indexIDs = []
previous =memory.cross_line_memory.copy()
memory.cross_line_memory = {}
for track in target_tracks:
boxes.append([track[0], track[1], track[2], track[3]])
indexIDs.append(int(track[4]))
memory.cross_line_memory[indexIDs[-1]] = boxes[-1]
if len(boxes) > 0:
i = int(0)
for box in boxes:
# # extract the bounding box coordinates
(x, y) = (int(box[0]), int(box[1]))
(w, h) = (int(box[2]), int(box[3]))
if indexIDs[i] in previous:
previous_box = previous[indexIDs[i]]
(x2, y2) = (int(previous_box[0]), int(previous_box[1]))
(w2, h2) = (int(previous_box[2]), int(previous_box[3]))
P0 = (int(x + (w-x)/2), int(y + (h-y)/2))
if isPoiWithinPoly(P0,poly):
if indexIDs[i] in trace_target:
pass
else:
trace_target.append(indexIDs[i])
box_target.BT[indexIDs[i]]=Obj_trace()
box_target.BT[indexIDs[i]].startTime=start_time
else:
pass
for key in list(box_target.BT.keys()):
if key in list(previous.keys()):
box_target.BT[key].get_traceId(key)
S=previous[key]
if S[0] < 0:
S[0]=0
box_target.BT[key].box=S
box_target.BT[key].get_flagForTrace()
Local=box_target.BT[key].box
width=(Local[2]-Local[0])/2
high=(Local[3]-Local[1])/2
local_center=(int(Local[0]+(Local[2]-Local[0])/2),int(Local[1]+(Local[3]-Local[1])/2))
box_target.BT[key].get_trace(local_center)
pts=box_target.BT[key].trace
logger.info(str(pts))
if box_target.BT[key].category:
pass
else:
try:
for det in category_dets:
stype = [float(S[0]),float(S[1]),float(S[2]),float(S[3])]
dettype=[float(det[0]),float(det[1]),float(det[2]),float(det[3])]
if iou(stype,dettype[0:4])>0.5:
box_target.BT[key].category=det[5]
category=box_target.BT[key].category
logger.info(str(category))
except:
pass
if len(pts)>2:
p0=pts[-1]
p1=pts[-2]
statues=box_target.BT[key].get_judgment_wrongDirection(rect_1,rect_4)
box_target.BT[key].wrongDirection=statues
cc=box_target.BT[key]
box_target.Complete_trace[key]=cc.ppr()
i += 1
# cv2.imwrite("/home/trace/frame-{}.jpg".format(frame_num),frame)
return(box_target.Complete_trace)
incidentId_dict = {}
# cls_to_incidentType = {pedestrian}
#根据划线接口去查询 if 有 调用 if 没有 默认
# rect_1=(600,520)
# rect_2=(1200,520)
# rect_3=(1530,1010)
# rect_4=(400,1010)
# straight_line=[(700,400),(1200,400)]
trace_target=[]
incident=[]
np.random.seed(42)
COLORS = np.random.randint(0, 255, size=(200, 3),dtype="uint8")
equipmentIdLineDict={}
def run(data):
start_time = time.time()
if 'taskId' in data:
cameraId_returned = data['equipmentId']
taskId_returned = data['taskId']
serviceIds