-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
221 lines (192 loc) · 8.25 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>YOLOv8 Object Detection with Sound Alert</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f9;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
#container {
position: relative;
width: 640px;
height: 480px;
border: 2px solid #ccc;
background-color: #fff;
}
#webcam {
width: 100%;
height: 100%;
object-fit: cover;
position: absolute;
}
#canvas {
position: absolute;
top: 0;
left: 0;
z-index: 10;
pointer-events: none; /* 캔버스가 비디오 위에 있지만 클릭할 수 없도록 설정 */
}
#log {
margin-top: 20px;
padding: 10px;
width: 640px;
max-height: 200px;
overflow-y: auto;
background-color: #222;
color: #fff;
font-family: monospace;
border-radius: 5px;
border: 2px solid #333;
}
h1 {
text-align: center;
color: #333;
}
</style>
</head>
<body>
<div id="container">
<video id="webcam" autoplay></video>
<canvas id="canvas" width="640" height="480"></canvas>
</div>
<div id="log"></div> <!-- 로그를 표시할 영역 추가 -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/ort.min.js"></script>
<script>
// 전역 변수: 소리, 상태
let alertSound = new Audio('alert_sound.mp3'); // 알림 소리 파일 경로 수정
let isPlaying = false;
// 웹캠 초기화
const video = document.getElementById('webcam');
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 웹캠 권한 요청 및 설정
navigator.mediaDevices.getUserMedia({ video: true })
.then((stream) => {
video.srcObject = stream;
video.play();
})
.catch((error) => {
console.error('Error accessing webcam:', error);
});
// onnxruntime-web 로딩 후 모델을 로드
let session;
window.onload = function () {
if (typeof ort !== 'undefined') {
loadModel(); // onnxruntime-web 라이브러리가 로드된 후 모델 로드
} else {
console.error("onnxruntime-web is not loaded properly");
logMessage("onnxruntime-web is not loaded properly");
}
};
async function loadModel() {
try {
session = await ort.InferenceSession.create('yolov8_model.onnx'); // 모델 경로 수정 필요
console.log("Model loaded successfully");
logMessage("Model loaded successfully");
startDetection();
} catch (err) {
console.error("Error loading model:", err);
logMessage("Error loading model: " + err);
}
}
// 객체 탐지 시작
async function startDetection() {
function detectObjects() {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
let frame = canvas;
// 이미지 데이터를 텐서로 변환
let tensor = preprocessImage(frame);
// 모델의 입력 이름을 확인 후, feeds 객체에 적절한 값을 추가
const feeds = {};
feeds['input.1'] = tensor; // 입력 이름을 정확하게 확인하고 변경하세요
// 추론 실행
session.run(feeds).then((output) => {
// output 객체 출력 (디버깅을 위해 추가)
console.log("Model output:", output);
// output의 구조를 확인한 후 아래와 같이 수정합니다.
// output[0], output[1], output[2] 등은 실제 모델의 출력 형식에 따라 다를 수 있습니다.
const boxes = output[0] ? output[0].data : []; // 박스 데이터
const confidences = output[1] ? output[1].data : []; // 신뢰도 데이터
const classIds = output[2] ? output[2].data : []; // 클래스 ID 데이터
// 'cigarette'가 탐지된 경우
let cigaretteDetected = false;
// 탐지된 각 객체에 대해 박스를 그리기
boxes.forEach((box, index) => {
const confidence = confidences[index];
if (confidence > 0.5) { // 신뢰도가 50% 이상인 경우
const [x, y, width, height] = box;
if (classIds[index] === 1) { // 클래스 ID가 1이면 'cigarette' 클래스라고 가정
cigaretteDetected = true;
drawBoundingBox(x, y, width, height);
}
}
});
// 'cigarette'가 탐지되었으면 소리 재생
if (cigaretteDetected && !isPlaying) {
alertSound.play();
isPlaying = true;
logMessage("Cigarette detected! Playing alert sound.");
} else if (!cigaretteDetected && isPlaying) {
alertSound.pause();
isPlaying = false;
logMessage("No cigarette detected. Stopping alert sound.");
}
requestAnimationFrame(detectObjects);
}).catch((error) => {
console.error("Error during inference:", error);
logMessage("Error during inference: " + error);
});
}
detectObjects();
}
// 웹캠 이미지 전처리 및 텐서로 변환
function preprocessImage(frame) {
canvas.width = 640;
canvas.height = 640;
ctx.drawImage(frame, 0, 0, canvas.width, canvas.height);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = new Float32Array(3 * 640 * 640);
let index = 0;
// RGBA -> RGB로 변환하고 정규화
for (let i = 0; i < imageData.data.length; i += 4) {
data[index++] = imageData.data[i] / 255; // Red
data[index++] = imageData.data[i + 1] / 255; // Green
data[index++] = imageData.data[i + 2] / 255; // Blue
}
// 모델에 맞게 텐서 생성
const tensor = new ort.Tensor('float32', data, [1, 3, 640, 640]);
return tensor;
}
// 박스 그리기
function drawBoundingBox(x, y, width, height) {
ctx.beginPath();
ctx.rect(x, y, width, height);
ctx.lineWidth = 3;
ctx.strokeStyle = 'red';
ctx.fillStyle = 'red';
ctx.stroke();
// 텍스트 추가: "Cigarette" 또는 클래스명 출력
ctx.font = "20px Arial";
ctx.fillStyle = "red";
ctx.fillText("Cigarette", x, y - 10);
}
// 로그 메시지 추가
function logMessage(message) {
const logElement = document.getElementById('log');
const newLog = document.createElement('div');
newLog.textContent = message;
logElement.appendChild(newLog);
logElement.scrollTop = logElement.scrollHeight; // 로그 창이 항상 최신 메시지로 스크롤
}
</script>
</body>
</html>