File size: 23,608 Bytes
8711bb8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Multiple Object Tracking\n",
    "- Andre Hu\n",
    "- Professor Pantelis\n",
    "- Introduction to Artificial Intelligence\n",
    "- 4/16/2023"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "mkdir: files: File exists\n",
      "--2023-04-17 14:41:33--  https://raw.githubusercontent.com/sseshadr/auvsi-cv-all/master/objectTracking/examples/ball.mp4\n",
      "Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.111.133, 185.199.108.133, 185.199.109.133, ...\n",
      "Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.111.133|:443... connected.\n",
      "HTTP request sent, awaiting response... 200 OK\n",
      "Length: 1368142 (1.3M) [application/octet-stream]\n",
      "Saving to: ‘files/videos/ball.mp4’\n",
      "\n",
      "ball.mp4            100%[===================>]   1.30M  --.-KB/s    in 0.09s   \n",
      "\n",
      "2023-04-17 14:41:34 (14.3 MB/s) - ‘files/videos/ball.mp4’ saved [1368142/1368142]\n",
      "\n",
      "--2023-04-17 14:41:34--  https://github.com/sseshadr/auvsi-cv-all/raw/master/objectTracking/examples/multiObject.avi\n",
      "Resolving github.com (github.com)... 140.82.112.4\n",
      "Connecting to github.com (github.com)|140.82.112.4|:443... connected.\n",
      "HTTP request sent, awaiting response... 302 Found\n",
      "Location: https://raw.githubusercontent.com/sseshadr/auvsi-cv-all/master/objectTracking/examples/multiObject.avi [following]\n",
      "--2023-04-17 14:41:34--  https://raw.githubusercontent.com/sseshadr/auvsi-cv-all/master/objectTracking/examples/multiObject.avi\n",
      "Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.111.133, 185.199.108.133, 185.199.109.133, ...\n",
      "Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.111.133|:443... connected.\n",
      "HTTP request sent, awaiting response... 200 OK\n",
      "Length: 1769608 (1.7M) [video/msvideo]\n",
      "Saving to: ‘files/videos/multiObject.avi’\n",
      "\n",
      "multiObject.avi     100%[===================>]   1.69M  5.22MB/s    in 0.3s    \n",
      "\n",
      "2023-04-17 14:41:35 (5.22 MB/s) - ‘files/videos/multiObject.avi’ saved [1769608/1769608]\n",
      "\n",
      "Requirement already satisfied: numpy in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (1.24.2)\n",
      "Requirement already satisfied: filterpy in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (1.4.5)\n",
      "Requirement already satisfied: numpy in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from filterpy) (1.24.2)\n",
      "Requirement already satisfied: scipy in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from filterpy) (1.10.1)\n",
      "Requirement already satisfied: matplotlib in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from filterpy) (3.7.1)\n",
      "Requirement already satisfied: contourpy>=1.0.1 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from matplotlib->filterpy) (1.0.7)\n",
      "Requirement already satisfied: cycler>=0.10 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from matplotlib->filterpy) (0.11.0)\n",
      "Requirement already satisfied: fonttools>=4.22.0 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from matplotlib->filterpy) (4.39.3)\n",
      "Requirement already satisfied: kiwisolver>=1.0.1 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from matplotlib->filterpy) (1.4.4)\n",
      "Requirement already satisfied: packaging>=20.0 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from matplotlib->filterpy) (23.1)\n",
      "Requirement already satisfied: pillow>=6.2.0 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from matplotlib->filterpy) (9.5.0)\n",
      "Requirement already satisfied: pyparsing>=2.3.1 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from matplotlib->filterpy) (3.0.9)\n",
      "Requirement already satisfied: python-dateutil>=2.7 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from matplotlib->filterpy) (2.8.2)\n",
      "Requirement already satisfied: importlib-resources>=3.2.0 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from matplotlib->filterpy) (5.12.0)\n",
      "Requirement already satisfied: zipp>=3.1.0 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from importlib-resources>=3.2.0->matplotlib->filterpy) (3.15.0)\n",
      "Requirement already satisfied: six>=1.5 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from python-dateutil>=2.7->matplotlib->filterpy) (1.16.0)\n",
      "Requirement already satisfied: opencv-python in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (4.7.0.72)\n",
      "Requirement already satisfied: numpy>=1.21.0 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from opencv-python) (1.24.2)\n",
      "Requirement already satisfied: gitpython>=3.1.30 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from -r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 5)) (3.1.31)\n",
      "Requirement already satisfied: matplotlib>=3.3 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from -r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 6)) (3.7.1)\n",
      "Requirement already satisfied: numpy>=1.18.5 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from -r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 7)) (1.24.2)\n",
      "Requirement already satisfied: opencv-python>=4.1.1 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from -r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 8)) (4.7.0.72)\n",
      "Requirement already satisfied: Pillow>=7.1.2 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from -r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 9)) (9.5.0)\n",
      "Requirement already satisfied: psutil in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from -r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 10)) (5.9.4)\n",
      "Requirement already satisfied: PyYAML>=5.3.1 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from -r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 11)) (6.0)\n",
      "Requirement already satisfied: requests>=2.23.0 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from -r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 12)) (2.28.2)\n",
      "Requirement already satisfied: scipy>=1.4.1 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from -r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 13)) (1.10.1)\n",
      "Requirement already satisfied: thop>=0.1.1 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from -r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 14)) (0.1.1.post2209072238)\n",
      "Requirement already satisfied: torch>=1.7.0 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from -r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 15)) (2.0.0)\n",
      "Requirement already satisfied: torchvision>=0.8.1 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from -r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 16)) (0.15.1)\n",
      "Requirement already satisfied: tqdm>=4.64.0 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from -r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 17)) (4.65.0)\n",
      "Requirement already satisfied: pandas>=1.1.4 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from -r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 26)) (2.0.0)\n",
      "Requirement already satisfied: seaborn>=0.11.0 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from -r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 27)) (0.12.2)\n",
      "Requirement already satisfied: setuptools>=65.5.1 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from -r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 41)) (67.6.1)\n",
      "Requirement already satisfied: gitdb<5,>=4.0.1 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from gitpython>=3.1.30->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 5)) (4.0.10)\n",
      "Requirement already satisfied: contourpy>=1.0.1 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from matplotlib>=3.3->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 6)) (1.0.7)\n",
      "Requirement already satisfied: cycler>=0.10 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from matplotlib>=3.3->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 6)) (0.11.0)\n",
      "Requirement already satisfied: fonttools>=4.22.0 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from matplotlib>=3.3->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 6)) (4.39.3)\n",
      "Requirement already satisfied: kiwisolver>=1.0.1 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from matplotlib>=3.3->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 6)) (1.4.4)\n",
      "Requirement already satisfied: packaging>=20.0 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from matplotlib>=3.3->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 6)) (23.1)\n",
      "Requirement already satisfied: pyparsing>=2.3.1 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from matplotlib>=3.3->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 6)) (3.0.9)\n",
      "Requirement already satisfied: python-dateutil>=2.7 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from matplotlib>=3.3->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 6)) (2.8.2)\n",
      "Requirement already satisfied: importlib-resources>=3.2.0 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from matplotlib>=3.3->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 6)) (5.12.0)\n",
      "Requirement already satisfied: charset-normalizer<4,>=2 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from requests>=2.23.0->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 12)) (3.1.0)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from requests>=2.23.0->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 12)) (3.4)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from requests>=2.23.0->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 12)) (1.26.15)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from requests>=2.23.0->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 12)) (2022.12.7)\n",
      "Requirement already satisfied: filelock in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from torch>=1.7.0->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 15)) (3.11.0)\n",
      "Requirement already satisfied: typing-extensions in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from torch>=1.7.0->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 15)) (4.5.0)\n",
      "Requirement already satisfied: sympy in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from torch>=1.7.0->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 15)) (1.11.1)\n",
      "Requirement already satisfied: networkx in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from torch>=1.7.0->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 15)) (3.1)\n",
      "Requirement already satisfied: jinja2 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from torch>=1.7.0->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 15)) (3.1.2)\n",
      "Requirement already satisfied: pytz>=2020.1 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from pandas>=1.1.4->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 26)) (2023.3)\n",
      "Requirement already satisfied: tzdata>=2022.1 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from pandas>=1.1.4->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 26)) (2023.3)\n",
      "Requirement already satisfied: smmap<6,>=3.0.1 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from gitdb<5,>=4.0.1->gitpython>=3.1.30->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 5)) (5.0.0)\n",
      "Requirement already satisfied: zipp>=3.1.0 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from importlib-resources>=3.2.0->matplotlib>=3.3->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 6)) (3.15.0)\n",
      "Requirement already satisfied: six>=1.5 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from python-dateutil>=2.7->matplotlib>=3.3->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 6)) (1.16.0)\n",
      "Requirement already satisfied: MarkupSafe>=2.0 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from jinja2->torch>=1.7.0->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 15)) (2.1.2)\n",
      "Requirement already satisfied: mpmath>=0.19 in /Users/bhu/.virtualenvs/mot/lib/python3.9/site-packages (from sympy->torch>=1.7.0->-r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt (line 15)) (1.3.0)\n"
     ]
    }
   ],
   "source": [
    "!mkdir files\n",
    "!rm -rf files/*\n",
    "\n",
    "# Downloading assignment videos\n",
    "!wget -P files/videos https://raw.githubusercontent.com/sseshadr/auvsi-cv-all/master/objectTracking/examples/ball.mp4\n",
    "!wget -P files/videos https://github.com/sseshadr/auvsi-cv-all/raw/master/objectTracking/examples/multiObject.avi\n",
    "\n",
    "!pip install numpy\n",
    "!pip install filterpy\n",
    "!pip install opencv-python\n",
    "!pip install -r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2\n",
    "import torch\n",
    "import numpy as np\n",
    "from scipy.linalg import block_diag\n",
    "from filterpy.kalman import KalmanFilter\n",
    "from filterpy.common import Q_discrete_white_noise"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Task 2: Object Detector"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using cache found in /Users/bhu/.cache/torch/hub/ultralytics_yolov5_master\n",
      "YOLOv5 🚀 2023-4-15 Python-3.9.6 torch-2.0.0 CPU\n",
      "\n",
      "Fusing layers... \n",
      "YOLOv5s summary: 213 layers, 7225885 parameters, 0 gradients\n",
      "Adding AutoShape... \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[31m\u001b[1mrequirements:\u001b[0m /Users/bhu/.cache/torch/hub/requirements.txt not found, check failed.\n"
     ]
    }
   ],
   "source": [
    "# Loading YOLOv5 model\n",
    "model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)\n",
    "\n",
    "# Filter out classes, only want to detect sports ball\n",
    "model.classes = [32]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Ball:\n",
    "    def __init__(self, x, y):\n",
    "        self.actual_points = []\n",
    "        self.predicted_points = []\n",
    "        self.filter = self.createFilter(x, y)\n",
    "\n",
    "    def createFilter(self, x, y):\n",
    "        \"\"\"\n",
    "        Based off of https://share.cocalc.com/share/7557a5ac1c870f1ec8f01271959b16b49df9d087/Kalman-and-Bayesian-Filters-in-Python/08-Designing-Kalman-Filters.ipynb?viewer=share\n",
    "        \"\"\"\n",
    "        kf = KalmanFilter(dim_x=4, dim_z=2)\n",
    "        dt = 1.0\n",
    "\n",
    "        kf.F = np.array([[1, dt, 0, 0],\n",
    "                         [0, 1, 0, 0],\n",
    "                         [0, 0, 1, dt],\n",
    "                         [0, 0, 0, 1]])\n",
    "\n",
    "        q = Q_discrete_white_noise(dim=2, dt=dt, var=0.05)\n",
    "        kf.Q = block_diag(q, q)\n",
    "\n",
    "        kf.H = np.array([[1, 0, 0, 0],\n",
    "                         [0, 0, 1, 0]])\n",
    "\n",
    "        kf.R = np.array([[0.5, 0],\n",
    "                         [0, 0.5]])\n",
    "\n",
    "        kf.P = np.eye(4)\n",
    "        kf.x = np.array([[x, 0, y, 0]]).T\n",
    "\n",
    "        return kf\n",
    "\n",
    "    def calculateDistance(self, x, y):\n",
    "        \"\"\"\n",
    "        Calculates the distance between the current position and the predicted position\n",
    "        \"\"\"\n",
    "        return np.sqrt((x - self.filter.x[0]) ** 2 + (y - self.filter.x[2]) ** 2)\n",
    "\n",
    "    def predict(self):\n",
    "        \"\"\"\n",
    "        Have the filter predict the next point\n",
    "        \"\"\"\n",
    "        self.filter.predict()\n",
    "        predicted_x = int(self.filter.x[0])\n",
    "        predicted_y = int(self.filter.x[2])\n",
    "\n",
    "        self.predicted_points.append((predicted_x, predicted_y))\n",
    "\n",
    "    def update(self, x, y):\n",
    "        \"\"\"\n",
    "        Update the filter with a new point\n",
    "        \"\"\"\n",
    "        self.actual_points.append((x, y))\n",
    "        self.filter.update(np.array([[x, y]]))\n",
    "\n",
    "    def addPointsToFrame(self, frame):\n",
    "        \"\"\"\n",
    "        Draw the actual and predicted points on the frame\n",
    "        \"\"\"\n",
    "        for i in self.actual_points:\n",
    "            cv2.circle(frame, i, 1, (0, 255, 0), 2)  # green\n",
    "        for i in self.predicted_points:\n",
    "            cv2.circle(frame, i, 1, (204, 51, 255), 2)  # purple\n",
    "\n",
    "\n",
    "def getNumberOfBalls(filename):\n",
    "    \"\"\"\n",
    "    Retrieves the maximum number of balls in a video\n",
    "    \"\"\"\n",
    "    cap = cv2.VideoCapture(filename)\n",
    "    t = []\n",
    "    while (cap.isOpened()):\n",
    "        ret, frame = cap.read()\n",
    "        if ret == True:\n",
    "            results = model(frame)\n",
    "            t.append(len(results.xyxy[0]))\n",
    "        else:\n",
    "            break\n",
    "    return max(t)\n",
    "\n",
    "\n",
    "def calculateCenter(box):\n",
    "    \"\"\"\n",
    "    Calculates the center of a bounding box\n",
    "    \"\"\"\n",
    "    return int((box[0] + box[2]) / 2), int((box[1] + box[3]) / 2)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "def ballDetector(filename, outfile):\n",
    "    # Keep track of all the balls in the video\n",
    "    balls = [] \n",
    "\n",
    "    # Get the number of balls in the video\n",
    "    numberOfBalls = getNumberOfBalls(filename)\n",
    "\n",
    "    cap = cv2.VideoCapture(filename)\n",
    "    \n",
    "    # Defining the codec to export the frames\n",
    "    fourcc = cv2.VideoWriter_fourcc(*'mp4v')\n",
    "    fps = int(cap.get(cv2.CAP_PROP_FPS))\n",
    "    frame_size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))\n",
    "    out = cv2.VideoWriter(outfile, fourcc, fps, frame_size)\n",
    "\n",
    "    # The code below renders the video and applies the YOLOv5 model\n",
    "    # loaded previously to detect objects in the video\n",
    "    while(cap.isOpened()):\n",
    "        # Read a frame from the video\n",
    "        ret, frame = cap.read()\n",
    "\n",
    "        if ret == True:\n",
    "            # Apply the YOLOv5 model to the frame\n",
    "            results = model(frame)\n",
    "            frame = results.render()[0]\n",
    "\n",
    "            # Find first frame where all the balls are detected\n",
    "            if len(balls) == 0 and len(results.xyxy[0]) == numberOfBalls:\n",
    "                for detection in results.xyxy[0]:\n",
    "                    cx, cy = calculateCenter(detection)\n",
    "                    balls.append(Ball(cx, cy))\n",
    "\n",
    "            if len(balls) == numberOfBalls:\n",
    "\n",
    "                # Update the filters for the balls\n",
    "                for detection in results.xyxy[0]:\n",
    "                    cx, cy = calculateCenter(detection)\n",
    "                    \n",
    "                    distances = [b.calculateDistance(cx, cy) for b in balls]\n",
    "                    indexOfMin = distances.index(min(distances))\n",
    "\n",
    "                    ball = balls[indexOfMin]\n",
    "                    ball.update(cx, cy)\n",
    "\n",
    "            for b in balls:\n",
    "                b.predict()\n",
    "                b.addPointsToFrame(frame)\n",
    "                    \n",
    "            # Render the results\n",
    "            cv2.imshow('Object Detection', frame)\n",
    "            out.write(frame)\n",
    "            \n",
    "            # Used for exiting the video\n",
    "            if cv2.waitKey(1) & 0xFF == ord('q'):\n",
    "                break\n",
    "        else:\n",
    "            break\n",
    "\n",
    "    # Release the video and close all windows\n",
    "    cap.release()\n",
    "    out.release()\n",
    "    cv2.destroyAllWindows()\n",
    "    cv2.waitKey(1)\n",
    "    \n",
    "\n",
    "# Open the videos\n",
    "ballDetector(\"files/videos/ball.mp4\", \"ball_detection.mp4\")\n",
    "ballDetector(\"files/videos/multiObject.avi\", \"multiObject_detection.mp4\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "mot",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.6"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}