File size: 5,242 Bytes
d81e049
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ce2ad6
d81e049
 
c1e37c4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import gradio as gr

from ultralytics import YOLO
import torch, torchvision
import cv2
import os
import pickle

import numpy as np

class jeysonHandler:
    def __init__(self, delta_threshold, pos_threshold, last_pos_num=5, wait_time=60, num_types=4):
        self.ids={}
        self.missing_ids=set()
        self.translator={}
        self.dt = delta_threshold
        self.pt = pos_threshold
        self.lpn = last_pos_num
        self.wt = wait_time
        self.num_types = num_types
    def reg_id(self, id):
        self.ids[id] ={
        'type_statistics':[0]*self.num_types,
        'last_positions':[],
        'last_delta':np.array((0,0)),
        'events':{
            '0':[],
            '1':[]
        }
        }
    def reg_data(self, timestamp, id, type, pos):
        pos = np.array(pos)
        self.missing_ids.discard(id)
        self.ids[id]['type_statistics'][type]+=1
        self.ids[id]['last_positions'].append((timestamp, pos))
        if len(self.ids[id]['last_positions']) > self.lpn:
            self.ids[id]['last_positions'] = self.ids[id]['last_positions'][-self.lpn:]
        deltaS = self.ids[id]['last_positions'][-1][1]-self.ids[id]['last_positions'][0][1]
        deltaT = self.ids[id]['last_positions'][-1][0]-self.ids[id]['last_positions'][0][0]
        delta = deltaS/deltaT
        self.ids[id]['last_delta'] = delta
        event = {
        'start_time': timestamp,
        'end_time': timestamp
        }
        if len(self.ids[id]['events']['0']) ==0:
            self.ids[id]['events']['0'].append(event)
        elif timestamp - self.ids[id]['events']['0'][-1]['end_time'] > self.wt:
            if self.ids[id]['events']['0'][-1]['end_time'] - self.ids[id]['events']['0'][-1]['start_time'] < self.wt/3:
                self.ids[id]['events']['0'].pop()
            self.ids[id]['events']['0'].append(event)
        else:
            self.ids[id]['events']['0'][-1]['end_time'] = timestamp
        
        if np.sqrt(np.sum(np.power(delta, 2)))> self.dt:
            if len(self.ids[id]['events']['1']) ==0:
                self.ids[id]['events']['1'].append(event)
            elif timestamp - self.ids[id]['events']['1'][-1]['end_time'] > self.wt:
                if self.ids[id]['events']['1'][-1]['end_time'] - self.ids[id]['events']['1'][-1]['start_time'] < self.wt/3:
                    self.ids[id]['events']['1'].pop()
                self.ids[id]['events']['1'].append(event)
            else:
                self.ids[id]['events']['1'][-1]['end_time'] = timestamp
    
    def add_data(self, timestamp, data):
        lost = set(self.ids.keys())
        lost = lost.difference(self.missing_ids)
        newids = []
        for id, type, pos in data:
            if id in self.translator:
                id = self.translator[id]
            if id in self.ids:
                lost.discard(id)
                self.reg_data(timestamp, id, type, pos)
            else:
                newids.append((id, type, pos))
        for id, type, pos in newids:
            distances = []
            for lostid in lost:
                last_time = self.ids[lostid]['last_positions'][-1][0]
                if timestamp - last_time > self.wt:
                    self.missing_ids.add(lostid)
                    continue
                last_pos = self.ids[lostid]['last_positions'][-1][1]
                last_delta = self.ids[lostid]['last_delta']
                predicted_pos = last_pos + last_delta*(timestamp - last_time)
                distance = np.sqrt(np.sum(np.power(pos-predicted_pos,2)))
                distances.append((distance, lostid))
            if len(distances)>0:
                mindist = min(distances)
                if mindist[0]<self.pt:
                    self.translator[id] = lostid
                    self.reg_data(timestamp, lostid, type, pos)
                else:
                    self.reg_id(id)
                    self.reg_data(timestamp, id, type, pos)
            else:
                self.reg_id(id)
                self.reg_data(timestamp, id, type, pos)
    def get_json(self, type_names):
          ajson = {}
          for id in self.ids:
              idinfo = {
              'type': type_names[np.argmax(np.array(self.ids[id]['type_statistics']))],
              'events': self.ids[id]['events']
              }
              ajson[str(id)] = idinfo
          return ajson
i = 0
def timestamp():
    global i
    i += 1
    return (i - 1) / 5

def video_model(video):
    model = YOLO('last.pt')
    predict = model.track(source=video, show=False, conf=.1)
    boxes = list(map(lambda x: (timestamp(), x.boxes.id.int().numpy(), x.boxes.cls.int().numpy(), (x.boxes.xywh[..., :2] + x.boxes.xywh[..., 2:] / 2).numpy()), predict))
    handler = jeysonHandler(3, 10)
    for x in boxes:
        timestamps = x[0]
        data = []
        for i in range(len(x[1])):
            data.append((x[1][i], x[2][i], x[3][i]))
        handler.add_data(timestamps, data)
    return handler.get_json(['crane', 'excavator', 'tractor', 'truck'])

demo = gr.Interface(video_model, 
                    gr.Video(), 
                    gr.JSON(), 
                cache_examples=True).queue()

if __name__ == "__main__":
    demo.launch(share=False)