-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
296 lines (248 loc) · 10.7 KB
/
index.html
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
<!--
Copyright 2022 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!--
This is a simple HTML page that fetches the image and bounding box info from the Coral Micro
Camera HTTP server and draws them on a canvas. The image and bounding box info are fetched
using fetch() and the canvas is drawn using the 2D context of the canvas.
WARNING: There is a bug in the Coral Micro Camera HTTP server that seems to corrupt the bounding
box info. I suspect this is due to the server not being able to handle multiple requests at the
same time or there is a race condition with the bounding box info being updated. If you solve this,
please let me know. You will get a metaphorical gold star.
Modified by: Shawn Hymel
Date: November 23, 2023
License: This code is licensed under the Apache License 2.0.
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Security Camera Web Server</title>
<script type="text/javascript">
// Uncomment these if you are running the Coral Micro Camera HTTP server on the Coral Dev Board
const imgUrl = "/camera_stream";
const bboxUrl = "/bboxes";
// Timeout for fetch requests (ms)
const fetchImageTimeout = 500;
const fetchBboxTimeout = 200;
// Global variables
let rawImageData = null;
// Sleeps for micro seconds.
function sleep (micro) {
return new Promise((resolve) => setTimeout(resolve, micro));
}
// Function to generate a random 8-digit hex value
function generateRandomHex() {
return Math.floor(Math.random() * 0x100000000).toString(16).substr(0, 8);
}
function drawBoundingBoxes(ctx, bboxes, imgElt, isMotionDetected) {
bboxes.forEach(bbox => {
let xmin = Math.max(bbox['xmin'] * imgElt.width, 0);
let ymin = Math.max(bbox['ymin'] * imgElt.height, 0);
let xmax = Math.min(bbox['xmax'] * imgElt.width, imgElt.width);
let ymax = Math.min(bbox['ymax'] * imgElt.height, imgElt.height);
// Determine box color based on conditions
ctx.lineWidth = 2;
ctx.font = '20px Calibri';
ctx.beginPath();
if (isMotionDetected && bbox['id'].includes("0")) {
// Green color for boxes with motion detected and ID containing "0"
ctx.strokeStyle = '#00ff00';
ctx.fillStyle = '#00ff00';
} else {
// Red color for default boxes
ctx.strokeStyle = '#ff0000';
ctx.fillStyle = '#ff0000';
}
// Draw bounding box
ctx.rect(xmin, ymin, xmax - xmin, ymax - ymin);
ctx.stroke();
ctx.fillText(bbox['id'], xmin, ymin - 5);
});
}
// Helper function to create a timeout promise
function timeout(ms, promise) {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error("Timeout after " + ms + " ms"));
}, ms);
promise.then(resolve, reject);
});
}
// Function to save the image with a custom filename
function saveImage() {
const imgElt = document.getElementById("cam_canvas");
// Get the value from the "Label" input field
const imageLabel = document.getElementById("image-label").value;
// Generate a random 8-digit hex value
const randomHex = generateRandomHex();
if (rawImageData) {
// Convert the raw image data to a Blob
const imageBlob = new Blob([rawImageData], { type: 'image/jpeg' });
// Construct the filename using the label and random hex
const filename = `${imageLabel}.${randomHex}.jpg`;
// Create a hidden anchor element and trigger the download
const a = document.createElement('a');
a.href = URL.createObjectURL(imageBlob);
a.download = filename;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
} else {
console.error('No raw image data available.');
}
}
// Main loop to fetch image and bounding boxes and draw them on the canvas
async function updateImage () {
// Add event listener to save image button
const saveImageBtn = document.getElementById("save-image-button");
saveImageBtn.addEventListener("click", saveImage);
// Create image reader and canvas context
const imgReader = new FileReader();
const imgElt = document.getElementById("cam_canvas");
const ctx = imgElt.getContext('2d');
// Do this forever
let img = new Image();
let startTime = Date.now();
while (1) {
// Reset variables
startTime = Date.now();
let bboxInfo = null;
let imageBlob = null;
// Fetch image
try {
// Fetch image data with timeout
const imageResponse = await timeout(fetchImageTimeout, fetch(imgUrl));
imageBlob = await timeout(fetchImageTimeout, imageResponse.blob());
// Store raw image data
rawImageData = await imageBlob.arrayBuffer();
} catch (error) {
console.error("Error in fetching image: ", error);
continue;
}
// Fetch bbox info
try {
// Fetch bbox info with timeout
const bboxResponse = await timeout(fetchBboxTimeout, fetch(bboxUrl));
const bboxStrPromise = bboxResponse.text();
const bboxStr = await timeout(fetchBboxTimeout, bboxStrPromise);
// Parse bbox info
bboxInfo = JSON.parse(bboxStr);
// Uncomment to view bbox info
console.log("bboxStr: ", bboxStr);
console.log("bboxInfo: ", bboxInfo);
} catch (error) {
console.error("Error in fetching bbox info: ", error);
continue;
}
// Go to top of loop if we don't have image or bbox info
if (!imageBlob || !bboxInfo) {
console.error("Error fetching data");
continue;
}
// Log bounding boxes
console.log(bboxInfo);
// Draw image and bounding boxes
imgReader.readAsDataURL(imageBlob);
imgReader.onloadend = () => {
img.onload = () => {
// Get width and height of image
const width = img.width;
const height = img.height;
// get zoom factor
const zoom = document.getElementById("image-zoom").value;
// Clear canvas and set new size
ctx.clearRect(0, 0, imgElt.width, imgElt.height);
imgElt.width = width * zoom;
imgElt.height = height * zoom;
// Draw image
ctx.drawImage(img, 0, 0, imgElt.width, imgElt.height);
// Draw bounding boxes
if (bboxInfo.bboxes) {
drawBoundingBoxes(ctx, bboxInfo.bboxes, imgElt, bboxInfo.isMotionDetected);
}
}
img.src = imgReader.result;
}
// Calculate dynamic FPS
const fps = 1000 / bboxInfo.dtime
const dynamicFpsLabel = document.getElementById("dynamic-fps-label");
dynamicFpsLabel.textContent = `FPS: ${fps.toFixed(2)}`;
// Log time to fetch and draw image
console.log("Total update time: ", Date.now() - startTime);
// Wait before fetching new image
await sleep(10);
}
}
</script>
<style>
body {
margin: 0;
padding: 0;
color: #9f4dfd;
background: #000000;
}
#main-container {
border: 1px solid #53bfc1;
background: #000000;
}
#coral-cam-title-container {
white-space: nowrap;
height: 45px;
background: #2600ff;
border-bottom: 1px solid #000000;
}
.coral-cam-title {
line-height: 45px;
font-size: 30px;
display: inline-block;
color: #000000;
padding-left: 10px;
}
#settings-save-menu {
height: 50px;
background: #2f2e9e;
border-top: 1px solid #000000;
}
#dynamic-fps-label {
height: 30px;
color: #bbff00;
background: #2f2e9e;
padding-left: 10px;
line-height: 30px;
}
.input-label {
padding-left: 10px;
}
</style>
</head>
<body id="body" onload="updateImage()">
<div id="main-container">
<div id="coral-cam-title-container">
<label class="coral-cam-title">Security Camera Web Interface</label>
</div>
<div id="settings-save-menu">
<div style="margin-top: 10px"></div>
<label for="image-zoom" class="input-label">Zoom:</label>
<input id="image-zoom" type="number" style="width: 40px;" required value=2.5>
<label for="image-label" class="input-label">Label:</label>
<input id="image-label" type="text" required value="image">
<button id="save-image-button">Save Image</button>
</div>
<div id="dynamic-fps-label">
FPS: N/A
</div>
<canvas id="cam_canvas"></canvas>
</div>
</body>
</html>