Apache Servicecomb结合人脸识别API实现人脸识别

点击上面“蓝字”关注我们!

本篇文章主要讲述如何在本地代码中调用华为云产品人脸识别服务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<String, String> tokenMap = new HashMap<String, String>();
  private static Map<String, String> data = new HashMap<String, String>();




  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<String> entity = new HttpEntity<String>(raw, headers);
    ResponseEntity<String> 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<HttpMessageConverter<?>> 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<String, Object> form = new LinkedMultiValueMap<String, Object>();
    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<MultiValueMap<String, Object>> files = new HttpEntity<MultiValueMap<String, Object>>(form, headers);
    ResponseEntity<String> 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<String, Object> form = new LinkedMultiValueMap<String, Object>();
    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<MultiValueMap<String, Object>> files = new HttpEntity<MultiValueMap<String, Object>>(form, headers);
    ResponseEntity<String> 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<String, String> paramMap = new HashMap<String, String>();
    paramMap.put("X-Auth-Token", getToken());




    // 用HttpEntity封装整个请求报文
    String URL_HTTPS = faceApiDel + id;
    HttpEntity<String> requestEntity = new HttpEntity<String>(null, headers);
    ResponseEntity<String> 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参考

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.apache.servicecomb.samples</groupId>
  <artifactId>garbage-classify</artifactId>
  <name>Java Chassis::Samples::Garbage-Classify</name>
  <version>1.2.0</version>
  <packaging>jar</packaging>




  <description>Quick Start Demo for Using ServiceComb Java Chassis</description>




  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <java-chassis.version>${project.version}</java-chassis.version>
    <spring-boot-1.version>1.5.14.RELEASE</spring-boot-1.version>
  </properties>




  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.apache.servicecomb</groupId>
        <artifactId>java-chassis-dependencies</artifactId>
        <version>${java-chassis.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>${spring-boot-1.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>




  <dependencies>
    <dependency>
      <groupId>org.hibernate.validator</groupId>
      <artifactId>hibernate-validator</artifactId>
    </dependency>
    <dependency>
      <groupId>javax.validation</groupId>
      <artifactId>validation-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
    </dependency>




    <dependency>
      <groupId>org.apache.servicecomb</groupId>
      <artifactId>spring-boot-starter-provider</artifactId>
    </dependency>




    <dependency>
      <groupId>org.apache.servicecomb</groupId>
      <artifactId>handler-flowcontrol-qps</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.servicecomb</groupId>
      <artifactId>handler-bizkeeper</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.servicecomb</groupId>
      <artifactId>handler-tracing-zipkin</artifactId>
    </dependency>
    <dependency>
      <groupId>com.huawei.paas.cse</groupId>
      <artifactId>cse-solution-service-engine</artifactId>
      <version>2.3.56</version>
    </dependency>
    <dependency>
      <groupId>org.apache.servicecomb</groupId>
      <artifactId>tracing-zipkin</artifactId>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.1</version>
    </dependency>




    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.0.14</version>
    </dependency>




    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.31</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-dependency-plugin</artifactId>
        <executions>
          <execution>
            <id>copy-dependencies</id>
            <phase>prepare-package</phase>
            <goals>
              <goal>copy-dependencies</goal>
            </goals>
            <configuration>
              <outputDirectory>
                ${project.build.directory}/dtm-lib
              </outputDirectory>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-jar-plugin</artifactId>
        <configuration>
          <outputDirectory>${project.build.directory}</outputDirectory>
          <archive>
            <manifest>
              <addClasspath>true</addClasspath>
              <classpathPrefix>./dtm-lib/</classpathPrefix>
              <mainClass>org.apache.servicecomb.samples.gc.GCApplication</mainClass>
              <useUniqueVersions>false</useUniqueVersions>
            </manifest>
            <manifestEntries>
              <Class-Path>.</Class-Path>
            </manifestEntries>
          </archive>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <compilerArgument>-parameters</compilerArgument>
          <encoding>UTF-8</encoding>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
          <fork>true</fork>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

如您对开源开发,微服务专家

欢迎扫描下方二维码添加

ServiceComb小助手

咱们一起做点有意思的事情〜

您点的每个赞,我都认真当成了喜欢

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值