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 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>人脸识别</title> <script src="https://cdn.jsdelivr.net/npm/face-api.js@0.22.2/dist/face-api.min.js"></script> </head> <body> <div class="content" id="app"> <input type="file" id="image-input"> <canvas id="canvas"></canvas> </div> <script> const imageInput = document.getElementById('image-input'); Promise.all([ faceapi.nets.ssdMobilenetv1.load('/models'), faceapi.nets.faceLandmark68Net.load('/models'), faceapi.nets.faceRecognitionNet.load('/models'), ]).then(start); function start() { imageInput.addEventListener('change', async () => { const imageFile = imageInput.files[0]; const imageSrc = URL.createObjectURL(imageFile); const image = await faceapi.fetchImage(imageSrc); const detectionOptions = new faceapi.SsdMobilenetv1Options({ minConfidence: 0.25, // 以控制需要检测到人脸的最小置信度分数。 minFaceSize: 100, // 参数以检测较小的人脸 maxFaceSize: 300, // 参数以检测较大的人脸 }); const detections = await faceapi.detectAllFaces(image, detectionOptions); const canvas = document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height; document.body.appendChild(canvas); const context = canvas.getContext('2d'); context.drawImage(image, 0, 0); detections.forEach((detection) => { const { x, y, width, height } = detection.box; const centerX = x + width / 2; const centerY = y + height / 2; const radius = Math.max(width, height) * 0.5; const gradient = context.createRadialGradient(centerX, centerY, radius / 3, centerX, centerY, radius); gradient.addColorStop(0, 'rgb(255,255,255)'); gradient.addColorStop(1, 'rgba(255, 255, 255, 0.8)'); context.beginPath(); // 绘制椭圆 context.ellipse(centerX, centerY, radius, (radius+4), 0, 0, 2 * Math.PI); context.fillStyle = gradient; context.fill(); }); const newImageSrc = canvas.toDataURL(); const newImage = document.createElement('img'); newImage.src = newImageSrc; document.body.appendChild(newImage); }); } </script> </body> </html> |