uni代码
<template>
<view>
<view class="upload">
<button @click="chooseImage">选择图片</button>
<button @click="recognizeFace">识别人脸</button>
</view>
<image class="image" v-if="imageUrl" :src="imageUrl" mode="aspectFit"></image>
<view v-if="faceDetected" class="result">检测到人脸!</view>
<view v-else class="result">未检测到人脸</view>
</view>
</template>
<script>
export default {
data() {
return {
imageUrl: '',
faceDetected: false
};
},
methods: {
chooseImage() {
uni.chooseImage({
count: 1,
success: (res) => {
this.imageUrl = res.tempFilePaths[0];
}
});
},
recognizeFace() {
uni.uploadFile({
url: 'http://your-backend-url/recognize-face',
filePath: this.imageUrl,
name: 'file',
success: (res) => {
const data = JSON.parse(res.data);
this.faceDetected = data.faceDetected;
},
fail: (error) => {
console.error('人脸识别失败:', error);
}
});
}
}
};
</script>
<style>
.upload {
display: flex;
justify-content: space-around;
margin-top: 20px;
}
.image {
width: 300px;
height: 300px;
margin-top: 20px;
}
.result {
text-align: center;
margin-top: 20px;
font-size: 20px;
}
</style>
java代码
import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.objdetect.CascadeClassifier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@SpringBootApplication
@RestController
public class FaceRecognitionApplication {
static {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
}
public static void main(String[] args) {
SpringApplication.run(FaceRecognitionApplication.class, args);
}
@PostMapping(value = "/recognize-face", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<Boolean> recognizeFace(@RequestParam("file") MultipartFile file) {
try {
// 保存上传的文件
File uploadedFile = new File(file.getOriginalFilename());
file.transferTo(uploadedFile);
// 加载级联分类器
CascadeClassifier faceDetector = new CascadeClassifier("haarcascade_frontalface_alt.xml");
// 加载图像并进行人脸识别
Mat image = Imgcodecs.imread(uploadedFile.getAbsolutePath());
MatOfRect detectedFaces = new MatOfRect();
faceDetector.detectMultiScale(image, detectedFaces);
// 检测是否有人脸
boolean faceDetected = detectedFaces.toArray().length > 0;
return ResponseEntity.ok(faceDetected);
} catch (IOException e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
}
}