点击上面“蓝字”关注我们!
本篇文章主要讲述如何在本地代码中调用华为云产品人脸识别服务API,实现人脸识别功能。
完整Demo参考:https://github.com/servicestage-demo/cse-java-demo-list/tree/master/demo-cse-face-recognition
一、创建工程
1、首先在本地搭建ServiceComb工程
为了能够使开发者可以快速构建ServiceComb应用程序,官方为我们提供了一套脚手架,这样能够方便学习者及应用开发者快速入门,同时极大的提高了效率。
快速开发引导页:http://start.servicecomb.io/
填写好工程group、artifact等信息(ServiceComb参数可以使用默认),就可以生成一个ServiceComb工程了,将工程下载到本地,导入到Eclipse或者IDEA等开发工具中。
2、配置microservice.yaml
servicecomb.service.registry.address:CSE(微服务引擎)服务注册发现地址
servicecomb.rest.address:本地应用访问地址
AK、SK获取请参考链接:https://support.huaweicloud.com/devg-apisign/api-sign-provide.html#p3
APPLICATION_ID: demo-face-recognition
service_description:
# name of the declaring microservice
name: demo-face-recognition
version: 0.0.1
environment: development
servicecomb:
service:
registry:
address: https://cse.xxx.myhuaweicloud.com:port
rest:
address: 0.0.0.0:8081
credentials:
accessKey: Your AK
secretKey: Your SK
project: cn-north-1
akskCustomerCipher: default
handler:
chain:
Provider:
default: tracing-provider
也可以使用本地注册中心,到官网http://servicecomb.apache.org/cn/release/下载ServiceComb Service-Center(选最新版本)
本地microservice.yaml配置参考:
APPLICATION_ID: demo-face-recognition
service_description:
name: demo-face-recognition
version: 1.0.0
service_description:
name: demo-provider
version: 1.0.0
servicecomb:
rest:
address: 0.0.0.0:9000
service:
registry:
address: http://127.0.0.1:30100
3、配置application.properties(与microservice.yaml同目录)
#图片保存路径:自定义
#获取token参数:参考Token认证鉴权指南https://support.huaweicloud.com/api-modelarts/modelarts_03_0004.html
#搜索人脸API:参考华为人脸识别服务 FRS:https://support.huaweicloud.com/face/index.html
首先是申请开通服务(须注册华为云账号,并完成实名认证),照着下面这个地址一步步操作就行,比较详细。
申请服务:https://support.huaweicloud.com/api-face/face_02_0006.html
然后要创建自己的人脸库,参考:https://support.huaweicloud.com/api-face/face_02_0031.html
人脸库扩展字段external_fields可以自定义,比如本文Demo设置了:name、gender、department等字段
#增加人脸API、#删除人脸API同上。
#图片保存路径
face_img_path=/usr/gc/img/
#获取token参数
face_token_url=https://xxx.myhuaweicloud.com/v3/auth/tokens
face_token_username=username
face_token_password=password
face_token_domain=domain
face_token_project=project
#搜索人脸API
face_api_search=https://face.xxx.myhuaweicloud.com/v1/xxx/face-sets/test/search
#增加人脸API
face_api_add=https://face.xxx.myhuaweicloud.com/v1/xxx/face-sets/test/faces
#删除人脸API
face_api_del=https://face.xxx.myhuaweicloud.com/v1/xxx/face-sets/test/faces?external_image_id=imgID
4、定义接口
定义了搜索、增加、删除3个接口,另外有个更新接口,可自行实现。
public interface FaceEndpoint {
/**
* search face
*/
String face(MultipartFile file);
/**
* add face
*/
String addface(MultipartFile file, String id);
/**
* delete face
*/
String delface(String id);
}
5、编写业务类
访问路径可以自定义,注意参数类型是file(直接上传图片进行识别)
@RestSchema(schemaId = "FaceRestEndpoint")
@RequestMapping(path = "/")
public class FaceRestEndpoint implements FaceEndpoint {
private final FileService fileService;
@Autowired
public FaceRestEndpoint(FileService fileService) {
this.fileService = fileService;
}
@PostMapping(path = "/face", produces = MediaType.TEXT_PLAIN_VALUE)
public String face(@RequestPart(name = "file") MultipartFile file) {
return fileService.face(file);
}
@PostMapping(path = "/addface", produces = MediaType.TEXT_PLAIN_VALUE)
public String addface(@RequestPart(name = "file") MultipartFile file, @RequestParam(name = "id") String id) {
return fileService.addface(file, id);
}
@DeleteMapping(path = "/delface", produces = MediaType.TEXT_PLAIN_VALUE)
public String delface(String id) {
return fileService.delface(id);
}
}
6、实现获取Token,调用人脸识别API
为避免频繁调用获取Token接口,可以在本地缓存Token,Token有效期是24小时
package org.apache.servicecomb.samples.face;
import java.io.File;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.servicecomb.provider.springmvc.reference.RestTemplateBuilder;
import org.apache.servicecomb.tracing.Span;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
@Service
public class FileServiceImpl implements FileService {
@Value("${face_img_path}")
private String faceImgPath;
@Value("${face_token_url}")
private String faceTokenUrl;
@Value("${face_token_username}")
private String faceTokenUsername;
@Value("${face_token_password}")
private String faceTokenPassword;
@Value("${face_token_domain}")
private String faceTokenDomain;
@Value("${face_token_project}")
private String faceTokenProject;
@Value("${face_api_search}")
private String faceApiSearch;
@Value("${face_api_add}")
private String faceApiAdd;
@Value("${face_api_del}")
private String faceApiDel;
private static final String TOKEN_KEY = "X-Subject-Token";
private static final String EXPIRES_KEY = "Expires-time";
private static final long availablePeriod = 20 * 3600 * 1000; // 20小时
private static Map tokenMap = new HashMap();
private static Map data = new HashMap();
private static Logger LOGGER = Logger.getLogger(FileServiceImpl.class);
private String getToken() {
LOGGER.info("start to get token");
if (!tokenMap.isEmpty()) {
long startTime = Long.valueOf(tokenMap.get(EXPIRES_KEY));
long currTime = System.currentTimeMillis();
if (currTime - startTime < availablePeriod) {
return tokenMap.get(TOKEN_KEY);
}
}
String raw = requestBody(faceTokenUsername, faceTokenPassword, faceTokenDomain, faceTokenProject);
RestTemplate restTemplate = RestTemplateBuilder.create();
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/json");
HttpEntity entity = new HttpEntity(raw, headers);
ResponseEntity r = restTemplate.postForEntity(faceTokenUrl, entity, String.class);
String token = r.getHeaders().getFirst(TOKEN_KEY);
tokenMap.put(TOKEN_KEY, token);
tokenMap.put(EXPIRES_KEY, String.valueOf(System.currentTimeMillis()));
LOGGER.info("end to get token");
return token;
}
/**
* 构造使用Token方式访问服务的请求Token对象
*
* @param username 用户名
* @param passwd 密码
* @param domainName 域名
* @param projectName 项目名称
* @return 构造访问的JSON对象
*/
private static String requestBody(String username, String passwd, String domainName, String projectName) {
JSONObject auth = new JSONObject();
JSONObject identity = new JSONObject();
JSONArray methods = new JSONArray();
methods.add("password");
identity.put("methods", methods);
JSONObject password = new JSONObject();
JSONObject user = new JSONObject();
user.put("name", username);
user.put("password", passwd);
JSONObject domain = new JSONObject();
domain.put("name", domainName);
user.put("domain", domain);
password.put("user", user);
identity.put("password", password);
JSONObject scope = new JSONObject();
JSONObject scopeProject = new JSONObject();
scopeProject.put("name", projectName);
scope.put("project", scopeProject);
auth.put("identity", identity);
auth.put("scope", scope);
JSONObject params = new JSONObject();
params.put("auth", auth);
return params.toJSONString();
}
//请求响应编码转换,防止乱码
public static RestTemplate getRestTemplate(String charset) {
RestTemplate restTemplate = new RestTemplate();
List> list = restTemplate.getMessageConverters();
for (HttpMessageConverter httpMessageConverter : list) {
if (httpMessageConverter instanceof StringHttpMessageConverter) {
((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(Charset.forName(charset));
break;
}
}
return restTemplate;
}
@Span
@Override
public String face(MultipartFile file) {
// 此处构造数据,建议使用数据库
if (data.isEmpty()) {
data.put("xiaoming", "{\"姓名\":\"小明\", \"性别\":\"男\", \"部门\":\"华为云服务\"}");
data.put("unknow", "{\"姓名\":\"未知\", \"性别\":\"未知\", \"部门\":\"未知\"}");
}
LOGGER.info("start to face recognition");
String filePath = null;
if (file != null && !file.isEmpty()) {
// 文件保存路径
filePath = faceImgPath + System.currentTimeMillis() + "-" + file.getOriginalFilename();
// 转存文件
try {
file.transferTo(new File(filePath));
} catch (Exception e) {
return e.getMessage();
}
}
if (filePath == null) {
return data.get("unknow");
}
RestTemplate restTemplate = getRestTemplate("UTF-8");
// 设置请求头
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("multipart/form-data;charset=UTF-8;");
headers.setContentType(type);
headers.set("X-Auth-Token", getToken());
// 设置请求体,注意是LinkedMultiValueMap
MultiValueMap form = new LinkedMultiValueMap();
FileSystemResource fileSystemResource = new FileSystemResource(filePath);
// 此处参数参考https://support.huaweicloud.com/api-face/face_02_0035.html
form.add("image_file", fileSystemResource);
form.add("return_fields", "[\"timestamp\",\"id\"]");
form.add("filter", "timestamp:12");
// 用HttpEntity封装整个请求报文
HttpEntity> files = new HttpEntity>(form, headers);
ResponseEntity s;
try {
s = restTemplate.postForEntity(faceApiSearch, files, String.class);
} catch (Exception e) {
return data.get("unknow");
}
LOGGER.info("end to face recognition");
// 此处进行相似度判断,实现逻辑可自行修改
String name = s.getBody().substring(s.getBody().indexOf("external_image_id") + 20);
name = name.substring(0, 3).replace("\"", "");
String similar = s.getBody().substring(s.getBody().indexOf("similarity") + 12);
similar = similar.substring(0, similar.indexOf("}"));
// 相似度大于86%,则认为人脸识别成功
if (Double.parseDouble(similar) > 0.86) {
return data.get(name);
}
return data.get("unknow");
}
@Override
public String addface(MultipartFile file, String external_image_id) {
LOGGER.info("start to addface file");
String filePath = null;
String imgName = System.currentTimeMillis() + "-" + file.getOriginalFilename();
if (file != null && !file.isEmpty()) {
// 文件保存路径
filePath = faceImgPath + imgName;
// 转存文件
try {
file.transferTo(new File(filePath));
} catch (Exception e) {
return e.getMessage();
}
}
// 文件保存失败,返回图片路径
if (filePath == null) {
return "{\"image\": \"" + (faceImgPath + imgName) + "\"}";
}
RestTemplate restTemplate = getRestTemplate("UTF-8");
// 设置请求头
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("multipart/form-data;charset=UTF-8;");
headers.setContentType(type);
headers.set("X-Auth-Token", getToken());
// 设置请求体,注意是LinkedMultiValueMap
MultiValueMap form = new LinkedMultiValueMap();
FileSystemResource fileSystemResource = new FileSystemResource(filePath);
// 此处参数参考https://support.huaweicloud.com/api-face/face_02_0035.html
form.add("image_file", fileSystemResource);
form.add("external_image_id", external_image_id);
form.add("external_fields", "{\"timestamp\" : 12,\"id\" : \"home\"}");
// 用HttpEntity封装整个请求报文
HttpEntity> files = new HttpEntity>(form, headers);
ResponseEntity s = restTemplate.postForEntity(faceApiAdd, files, String.class);
LOGGER.info("end to addface file");
return s.getBody();
}
@Override
public String delface(String id) {
RestTemplate restTemplate = getRestTemplate("UTF-8");
// 设置请求头
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8;");
headers.setContentType(type);
headers.set("X-Auth-Token", getToken());
Map paramMap = new HashMap();
paramMap.put("X-Auth-Token", getToken());
// 用HttpEntity封装整个请求报文
String URL_HTTPS = faceApiDel + id;
HttpEntity requestEntity = new HttpEntity(null, headers);
ResponseEntity s = restTemplate.exchange(URL_HTTPS, HttpMethod.DELETE, requestEntity, String.class);
LOGGER.info("end to delface file");
return s.getBody();
}
}
7、调用示例
#搜索人脸接口
请求URL:http://xxx.xxx.213.158:8081/face
请求方式:POST
参数类型:body
参数示例:form-data (key:file, value:[图片文件])
返回示例:{"姓名":"小明", "性别":"男", "部门":"华为云服务"}
#增加人脸接口
请求URL:http://xxx.xxx.213.158:8081/add
请求方式:POST
参数类型:body
参数示例:raw(json)
{
"name":"谷歌",
"gender":"女",
"department":"云服务"
}
返回示例:1
#删除人脸接口
请求URL:http://xxx.xxx.213.158:8081/delface?id=xxx
请求方式:DELETE
参数类型:query
参数示例:见url (或者key:id, value:xxx)
返回示例:{"face_number":1, "face_set_name":"test", "face_set_id":"xxx"}
8、pom.xml参考
4.0.0
org.apache.servicecomb.samples
garbage-classify
Java Chassis::Samples::Garbage-Classify
1.2.0
jar
Quick Start Demo for Using ServiceComb Java Chassis
UTF-8
UTF-8
1.8
${project.version}
1.5.14.RELEASE
org.apache.servicecomb
java-chassis-dependencies
${java-chassis.version}
pom
import
org.springframework.boot
spring-boot-dependencies
${spring-boot-1.version}
pom
import
org.hibernate.validator
hibernate-validator
javax.validation
validation-api
org.springframework.boot
spring-boot-starter
org.apache.servicecomb
spring-boot-starter-provider
org.apache.servicecomb
handler-flowcontrol-qps
org.apache.servicecomb
handler-bizkeeper
org.apache.servicecomb
handler-tracing-zipkin
com.huawei.paas.cse
cse-solution-service-engine
2.3.56
org.apache.servicecomb
tracing-zipkin
org.mybatis
mybatis
3.4.1
com.alibaba
druid
1.0.14
com.alibaba
fastjson
1.2.31
maven-dependency-plugin
copy-dependencies
prepare-package
copy-dependencies
${project.build.directory}/dtm-lib
maven-jar-plugin
${project.build.directory}
true
./dtm-lib/
org.apache.servicecomb.samples.gc.GCApplication
false
.
org.apache.maven.plugins
maven-compiler-plugin
3.1
-parameters
UTF-8
1.8
1.8
org.springframework.boot
spring-boot-maven-plugin
true
如您对开源开发,微服务专家
欢迎扫描下方二维码添加
ServiceComb小助手
咱们一起做点有意思的事情〜
您点的每个赞,我都认真当成了喜欢