-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathface1.js
330 lines (244 loc) · 10.2 KB
/
face1.js
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
const video1 = document.getElementsByClassName('input_video1')[0];
const out1 = document.getElementsByClassName('output1')[0];
const canvasCtx1 = out1.getContext('2d');
const captureBtn = document.getElementById('captureBtn');
const capturedImageContainer = document.getElementById('capturedImageContainer');
const shoted = document.getElementById('shoted');
const sizechange = document.getElementById('size-change');
var now_filename = 'photo';
var shot_high = 30
const shoted_bar = document.getElementsByClassName('shoted-bar');
const shot_bar = document.getElementsByClassName('shot-bar');
let boxCoordinates = null;
let faceDetected = false;
function changeSize() {
if (sizechange.innerHTML === '5:6') {
sizechange.innerHTML = '4:5';
} else{
sizechange.innerHTML = '5:6';
}
}
function onResultsFace(results) {
document.body.classList.add('loaded');
canvasCtx1.clearRect(0, 0, out1.width, out1.height);
canvasCtx1.drawImage(results.image, 0, 0, out1.width, out1.height); // 先绘制图像
if (results.detections.length > 0) {
faceDetected = true;
const leftEdge = results.detections[0].landmarks[4]; // 左臉邊緣
const rightEdge = results.detections[0].landmarks[5]; // 右臉邊緣
const leftEdgeX = leftEdge.x * out1.width;
const leftEdgeY = leftEdge.y * out1.height;
const rightEdgeX = rightEdge.x * out1.width;
const rightEdgeY = rightEdge.y * out1.height;
const centerX = (leftEdgeX + rightEdgeX) / 2;
const centerY = (leftEdgeY + rightEdgeY) / 2 - shot_high;
let faceWidth = Math.sqrt(Math.pow(rightEdgeX - leftEdgeX, 2) + Math.pow(rightEdgeY - leftEdgeY, 2));
let boxHeight = 0;
let boxWidth = 0;
if (sizechange.innerHTML === '5:6') {
boxWidth = Math.ceil(faceWidth * 1.65);
if (boxWidth % 5 !== 0) {
boxWidth += 5 - (boxWidth % 5);
}
boxHeight = Math.round(boxWidth * 1.2);
}else {
boxWidth = Math.ceil(faceWidth * 1.65);
if (boxWidth % 4 !== 0) {
boxWidth += 4 - (boxWidth % 4);
}
boxHeight = Math.round(boxWidth * 1.25);
}
const startX = centerX - (boxWidth / 2);
const startY = centerY - (boxHeight / 2);
boxCoordinates = { startX, startY, boxWidth, boxHeight };
const isOutOfBounds = startX < 0 || startY < 0 || startX + boxWidth > out1.width || startY + boxHeight > out1.height;
if (isOutOfBounds) {
canvasCtx1.strokeStyle = 'orange';
captureBtn.disabled = true
} else {
canvasCtx1.strokeStyle = 'white';
captureBtn.disabled = false;
}
canvasCtx1.lineWidth = 4;
canvasCtx1.strokeRect(startX-3, startY-3, boxWidth+6, boxHeight+6);
} else {
captureBtn.disabled = false;
faceDetected = false;
const boxWidth = 200 * 1.6;
const boxHeight = 0;
if (sizechange.innerHTML === '5:6') {
if (boxWidth % 5 !== 0) {
boxWidth += 5 - (boxWidth % 5);
}
boxHeight = Math.round(boxWidth * 1.2);
}else {
if (boxWidth % 4 !== 0) {
boxWidth += 4 - (boxWidth % 4);
}
boxHeight = Math.round(boxWidth * 1.25);
}
const centerX = out1.width / 2;
const centerY = out1.height / 2;
const startX = centerX - (boxWidth / 2);
const startY = centerY - (boxHeight / 2);
boxCoordinates = { startX, startY, boxWidth, boxHeight };
canvasCtx1.strokeStyle = 'red';
canvasCtx1.lineWidth = 4;
canvasCtx1.strokeRect(startX-3, startY-3, boxWidth+6, boxHeight+6);
canvasCtx1.font = '24px Arial';
canvasCtx1.fillStyle = 'red';
canvasCtx1.fontWeight = 'bold';
canvasCtx1.fillText('無法偵測人臉-可自行對準', startX + 10, startY + boxHeight+6 +30);
}
}
captureBtn.addEventListener('click', () => {
if (boxCoordinates) {
const { startX, startY, boxWidth, boxHeight } = boxCoordinates;
const tempCanvas = document.createElement('canvas');
const tempCtx = tempCanvas.getContext('2d');
tempCanvas.width = boxWidth;
tempCanvas.height = boxHeight;
// 裁切图片内容,不包含框框
tempCtx.drawImage(out1, startX, startY, boxWidth, boxHeight, 0, 0, boxWidth, boxHeight);
const dataURL = tempCanvas.toDataURL('image/png');
capturedImageContainer.innerHTML = '';
const capturedImage = document.createElement('img');
capturedImage.src = dataURL;
capturedImageContainer.appendChild(capturedImage);
shoted.style.display = 'block';
out1.style.display = 'none';
shot_bar[0].style.display = 'none';
shoted_bar[0].style.display = 'block';
} else {
console.log('No face detected and no manual frame to capture.');
}
saved = false;
console.log('Saved status:---------------------------------', saved);
});
function reShot() {
shoted.style.display = 'none';
out1.style.display = 'block';
shot_bar[0].style.display = 'block';
shoted_bar[0].style.display = 'none';
}
reshot.addEventListener('click', () => {
reShot();
});
sizechange.addEventListener('click', () => {
changeSize();
console.log('Change size to ', sizechange.innerHTML);
});
// 保存學生照片後的處理
savephoto.addEventListener('click', () => {
const img = capturedImageContainer.querySelector('img');
if (img) {
now_filename = document.getElementById('student-information').innerHTML;
const a = document.createElement('a');
a.href = img.src;
a.download = now_filename + "--" + nowID.toString() +'.png';
document.body.appendChild(a); // 必須將 <a> 元素附加到文檔中,才能觸發點擊事件
a.click();
document.body.removeChild(a); // 點擊後移除 <a> 元素
// 保存學生信息到 cookies,保存30天
setCookie(nowID, "saved", 30);
saved = true;
console.log('Saved status:---------------------------------');
console.log(nowID);
// 在學生列表中顯示 "(已拍攝)"
var studentButton = document.getElementById(nowID);
if (studentButton && !studentButton.innerHTML.includes('(已拍攝)')) {
studentButton.innerHTML += " (已拍攝)";
}
} else {
console.log('No image found to download.');
}
});
const checkboxes = document.querySelectorAll('fieldset input[type="checkbox"]');
checkboxes.forEach(checkbox => {
checkbox.addEventListener('change', handleChange);
});
function handleChange(event) {
const { id, checked } = event.target;
console.log(`Checkbox with id: ${id} changed to ${checked ? 'checked' : 'unchecked'}`);
const checkboxes = document.querySelectorAll('fieldset input[type="checkbox"]');
const checkedIds = Array.from(checkboxes) // Convert NodeList to Array to use filter and map
.filter(checkbox => checkbox.checked) // Keep only checked checkboxes
.map(checkbox => checkbox.id); // Extract the id of each checked checkbox
console.log('Checked checkboxes:', checkedIds);
chchange = ['班級', '學號', '座號', '學生姓名', '證照號碼',];
enname = ['class', 'sid', 'sitnu', 'name', 'id',];
addch = ['班', '', '號', '', ''];
now_filename = '';
for (let i = 0; i < checkedIds.length; i++) {
for (let j = 0; j < enname.length-1; j++) {
if (checkedIds[i] === enname[j]) {
now_filename += Json[chchange[j]] + addch[j] + '--';
}
}
}
now_filename = now_filename.slice(0, -1); // Remove the last hyphen
if (document.getElementById('student-information').innerHTML != '尚未選擇學生') {
document.getElementById('student-information').innerHTML = now_filename;
}
}
const faceDetection = new FaceDetection({ locateFile: (file) => {
return `https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/${file}`;
}});
faceDetection.onResults(onResultsFace);
// 獲取當前頁面的 URL
const url = new URL(window.location.href);
// 使用 URLSearchParams 來讀取查詢參數
const params = new URLSearchParams(url.search);
const id = params.get('id'); // 從 URL 參數中獲取 id
// 輸出 id 的值
console.log(id);
const videoElement = document.getElementById('video1'); // 假設你有這個 HTML 元素
navigator.mediaDevices.enumerateDevices()
.then(devices => {
const videoDevices = devices.filter(device => device.kind === 'videoinput');
console.log(videoDevices);
if (videoDevices.length === 0) {
console.error('找不到攝像頭');
return;
}
const selectedCameraId = videoDevices[id].deviceId; // 選擇指定的攝像頭
console.log(selectedCameraId);
// 根據選定的攝像頭 ID 獲取視頻流
navigator.mediaDevices.getUserMedia({
video: {
deviceId: selectedCameraId, // 使用指定的攝像頭
width: 480, // 設置視頻的寬度
height: 480 // 設置視頻的高度
}
})
.then(stream => {
// 將攝像頭的視頻流設置為 video 元素的來源
videoElement.srcObject = stream;
videoElement.play();
// 定義每幀進行檢測的函數
const detectFace = async () => {
// 使用 faceDetection 處理 video 元素的畫面
await faceDetection.send({ image: videoElement });
requestAnimationFrame(detectFace); // 在下一幀時繼續檢測
};
// 當視頻準備好時,開始進行檢測
videoElement.onloadedmetadata = () => {
console.log('視頻已準備好,開始進行人臉檢測');
detectFace(); // 開始檢測循環
};
})
.catch(error => {
console.error('無法獲取攝像頭視頻流:', error);
});
})
.catch(error => {
console.error('無法獲取設備:', error);
});
const slider = document.getElementById('vertical-slider');
// 每當拉桿的值改變時執行動作
slider.addEventListener('input', (event) => {
console.log(`滑動條的值為: ${event.target.value}`);
shot_high = event.target.value;
});
window.addEventListener('resize', adjustCanvasSize);
adjustCanvasSize();