-
Notifications
You must be signed in to change notification settings - Fork 0
/
test-tfjs-usbcam-inner-polygon.html
357 lines (301 loc) · 11.6 KB
/
test-tfjs-usbcam-inner-polygon.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
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
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TensorFlow.js リアルタイム物体検出</title>
<style>
canvas {
border: 1px solid black;
}
#alert {
position: absolute;
top: 10px;
left: 10px;
padding: 10px;
background-color: rgba(255, 0, 0, 0.8);
color: white;
font-size: 20px;
display: none;
}
</style>
</head>
<body>
<div id="alert">Entered the area</div>
<video id="video" width="640" height="480" autoplay></video>
<canvas id="output-canvas" width="640" height="480"></canvas>
<button id="reset-button">Reset Polygons</button>
<button id="save-json-button">Save Polygons to JSON</button>
<button id="load-json-button">Load Polygons from JSON</button>
<div id="inference-time" style="margin-top: 10px;"></div>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<script>
const VIDEO_INPUT_WIDTH = 640;
const VIDEO_INPUT_HEIGHT = 480;
const MODEL_INPUT_WIDTH = 640;
const MODEL_INPUT_HEIGHT = 480;
const classColors = [
"#FF0000", "#00FF00", "#0000FF", "#FFFF00", "#FF00FF", "#00FFFF", "#FFA500", "#800080",
"#008080", "#A52A2A", "#808000", "#000080", "#FFC0CB", "#800000", "#808080", "#C0C0C0",
"#FFD700", "#ADFF2F", "#87CEEB", "#DC143C", "#FF4500", "#2E8B57", "#4682B4", "#6A5ACD",
"#708090"
];
let model;
// カメラ映像の取得
async function setupCamera() {
const video = document.getElementById('video');
const stream = await navigator.mediaDevices.getUserMedia({
video: { width: VIDEO_INPUT_WIDTH, height: VIDEO_INPUT_HEIGHT }
});
video.srcObject = stream;
return new Promise((resolve) => {
video.onloadedmetadata = () => resolve(video);
});
}
// モデルのロード
async function loadModel() {
try {
model = await tf.loadGraphModel('tfjs_model_480x640/model.json');
return model;
} catch (err) {
console.error('モデルのロードに失敗しました:', err);
alert('モデルのロードに失敗しました。');
}
}
// 前処理
function preprocessImage(videoElement) {
let tensor = tf.browser.fromPixels(videoElement).expandDims(0).toFloat();
tensor = tf.reverse(tensor, axis=[-1]);
return tensor;
}
// 推論の実行
async function runInference(inputTensor) {
const startTime = Date.now();
const output = await model.executeAsync(inputTensor);
const endTime = Date.now();
const inferenceTime = endTime - startTime;
document.getElementById('inference-time').textContent = `推論時間: ${inferenceTime} ミリ秒`;
return output;
}
const threshold = 0.35;
let currentPolygon = [];
let polygons = [];
let isDrawing = false;
const canvas = document.getElementById('output-canvas');
const ctx = canvas.getContext('2d');
// マウスクリックで頂点を追加
canvas.addEventListener('click', function (e) {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
currentPolygon.push([x, y]);
isDrawing = true;
drawCurrentPolygon(video);
});
// ダブルクリックで多角形を確定
canvas.addEventListener('dblclick', function (e) {
if (currentPolygon.length >= 3) {
polygons.push([...currentPolygon]); // 多角形を確定
currentPolygon = []; // 新しい多角形に向けてリセット
isDrawing = false;
drawPolygons(ctx, polygons); // 確定した多角形を描画
}
});
// リセットボタンで多角形をリセット
document.getElementById('reset-button').addEventListener('click', function () {
polygons = [];
currentPolygon = [];
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
// 現在の多角形の頂点を描画する関数
function drawCurrentPolygon(videoElement) {
if (currentPolygon.length === 0) return;
// 背景のカメラ映像を描画
ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height);
// 確定した多角形も再描画
drawPolygons(ctx, polygons);
ctx.beginPath();
ctx.moveTo(currentPolygon[0][0], currentPolygon[0][1]);
for (let i = 1; i < currentPolygon.length; i++) {
ctx.lineTo(currentPolygon[i][0], currentPolygon[i][1]);
}
ctx.strokeStyle = 'blue';
ctx.setLineDash([5, 5]); // 点線を設定
ctx.stroke();
ctx.setLineDash([]); // 点線を解除
}
// 確定した多角形を描画する関数
function drawPolygons(ctx, polygons) {
polygons.forEach(polygon => {
ctx.beginPath();
ctx.moveTo(polygon[0][0], polygon[0][1]);
for (let i = 1; i < polygon.length; i++) {
ctx.lineTo(polygon[i][0], polygon[i][1]);
}
ctx.closePath();
ctx.strokeStyle = 'red'; // 確定した多角形は赤で描画
ctx.stroke();
});
}
// JSONに保存するボタン
document.getElementById('save-json-button').addEventListener('click', function () {
const dataStr = JSON.stringify(polygons);
const blob = new Blob([dataStr], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'polygons.json';
a.click();
URL.revokeObjectURL(url);
});
// JSONから読み込むボタン
document.getElementById('load-json-button').addEventListener('click', function () {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'application/json';
input.addEventListener('change', function (e) {
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = function (event) {
polygons = JSON.parse(event.target.result);
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPolygons(ctx, polygons);
};
reader.readAsText(file);
});
input.click();
});
let frameCounters = {}; // classId 21 の物体が領域に入ったか追跡するオブジェクト
function renderBoundingBoxes(output, videoElement) {
const width = videoElement.videoWidth;
const height = videoElement.videoHeight;
canvas.width = width;
canvas.height = height;
// Webカメラの映像を描画
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height);
// 元のconsole.warn()を保存
const originalWarn = console.warn;
// 特定のワーニングメッセージを抑制
console.warn = (message) => {
if (!message.includes("This model execution did not contain any nodes with control flow")) {
originalWarn(message);
}
};
// 確定した多角形を描画
drawPolygons(ctx, polygons);
// 現在描画中の多角形を描画
if (isDrawing) {
drawCurrentPolygon(videoElement);
}
// 推論
const boxesData = output.arraySync();
// レンダリング除外クラスID
const excludedIds = [1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 22, 23];
for (let i = 0; i < boxesData.length; i++) {
const [batchno, classId, score, x1, y1, x2, y2] = boxesData[i];
// 除外されたクラスIDは処理しない
if (excludedIds.includes(classId)) {
continue;
}
if (score > threshold) {
const scaleX = canvas.width / MODEL_INPUT_WIDTH;
const scaleY = canvas.height / MODEL_INPUT_HEIGHT;
const bx1 = x1 * scaleX;
const by1 = y1 * scaleY;
const bx2 = x2 * scaleX;
const by2 = y2 * scaleY;
// バウンディングボックスを描画
ctx.strokeStyle = classColors[classId % classColors.length];
ctx.lineWidth = 2;
ctx.strokeRect(bx1, by1, bx2 - bx1, by2 - by1);
ctx.font = '16px Arial';
ctx.fillStyle = classColors[classId % classColors.length];
ctx.fillText(`Class: ${classId} Score: ${score.toFixed(2)}`, bx1, by1 - 5);
// classId 21 の物体に対して領域内侵入を判定
if (classId === 21 && score > threshold) {
const box = [bx1, by1, bx2, by2];
for (let j = 0; j < polygons.length; j++) {
if (!frameCounters[i]) {
frameCounters[i] = {}; // 物体ごとのカウンタを初期化
}
if (!frameCounters[i][j]) {
frameCounters[i][j] = 0; // 領域ごとのカウンタを初期化
}
if (isBoxInPolygon(box, polygons[j])) {
frameCounters[i][j] += 1; // 領域ごとのカウンタを更新
if (frameCounters[i][j] >= 5) {
showAlert(); // 物体が 5 フレーム以上領域内にいる場合、警告を表示
}
} else {
frameCounters[i][j] = 0; // 領域に侵入していない場合はリセット
}
}
}
}
}
// 古い物体のデータをクリーンアップ
cleanupFrameCounters(output);
}
// バウンディングボックスと多角形の重なり判定 (Ray-Casting アルゴリズム)
function isBoxInPolygon(box, polygon) {
const [bx1, by1, bx2, by2] = box;
const boxPoints = [
[bx1, by1], [bx2, by1], [bx2, by2], [bx1, by2]
];
return boxPoints.some(point => pointInPolygon(point, polygon));
}
// 多角形内の点を判定する関数 (Ray-Casting アルゴリズム)
function pointInPolygon(point, vs) {
const x = point[0], y = point[1];
let inside = false;
for (let i = 0, j = vs.length - 1; i < vs.length; j = i++) {
const xi = vs[i][0], yi = vs[i][1];
const xj = vs[j][0], yj = vs[j][1];
const intersect = ((yi > y) !== (yj > y)) &&
(x < (xj - xi) * (y - yi) / (yj - yi) + xi);
if (intersect) inside = !inside;
}
return inside;
}
// 「Entered the area」を表示
function showAlert() {
const alertBox = document.getElementById('alert');
alertBox.style.display = 'block';
setTimeout(() => {
alertBox.style.display = 'none';
}, 3000); // 3秒後に非表示
}
// 古い物体のデータをクリーンアップ
function cleanupFrameCounters(output) {
const boxesData = output.arraySync();
const detectedIds = boxesData.map((_, i) => i); // 現在フレームで検出された物体のインデックスリスト
// 検出されていない物体のカウンタを削除
for (let id in frameCounters) {
if (!detectedIds.includes(parseInt(id))) {
delete frameCounters[id];
}
}
}
// フレーム処理
async function detectFrame(videoElement) {
tf.engine().startScope();
const inputTensor = preprocessImage(videoElement);
const output = await runInference(inputTensor);
renderBoundingBoxes(output, videoElement);
requestAnimationFrame(() => detectFrame(videoElement));
inputTensor.dispose();
output.dispose();
tf.engine().endScope();
}
// 初期化
async function init() {
await setupCamera();
await loadModel();
const video = document.getElementById('video');
detectFrame(video);
}
window.onload = init;
</script>
</body>
</html>