3
3
< head >
4
4
< meta charset ="UTF-8 ">
5
5
< 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 >
7
7
< style >
8
8
# webcam-container {
9
9
display : flex;
14
14
# webcam {
15
15
border : 2px solid black;
16
16
}
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
+ }
17
27
</ style >
18
28
</ head >
19
29
< body >
20
30
< h1 > YOLOv8 Object Detection</ h1 >
21
31
< div id ="webcam-container ">
22
32
< video id ="webcam " width ="640 " height ="480 " autoplay > </ video >
23
33
</ 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 파일을 로드 -->
25
36
< 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' ) ; // 알림 소리 파일 경로 수정
31
39
let isPlaying = false ;
32
40
33
- // Initialize webcam
41
+ // 웹캠 초기화
34
42
const video = document . getElementById ( 'webcam' ) ;
35
43
const canvas = document . createElement ( 'canvas' ) ;
36
44
const ctx = canvas . getContext ( '2d' ) ;
37
45
38
- // Access webcam
46
+ // 웹캠 권한 요청 및 설정
39
47
navigator . mediaDevices . getUserMedia ( { video : true } )
40
48
. then ( ( stream ) => {
41
49
video . srcObject = stream ;
@@ -45,22 +53,30 @@ <h1>YOLOv8 Object Detection</h1>
45
53
console . error ( 'Error accessing webcam:' , error ) ;
46
54
} ) ;
47
55
48
- // Load ONNX model
56
+ // onnxruntime-web 로딩 후 모델을 로드
49
57
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
+ } ;
50
66
51
67
async function loadModel ( ) {
52
68
try {
53
- session = await ort . InferenceSession . create ( modelPath ) ;
69
+ session = await ort . InferenceSession . create ( 'yolov8_model.onnx' ) ; // 모델 경로 수정 필요
54
70
console . log ( "Model loaded successfully" ) ;
71
+ logMessage ( "Model loaded successfully" ) ;
55
72
startDetection ( ) ;
56
73
} catch ( err ) {
57
74
console . error ( "Error loading model:" , err ) ;
75
+ logMessage ( "Error loading model: " + err ) ;
58
76
}
59
77
}
60
78
61
- loadModel ( ) ;
62
-
63
- // Start object detection
79
+ // 객체 탐지 시작
64
80
async function startDetection ( ) {
65
81
canvas . width = video . width ;
66
82
canvas . height = video . height ;
@@ -69,57 +85,60 @@ <h1>YOLOv8 Object Detection</h1>
69
85
ctx . drawImage ( video , 0 , 0 , canvas . width , canvas . height ) ;
70
86
let frame = canvas . toDataURL ( 'image/jpeg' ) ;
71
87
72
- // Convert image data to tensor
88
+ // 이미지 데이터를 텐서로 변환
73
89
let tensor = preprocessImage ( frame ) ;
74
90
75
- // Run inference
91
+ // 추론 실행
76
92
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 데이터
79
96
80
- // Check if cigarette is detected
97
+ // ' cigarette'가 탐지된 경우
81
98
let cigaretteDetected = false ;
82
99
83
- // Loop through detections and draw boxes
100
+ // 탐지된 각 객체에 대해 박스를 그리기
84
101
boxes . forEach ( ( box , index ) => {
85
102
const confidence = confidences [ index ] ;
86
- if ( confidence > 0.5 ) { // Adjust the confidence threshold
103
+ if ( confidence > 0.5 ) { // 신뢰도가 50% 이상인 경우
87
104
const [ x , y , width , height ] = box ;
88
- if ( /* check if the class is cigarette */ ) {
105
+ if ( classIds [ index ] === 1 ) { // 클래스 ID가 1이면 ' cigarette' 클래스라고 가정
89
106
cigaretteDetected = true ;
90
107
drawBoundingBox ( x , y , width , height ) ;
91
108
}
92
109
}
93
110
} ) ;
94
111
95
- // Play alert sound if cigarette is detected
112
+ // ' cigarette'가 탐지되었으면 소리 재생
96
113
if ( cigaretteDetected && ! isPlaying ) {
97
114
alertSound . play ( ) ;
98
115
isPlaying = true ;
116
+ logMessage ( "Cigarette detected! Playing alert sound." ) ;
99
117
} else if ( ! cigaretteDetected && isPlaying ) {
100
118
alertSound . pause ( ) ;
101
119
isPlaying = false ;
120
+ logMessage ( "No cigarette detected. Stopping alert sound." ) ;
102
121
}
103
122
104
123
requestAnimationFrame ( detectObjects ) ;
105
124
} ) . catch ( ( error ) => {
106
125
console . error ( "Error during inference:" , error ) ;
126
+ logMessage ( "Error during inference: " + error ) ;
107
127
} ) ;
108
128
}
109
129
110
130
detectObjects ( ) ;
111
131
}
112
132
113
- // Preprocess webcam frame and convert to tensor
133
+ // 웹캠 이미지 전처리 및 텐서로 변환
114
134
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 ] ) ; // 모델의 입력 형식에 맞게 수정 필요
119
138
return tensor ;
120
139
}
121
140
122
- // Draw bounding box on canvas
141
+ // 박스 그리기
123
142
function drawBoundingBox ( x , y , width , height ) {
124
143
ctx . beginPath ( ) ;
125
144
ctx . rect ( x , y , width , height ) ;
@@ -128,6 +147,15 @@ <h1>YOLOv8 Object Detection</h1>
128
147
ctx . fillStyle = 'red' ;
129
148
ctx . stroke ( ) ;
130
149
}
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
+ }
131
159
</ script >
132
160
</ body >
133
161
</ html >
0 commit comments