Skip to content

Commit 411eb37

Browse files
authored
Add files via upload
1 parent 0882b35 commit 411eb37

File tree

1 file changed

+57
-29
lines changed

1 file changed

+57
-29
lines changed

index.html

+57-29
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
<head>
44
<meta charset="UTF-8">
55
<meta name="viewport" content="width=device-width, initial-scale=1.0">
6-
<title>YOLOv8 Object Detection</title>
6+
<title>YOLOv8 Object Detection with Logs</title>
77
<style>
88
#webcam-container {
99
display: flex;
@@ -14,28 +14,36 @@
1414
#webcam {
1515
border: 2px solid black;
1616
}
17+
#log {
18+
margin-top: 20px;
19+
padding: 10px;
20+
width: 640px;
21+
height: 150px;
22+
border: 2px solid #000;
23+
overflow-y: scroll;
24+
background-color: #f0f0f0;
25+
font-family: monospace;
26+
}
1727
</style>
1828
</head>
1929
<body>
2030
<h1>YOLOv8 Object Detection</h1>
2131
<div id="webcam-container">
2232
<video id="webcam" width="640" height="480" autoplay></video>
2333
</div>
24-
<script src="https://cdn.jsdelivr.net/npm/onnxruntime-web@latest/dist/onnxruntime-web.min.js"></script>
34+
<div id="log"></div> <!-- 로그를 표시할 영역 추가 -->
35+
<script src="ort.min.js"></script> <!-- 로컬 ort.min.js 파일을 로드 -->
2536
<script>
26-
// ONNX model path
27-
const modelPath = 'yolov8_model.onnx'; // Make sure this path is correct
28-
29-
// Global variables for sound and state
30-
let alertSound = new Audio('alert_sound.mp3'); // Replace with actual sound file path
37+
// 전역 변수: 소리, 상태
38+
let alertSound = new Audio('alert_sound.mp3'); // 알림 소리 파일 경로 수정
3139
let isPlaying = false;
3240

33-
// Initialize webcam
41+
// 웹캠 초기화
3442
const video = document.getElementById('webcam');
3543
const canvas = document.createElement('canvas');
3644
const ctx = canvas.getContext('2d');
3745

38-
// Access webcam
46+
// 웹캠 권한 요청 및 설정
3947
navigator.mediaDevices.getUserMedia({ video: true })
4048
.then((stream) => {
4149
video.srcObject = stream;
@@ -45,22 +53,30 @@ <h1>YOLOv8 Object Detection</h1>
4553
console.error('Error accessing webcam:', error);
4654
});
4755

48-
// Load ONNX model
56+
// onnxruntime-web 로딩 후 모델을 로드
4957
let session;
58+
window.onload = function () {
59+
if (typeof ort !== 'undefined') {
60+
loadModel(); // onnxruntime-web 라이브러리가 로드된 후 모델 로드
61+
} else {
62+
console.error("onnxruntime-web is not loaded properly");
63+
logMessage("onnxruntime-web is not loaded properly");
64+
}
65+
};
5066

5167
async function loadModel() {
5268
try {
53-
session = await ort.InferenceSession.create(modelPath);
69+
session = await ort.InferenceSession.create('yolov8_model.onnx'); // 모델 경로 수정 필요
5470
console.log("Model loaded successfully");
71+
logMessage("Model loaded successfully");
5572
startDetection();
5673
} catch (err) {
5774
console.error("Error loading model:", err);
75+
logMessage("Error loading model: " + err);
5876
}
5977
}
6078

61-
loadModel();
62-
63-
// Start object detection
79+
// 객체 탐지 시작
6480
async function startDetection() {
6581
canvas.width = video.width;
6682
canvas.height = video.height;
@@ -69,57 +85,60 @@ <h1>YOLOv8 Object Detection</h1>
6985
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
7086
let frame = canvas.toDataURL('image/jpeg');
7187

72-
// Convert image data to tensor
88+
// 이미지 데이터를 텐서로 변환
7389
let tensor = preprocessImage(frame);
7490

75-
// Run inference
91+
// 추론 실행
7692
session.run([tensor]).then((output) => {
77-
const boxes = output[0].data; // Adjust according to output format
78-
const confidences = output[1].data; // Adjust according to output format
93+
const boxes = output[0].data; // 박스 데이터
94+
const confidences = output[1].data; // 신뢰도 데이터
95+
const classIds = output[2].data; // 클래스 ID 데이터
7996

80-
// Check if cigarette is detected
97+
// 'cigarette'가 탐지된 경우
8198
let cigaretteDetected = false;
8299

83-
// Loop through detections and draw boxes
100+
// 탐지된 각 객체에 대해 박스를 그리기
84101
boxes.forEach((box, index) => {
85102
const confidence = confidences[index];
86-
if (confidence > 0.5) { // Adjust the confidence threshold
103+
if (confidence > 0.5) { // 신뢰도가 50% 이상인 경우
87104
const [x, y, width, height] = box;
88-
if (/* check if the class is cigarette */) {
105+
if (classIds[index] === 1) { // 클래스 ID가 1이면 'cigarette' 클래스라고 가정
89106
cigaretteDetected = true;
90107
drawBoundingBox(x, y, width, height);
91108
}
92109
}
93110
});
94111

95-
// Play alert sound if cigarette is detected
112+
// 'cigarette'가 탐지되었으면 소리 재생
96113
if (cigaretteDetected && !isPlaying) {
97114
alertSound.play();
98115
isPlaying = true;
116+
logMessage("Cigarette detected! Playing alert sound.");
99117
} else if (!cigaretteDetected && isPlaying) {
100118
alertSound.pause();
101119
isPlaying = false;
120+
logMessage("No cigarette detected. Stopping alert sound.");
102121
}
103122

104123
requestAnimationFrame(detectObjects);
105124
}).catch((error) => {
106125
console.error("Error during inference:", error);
126+
logMessage("Error during inference: " + error);
107127
});
108128
}
109129

110130
detectObjects();
111131
}
112132

113-
// Preprocess webcam frame and convert to tensor
133+
// 웹캠 이미지 전처리 및 텐서로 변환
114134
function preprocessImage(frame) {
115-
// Convert frame to tensor here (resize, normalize, etc.)
116-
// This depends on the expected input format for your model
117-
// Example: You might need to resize the frame, normalize, etc.
118-
let tensor = new ort.Tensor('float32', new Float32Array(frame), [1, 3, 640, 640]); // Adjust the shape as per model requirement
135+
// 이미지 전처리 (크기 조정, 정규화 등)
136+
// 모델에 맞는 텐서 형태로 변환
137+
let tensor = new ort.Tensor('float32', new Float32Array(frame), [1, 3, 640, 640]); // 모델의 입력 형식에 맞게 수정 필요
119138
return tensor;
120139
}
121140

122-
// Draw bounding box on canvas
141+
// 박스 그리기
123142
function drawBoundingBox(x, y, width, height) {
124143
ctx.beginPath();
125144
ctx.rect(x, y, width, height);
@@ -128,6 +147,15 @@ <h1>YOLOv8 Object Detection</h1>
128147
ctx.fillStyle = 'red';
129148
ctx.stroke();
130149
}
150+
151+
// 로그 메시지 추가
152+
function logMessage(message) {
153+
const logElement = document.getElementById('log');
154+
const newLog = document.createElement('div');
155+
newLog.textContent = message;
156+
logElement.appendChild(newLog);
157+
logElement.scrollTop = logElement.scrollHeight; // 로그 창이 항상 최신 메시지로 스크롤
158+
}
131159
</script>
132160
</body>
133161
</html>

0 commit comments

Comments
 (0)