# Vue+Axios 實現圖片上傳識別人臉技術詳解
## 一、前言:人臉識別技術背景
人臉識別作為計算機視覺領域的重要應用,已廣泛應用于安防、金融、社交等領域。在Web開發中,結合Vue框架和Axios網絡庫,我們可以輕松實現圖片上傳+人臉識別的完整流程。本文將詳細介紹從圖片上傳到人臉識別的全鏈路實現方案。
## 二、技術棧準備
### 2.1 基礎環境配置
```bash
# 創建Vue項目
vue create face-recognition-demo
# 安裝必要依賴
npm install axios vue-axios face-api.js
<template>
<div class="upload-container">
<input
type="file"
accept="image/*"
@change="handleFileChange"
/>
<button @click="uploadImage">上傳識別</button>
<canvas ref="canvas" v-show="showResult"/>
</div>
</template>
// http.js
import axios from 'axios'
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API,
timeout: 10000
})
// 請求攔截器
service.interceptors.request.use(config => {
config.headers['Content-Type'] = 'multipart/form-data'
return config
})
export default service
export default {
data() {
return {
file: null,
showResult: false
}
},
methods: {
handleFileChange(e) {
this.file = e.target.files[0]
},
async uploadImage() {
if (!this.file) return
const formData = new FormData()
formData.append('image', this.file)
try {
const res = await this.$http.post('/api/face-detection', formData)
this.drawDetectionResult(res.data)
} catch (err) {
console.error('識別失敗:', err)
}
},
drawDetectionResult(faces) {
const canvas = this.$refs.canvas
const ctx = canvas.getContext('2d')
// 繪制識別結果
faces.forEach(face => {
const { x, y, width, height } = face.box
ctx.strokeStyle = '#FF0000'
ctx.lineWidth = 2
ctx.strokeRect(x, y, width, height)
})
this.showResult = true
}
}
}
import * as faceapi from 'face-api.js'
async loadModels() {
await faceapi.nets.tinyFaceDetector.loadFromUri('/models')
await faceapi.nets.faceLandmark68Net.loadFromUri('/models')
}
async detectFaces(imageFile) {
const image = await faceapi.bufferToImage(imageFile)
const detections = await faceapi.detectAllFaces(
image,
new faceapi.TinyFaceDetectorOptions()
)
return detections
}
# app.py (Flask示例)
import cv2
import numpy as np
from flask import Flask, request, jsonify
app = Flask(__name__)
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
@app.route('/api/face-detection', methods=['POST'])
def detect_faces():
file = request.files['image']
img = cv2.imdecode(np.frombuffer(file.read(), np.uint8), cv2.IMREAD_COLOR)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
result = [{
'box': {
'x': int(x),
'y': int(y),
'width': int(w),
'height': int(h)
},
'confidence': 1.0
} for (x,y,w,h) in faces]
return jsonify(result)
// 圖片壓縮處理
function compressImage(file, maxWidth = 800) {
return new Promise((resolve) => {
const reader = new FileReader()
reader.onload = function(e) {
const img = new Image()
img.onload = function() {
const canvas = document.createElement('canvas')
const ratio = maxWidth / img.width
canvas.width = maxWidth
canvas.height = img.height * ratio
const ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
canvas.toBlob(resolve, 'image/jpeg', 0.8)
}
img.src = e.target.result
}
reader.readAsDataURL(file)
})
}
face-recognition/
├── public/
│ └── models/ # face-api.js模型文件
├── src/
│ ├── api/ # 接口封裝
│ ├── components/ # 組件
│ ├── utils/ # 工具函數
│ └── views/ # 頁面
├── server/ # 后端代碼
│ └── app.js # Express服務
└── vue.config.js # 配置
const detections = await faceapi
.detectAllFaces(image)
.withFaceLandmarks()
.withFaceDescriptors()
// vue.config.js
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:5000',
changeOrigin: true
}
}
}
}
async loadModels() {
try {
await Promise.all([
faceapi.nets.tinyFaceDetector.loadFromUri('/models'),
faceapi.nets.faceLandmark68Net.loadFromUri('/models')
])
} catch (err) {
console.error('模型加載失敗:', err)
// 備用CDN加載方案
await faceapi.nets.tinyFaceDetector.loadFromUri(
'https://cdn.jsdelivr.net/npm/face-api.js@0.22.2/weights'
)
}
}
本文詳細介紹了基于Vue+Axios的圖片上傳與人臉識別實現方案,涵蓋: - 前端文件上傳處理 - 兩種識別方案對比 - 性能優化技巧 - 安全防護措施
未來可擴展方向: 1. 結合WebAssembly提升性能 2. 實現實時視頻流檢測 3. 集成多模態生物識別
附錄: - face-api.js官方文檔 - OpenCV人臉檢測教程 - 示例項目GitHub地址 “`
(注:實際字數約2500字,可根據需要擴展具體實現細節或補充示意圖)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。