• 从零玩转人脸识别


    前言

    在线demo

    (前往享受人脸识别)

    文章作者个人博客

    (前往作者博客)

    本期教程人脸识别第三方平台为虹软科技,基于Java开发,本文章讲解的是人脸识别RGB活体追踪技术,免费的功能很多可以自行搭配,希望在你看完本章课程有所收获。

    人脸追踪示例

    ArcFace 离线SDK,包含人脸检测、性别检测、年龄检测、人脸识别、图像质量检测、RGB活体检测、IR活体检测等能力,初次使用时需联网激活,激活后即可在本地无网络环境下工作,可根据具体的业务需求结合人脸识别SDK灵活地进行应用层开发。

    SDK功能模块图.png

    功能介绍

    1. 人脸检测

    对传入的图像数据进行人脸检测,返回人脸的边框以及朝向信息,可用于后续的人脸识别、特征提取、活体检测等操作;

    • 支持IMAGE模式和VIDEO模式人脸检测。
    • 支持单人脸、多人脸检测,最多支持检测人脸数为50。

    2.人脸追踪

    对来自于视频流中的图像数据,进行人脸检测,并对检测到的人脸进行持续跟踪。(我们是实时的所以就只能使用第三方操作,先不使用这个)

    3.人脸特征提取

    提取人脸特征信息,用于人脸的特征比对。

    4.人脸属性检测

    人脸属性,支持检测年龄、性别以及3D角度。

    人脸3D角度:俯仰角(pitch), 横滚角(roll), 偏航角(yaw)。

    3D角度.png

    5.活体检测

    离线活体检测,静默式识别,在人脸识别过程中判断操作用户是否为真人,有效防御照片、视频、纸张等不同类型的作弊攻击,提高业务安全性,让人脸识别更安全、更快捷,体验更佳。支持单目RGB活体检测、双目(IR/RGB)活体检测,可满足各类人脸识别终端产品活体检测应用。

    开造

    访问地址: https://ai.arcsoft.com.cn/technology/faceTracking.html 进入开发者中心进行注册以及认证个人信息
    1. 点击我的应用 > 新建应用

    image-20210702134809401

    2.填写信息立即创建 点击 添加SDK

    image-20210702135034579

    3.选中免费版人脸识别

    image-20210702135111937

    4. 填写授权码信息
    选择平台先选择windows的根据你的电脑配置来 是64位还是32位的, 语言选择Java

    image-20210702135225642

    sdk

    5. 介绍sdk文件

    image-20210702135945966

    构建项目工程

    image-1652620445459

    导入项目依赖

    1. <properties>
    2. <java.version>1.8</java.version>
    3. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    4. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    5. <spring-boot.version>2.3.7.RELEASE</spring-boot.version>
    6. <druid-spring-boot-starter.version>1.2.6</druid-spring-boot-starter.version>
    7. <mybatis-spring-boot.version>2.1.4</mybatis-spring-boot.version>
    8. <pagehelper.boot.version>1.3.0</pagehelper.boot.version>
    9. </properties>
    10. <dependencies>
    11. <dependency>
    12. <groupId>org.springframework.boot</groupId>
    13. <artifactId>spring-boot-starter-web</artifactId>
    14. </dependency>
    15. <!-- 人脸识别 -->
    16. <dependency>
    17. <groupId>com.arcsoft.face</groupId>
    18. <artifactId>arcsoft-sdk-face</artifactId>
    19. <scope>system</scope>
    20. <systemPath>${project.basedir}/lib/arcsoft-sdk-face-3.0.0.0.jar</systemPath>
    21. <version>3.0.0.0</version>
    22. </dependency>
    23. <!-- pool 对象池 -->
    24. <dependency>
    25. <groupId>org.apache.commons</groupId>
    26. <artifactId>commons-pool2</artifactId>
    27. </dependency>
    28. <!-- guava -->
    29. <dependency>
    30. <groupId>com.google.guava</groupId>
    31. <artifactId>guava</artifactId>
    32. <version>27.0.1-jre</version>
    33. </dependency>
    34. <!-- Mysql驱动包 -->
    35. <dependency>
    36. <groupId>mysql</groupId>
    37. <artifactId>mysql-connector-java</artifactId>
    38. </dependency>
    39. <!-- mybatis-plus 增强CRUD -->
    40. <dependency>
    41. <groupId>com.baomidou</groupId>
    42. <artifactId>mybatis-plus-boot-starter</artifactId>
    43. <version>3.4.2</version>
    44. </dependency>
    45. <!-- pagehelper 分页插件 内置mybatis 依赖-->
    46. <dependency>
    47. <groupId>com.github.pagehelper</groupId>
    48. <artifactId>pagehelper-spring-boot-starter</artifactId>
    49. <version>${pagehelper.boot.version}</version>
    50. </dependency>
    51. <!-- 阿里数据源 -->
    52. <dependency>
    53. <groupId>com.alibaba</groupId>
    54. <artifactId>druid-spring-boot-starter</artifactId>
    55. <version>${druid-spring-boot-starter.version}</version>
    56. </dependency>
    57. <dependency>
    58. <groupId>org.springframework.boot</groupId>
    59. <artifactId>spring-boot-configuration-processor</artifactId>
    60. <optional>true</optional>
    61. </dependency>
    62. <!-- Spring框架基本的核心工具 -->
    63. <dependency>
    64. <groupId>org.springframework</groupId>
    65. <artifactId>spring-context-support</artifactId>
    66. </dependency>
    67. <!-- JSON工具类 -->
    68. <dependency>
    69. <groupId>com.fasterxml.jackson.core</groupId>
    70. <artifactId>jackson-databind</artifactId>
    71. </dependency>
    72. <dependency>
    73. <groupId>cn.hutool</groupId>
    74. <artifactId>hutool-all</artifactId>
    75. <version>5.8.0</version>
    76. </dependency>
    77. <!-- SpringWeb模块 -->
    78. <dependency>
    79. <groupId>org.springframework</groupId>
    80. <artifactId>spring-web</artifactId>
    81. </dependency>
    82. <!-- servlet包 -->
    83. <dependency>
    84. <groupId>javax.servlet</groupId>
    85. <artifactId>javax.servlet-api</artifactId>
    86. </dependency>
    87. <!-- aop -->
    88. <dependency>
    89. <groupId>org.springframework.boot</groupId>
    90. <artifactId>spring-boot-starter-aop</artifactId>
    91. </dependency>
    92. <dependency>
    93. <groupId>org.projectlombok</groupId>
    94. <artifactId>lombok</artifactId>
    95. <optional>true</optional>
    96. </dependency>
    97. </dependencies>
    98. <dependencyManagement>
    99. <dependencies>
    100. <dependency>
    101. <groupId>org.springframework.boot</groupId>
    102. <artifactId>spring-boot-dependencies</artifactId>
    103. <version>${spring-boot.version}</version>
    104. <type>pom</type>
    105. <scope>import</scope>
    106. </dependency>
    107. </dependencies>
    108. </dependencyManagement>
    109. <build>
    110. <plugins>
    111. <plugin>
    112. <groupId>org.apache.maven.plugins</groupId>
    113. <artifactId>maven-compiler-plugin</artifactId>
    114. <version>3.8.1</version>
    115. <configuration>
    116. <source>1.8</source>
    117. <target>1.8</target>
    118. <encoding>UTF-8</encoding>
    119. </configuration>
    120. </plugin>
    121. <plugin>
    122. <groupId>org.springframework.boot</groupId>
    123. <artifactId>spring-boot-maven-plugin</artifactId>
    124. <version>2.3.7.RELEASE</version>
    125. <configuration>
    126. <mainClass>top.yangbuyi.YangbuyiFaceDemoApplication</mainClass>
    127. <!-- 文件要配置includeSystemScope属性,否则可能会导致arcsoft-sdk-face-3.0.0.0.jar获取不到 -->
    128. <includeSystemScope>true</includeSystemScope>
    129. <fork>true</fork>
    130. </configuration>
    131. <executions>
    132. <execution>
    133. <id>repackage</id>
    134. <goals>
    135. <goal>repackage</goal>
    136. </goals>
    137. </execution>
    138. </executions>
    139. </plugin>
    140. </plugins>
    141. </build>

    使用代码生成器生成CURD
    版本请对应图片当中的jebat全家桶群里获取3秒破解使用

    image-1652622813045image-1652621615948

    生成完毕后在根目录创建lib目录将下载下来的人脸识别依赖导入->右击添加到库

    image-1652621634861

    application.yml 修改配置文件

    1. # 开发环境配置
    2. server:
    3. # 服务器的HTTP端口,默认为8080
    4. port: 8080
    5. servlet:
    6. # 应用的访问路径
    7. context-path: /
    8. tomcat:
    9. # tomcat的URI编码
    10. uri-encoding: UTF-8
    11. # tomcat最大线程数,默认为200
    12. max-threads: 800
    13. # Tomcat启动初始化的线程数,默认值25
    14. min-spare-threads: 30
    15. # Spring配置
    16. spring:
    17. # 同时执行其它配置文件
    18. profiles:
    19. active: druid
    20. mvc: # 把前端的接收到的时间格式 格式化为 yyyy-MM-dd HH:mm:ss
    21. date-format: yyyy-MM-dd HH:mm:ss
    22. jackson: # 把后台的时间格式 格式化为 yyyy-MM-dd HH:mm:ss
    23. date-format: yyyy-MM-dd HH:mm:ss
    24. time-zone: GMT+8
    25. # 服务模块
    26. devtools:
    27. restart:
    28. # 热部署开关
    29. enabled: true
    30. # MyBatis配置
    31. mybatis-plus:
    32. # 搜索指定包别名
    33. typeAliasesPackage: top.yangbuyi.domain
    34. # 配置mapper的扫描,找到所有的mapper.xml映射文件
    35. mapperLocations: classpath*:mapper/*Mapper.xml
    36. # 加载全局的配置文件
    37. configLocation: classpath:mybatis/mybatis-config.xml
    38. # PageHelper分页插件
    39. pagehelper:
    40. helperDialect: mysql
    41. reasonable: true
    42. supportMethodsArguments: true
    43. params: count=countSql
    44. # 人脸识别配置
    45. # WIND64
    46. config:
    47. sdk-lib-path: M:\yangbuyiya-RBAC\libs\WIN64
    48. app-id: 4QKtmacvsKqaCsoXyyujcs21JTAr79pTczPdZpuaEjhH
    49. sdk-key: EgBjrmidnqstaL46msfHukeKanYXCujzeHokf2qcC3br
    50. thread-pool-size: 5

    application-druid.yml 数据源配置

    1. # 数据源配置
    2. spring:
    3. datasource:
    4. type: com.alibaba.druid.pool.DruidDataSource
    5. driverClassName: com.mysql.cj.jdbc.Driver
    6. druid:
    7. url: jdbc:mysql://127.0.0.1:3308/face?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
    8. username: root
    9. password: 123456
    10. # 初始连接数
    11. initialSize: 5
    12. # 最小连接池数量
    13. minIdle: 10
    14. # 最大连接池数量
    15. maxActive: 20
    16. # 配置获取连接等待超时的时间
    17. maxWait: 60000
    18. # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    19. timeBetweenEvictionRunsMillis: 60000
    20. # 配置一个连接在池中最小生存的时间,单位是毫秒
    21. minEvictableIdleTimeMillis: 300000
    22. # 配置一个连接在池中最大生存的时间,单位是毫秒
    23. maxEvictableIdleTimeMillis: 900000
    24. # 配置检测连接是否有效
    25. validationQuery: SELECT 1 FROM DUAL
    26. testWhileIdle: true
    27. testOnBorrow: false
    28. testOnReturn: false
    29. webStatFilter:
    30. enabled: true
    31. statViewServlet:
    32. enabled: true
    33. # 设置白名单,不填则允许所有访问
    34. allow:
    35. url-pattern: /yangbuyi/druid/*
    36. filter:
    37. stat:
    38. enabled: true
    39. # 慢SQL记录
    40. log-slow-sql: true
    41. slow-sql-millis: 1000
    42. merge-sql: true
    43. wall:
    44. config:
    45. multi-statement-allow: true

    resources 下创建mybatis文件夹创建mybatis-config.xml文件

    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <!DOCTYPE configuration
    3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
    5. <configuration>
    6. <settings>
    7. <setting name="cacheEnabled" value="true"/> <!-- 全局映射器启用缓存 -->
    8. <setting name="useGeneratedKeys" value="true"/> <!-- 允许 JDBC 支持自动生成主键 -->
    9. <setting name="defaultExecutorType" value="REUSE"/> <!-- 配置默认的执行器 -->
    10. <setting name="logImpl" value="SLF4J"/> <!-- 指定 MyBatis 所用日志的具体实现 -->
    11. <!-- <setting name="mapUnderscoreToCamelCase" value="true"/> 驼峰式命名 -->
    12. </settings>
    13. </configuration>

    项目基础文件配置

    创建config文件
    创建ApplicationConfig全局配置类

    1. /**
    2. * 程序注解配置
    3. *
    4. * @author yangbuyi
    5. */
    6. @Configuration
    7. // 表示通过aop框架暴露该代理对象,AopContext能够访问
    8. @EnableAspectJAutoProxy(exposeProxy = true)
    9. // 指定要扫描的Mapper类的包的路径
    10. @MapperScan("top.yangbuyi.mapper")
    11. public class ApplicationConfig {
    12. /**
    13. * 时区配置
    14. */
    15. @Bean
    16. public Jackson2ObjectMapperBuilderCustomizer jacksonObjectMapperCustomization () {
    17. return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder.timeZone(TimeZone.getDefault());
    18. }
    19. /**
    20. * 处理Long类型精度丢失
    21. *
    22. * @return
    23. */
    24. @Bean("jackson2ObjectMapperBuilderCustomizer")
    25. public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer () {
    26. return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder.serializerByType(Long.class, ToStringSerializer.instance)
    27. .serializerByType(Long.TYPE, ToStringSerializer.instance);
    28. }
    29. }

    创建全局MybatisPlusConfig配置

    1. /**
    2. * @program: yangbuyi-rbac
    3. * @ClassName: MybatisPlusConfig
    4. * @create: 2022-04-25 15:48
    5. * @author: yangbuyi.top
    6. * @since: JDK1.8
    7. * @MybatisPlusConfig: $
    8. **/
    9. import com.baomidou.mybatisplus.annotation.DbType;
    10. import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
    11. import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
    12. import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
    13. import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
    14. import org.springframework.context.annotation.Bean;
    15. import org.springframework.context.annotation.Configuration;
    16. import org.springframework.transaction.annotation.EnableTransactionManagement;
    17. @EnableTransactionManagement(proxyTargetClass = true)
    18. @Configuration
    19. public class MybatisPlusConfig {
    20. @Bean
    21. public MybatisPlusInterceptor mybatisPlusInterceptor () {
    22. MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    23. // 分页插件
    24. interceptor.addInnerInterceptor(paginationInnerInterceptor());
    25. // 乐观锁插件
    26. interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor());
    27. // 阻断插件
    28. interceptor.addInnerInterceptor(blockAttackInnerInterceptor());
    29. return interceptor;
    30. }
    31. /**
    32. * 分页插件,自动识别数据库类型 https://baomidou.com/guide/interceptor-pagination.html
    33. */
    34. public PaginationInnerInterceptor paginationInnerInterceptor () {
    35. PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
    36. // 设置数据库类型为mysql
    37. paginationInnerInterceptor.setDbType(DbType.MYSQL);
    38. // 设置最大单页限制数量,默认 500 条,-1 不受限制
    39. paginationInnerInterceptor.setMaxLimit(-1L);
    40. return paginationInnerInterceptor;
    41. }
    42. /**
    43. * 乐观锁插件 https://baomidou.com/guide/interceptor-optimistic-locker.html
    44. */
    45. public OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor () {
    46. return new OptimisticLockerInnerInterceptor();
    47. }
    48. /**
    49. * 如果是对全表的删除或更新操作,就会终止该操作 https://baomidou.com/guide/interceptor-block-attack.html
    50. */
    51. public BlockAttackInnerInterceptor blockAttackInnerInterceptor () {
    52. return new BlockAttackInnerInterceptor();
    53. }
    54. }

    创建dto文件夹

    创建人脸返回实体 FaceSearchResDto

    1. /**
    2. * @author yangbuyi.top
    3. */
    4. @Data
    5. public class FaceSearchResDto {
    6. /**
    7. * 唯一人脸Id
    8. */
    9. private String faceId;
    10. /**
    11. * 人脸名称
    12. */
    13. private String name;
    14. private Integer similarValue;
    15. /**
    16. * 年龄
    17. */
    18. private Integer age;
    19. /**
    20. * 性别
    21. */
    22. private String gender;
    23. /**
    24. * 图片
    25. */
    26. private String image;
    27. }

    创建人脸映射 FaceUserInfo

    1. /**
    2. * @author yangbuyi.top
    3. */
    4. @Data
    5. public class FaceUserInfo {
    6. private int id;
    7. private int groupId;
    8. private String faceId;
    9. private String name;
    10. private Integer similarValue;
    11. private byte[] faceFeature;
    12. }

    创建年龄映射

    1. /**
    2. * @author yangbuyi.top
    3. */
    4. public class ProcessInfo {
    5. private Integer age;
    6. private Integer gender;
    7. public Integer getAge () {
    8. return age;
    9. }
    10. public void setAge (Integer age) {
    11. this.age = age;
    12. }
    13. public Integer getGender () {
    14. return gender;
    15. }
    16. public void setGender (Integer gender) {
    17. this.gender = gender;
    18. }
    19. }

    创建enums文件夹

    创建ErrorCodeEnum枚举类

    1. /**
    2. * @author yangbuyi.top
    3. */
    4. public enum ErrorCodeEnum {
    5. MOK(0, "成功"),
    6. UNKNOWN(1, "未知错误"),
    7. INVALID_PARAM(2, "无效参数"),
    8. UNSUPPORTED(3, "引擎不支持"),
    9. NO_MEMORY(4, "内存不足"),
    10. BAD_STATE(5, "状态错误"),
    11. USER_CANCEL(6, "用户取消相关操作"),
    12. EXPIRED(7, "操作时间过期"),
    13. USER_PAUSE(8, "用户暂停操作"),
    14. BUFFER_OVERFLOW(9, "缓冲上溢"),
    15. BUFFER_UNDERFLOW(10, "缓冲下溢"),
    16. NO_DISKSPACE(11, "存贮空间不足"),
    17. COMPONENT_NOT_EXIST(12, "组件不存在"),
    18. GLOBAL_DATA_NOT_EXIST(13, "全局数据不存在"),
    19. NO_FACE_DETECTED(14, "未检出到人脸"),
    20. FACE_DOES_NOT_MATCH(15, "人脸不匹配"),
    21. INVALID_APP_ID(28673, "无效的AppId"),
    22. INVALID_SDK_ID(28674, "无效的SdkKey"),
    23. INVALID_ID_PAIR(28675, "AppId和SdkKey不匹配"),
    24. MISMATCH_ID_AND_SDK(28676, "SdkKey 和使用的SDK 不匹配"),
    25. SYSTEM_VERSION_UNSUPPORTED(28677, "系统版本不被当前SDK所支持"),
    26. LICENCE_EXPIRED(28678, "SDK有效期过期,需要重新下载更新"),
    27. APS_ENGINE_HANDLE(69633, "引擎句柄非法"),
    28. APS_MEMMGR_HANDLE(69634, "内存句柄非法"),
    29. APS_DEVICEID_INVALID(69635, " Device ID 非法"),
    30. APS_DEVICEID_UNSUPPORTED(69636, "Device ID 不支持"),
    31. APS_MODEL_HANDLE(69637, "模板数据指针非法"),
    32. APS_MODEL_SIZE(69638, "模板数据长度非法"),
    33. APS_IMAGE_HANDLE(69639, "图像结构体指针非法"),
    34. APS_IMAGE_FORMAT_UNSUPPORTED(69640, "图像格式不支持"),
    35. APS_IMAGE_PARAM(69641, "图像参数非法"),
    36. APS_IMAGE_SIZE(69642, "图像尺寸大小超过支持范围"),
    37. APS_DEVICE_AVX2_UNSUPPORTED(69643, "处理器不支持AVX2指令"),
    38. FR_INVALID_MEMORY_INFO(73729, "无效的输入内存"),
    39. FR_INVALID_IMAGE_INFO(73730, "无效的输入图像参数"),
    40. FR_INVALID_FACE_INFO(73731, "无效的脸部信息"),
    41. FR_NO_GPU_AVAILABLE(73732, "当前设备无GPU可用"),
    42. FR_MISMATCHED_FEATURE_LEVEL(73733, "待比较的两个人脸特征的版本不一致"),
    43. FACEFEATURE_UNKNOWN(81921, "人脸特征检测错误未知"),
    44. FACEFEATURE_MEMORY(81922, "人脸特征检测内存错误"),
    45. FACEFEATURE_INVALID_FORMAT(81923, "人脸特征检测格式错误"),
    46. FACEFEATURE_INVALID_PARAM(81924, "人脸特征检测参数错误"),
    47. FACEFEATURE_LOW_CONFIDENCE_LEVEL(81925, "人脸特征检测结果置信度低"),
    48. ASF_EX_BASE_FEATURE_UNSUPPORTED_ON_INIT(86017, "Engine不支持的检测属性"),
    49. ASF_EX_BASE_FEATURE_UNINITED(86018, "需要检测的属性未初始化"),
    50. ASF_EX_BASE_FEATURE_UNPROCESSED(86019, "待获取的属性未在process中处理过"),
    51. ASF_EX_BASE_FEATURE_UNSUPPORTED_ON_PROCESS(86020, "PROCESS不支持的检测属性,例如FR,有自己独立的处理函数"),
    52. ASF_EX_BASE_INVALID_IMAGE_INFO(86021, "无效的输入图像"),
    53. ASF_EX_BASE_INVALID_FACE_INFO(86022, "无效的脸部信息"),
    54. ASF_BASE_ACTIVATION_FAIL(90113, "人脸比对SDK激活失败,请打开读写权限"),
    55. ASF_BASE_ALREADY_ACTIVATED(90114, "人脸比对SDK已激活"),
    56. ASF_BASE_NOT_ACTIVATED(90115, "人脸比对SDK未激活"),
    57. ASF_BASE_SCALE_NOT_SUPPORT(90116, "detectFaceScaleVal 不支持"),
    58. ASF_BASE_VERION_MISMATCH(90117, "SDK版本不匹配"),
    59. ASF_BASE_DEVICE_MISMATCH(90118, "设备不匹配"),
    60. ASF_BASE_UNIQUE_IDENTIFIER_MISMATCH(90119, "唯一标识不匹配"),
    61. ASF_BASE_PARAM_NULL(90120, "参数为空"),
    62. ASF_BASE_SDK_EXPIRED(90121, "SDK已过期"),
    63. ASF_BASE_VERSION_NOT_SUPPORT(90122, "版本不支持"),
    64. ASF_BASE_SIGN_ERROR(90123, "签名错误"),
    65. ASF_BASE_DATABASE_ERROR(90124, "数据库插入错误"),
    66. ASF_BASE_UNIQUE_CHECKOUT_FAIL(90125, "唯一标识符校验失败"),
    67. ASF_BASE_COLOR_SPACE_NOT_SUPPORT(90126, "输入的颜色空间不支持"),
    68. ASF_BASE_IMAGE_WIDTH_NOT_SUPPORT(90127, "输入图像的byte数据长度不正确"),
    69. ASF_NETWORK_BASE_COULDNT_RESOLVE_HOST(94209, "无法解析主机地址"),
    70. ASF_NETWORK_BASE_COULDNT_CONNECT_SERVER(94210, "无法连接服务器"),
    71. ASF_NETWORK_BASE_CONNECT_TIMEOUT(94211, "网络连接超时"),
    72. ASF_NETWORK_BASE_UNKNOWN_ERROR(94212, "未知错误");
    73. private Integer code;
    74. private String description;
    75. ErrorCodeEnum (Integer code, String description) {
    76. this.code = code;
    77. this.description = description;
    78. }
    79. public Integer getCode () {
    80. return code;
    81. }
    82. public void setCode (Integer code) {
    83. this.code = code;
    84. }
    85. public String getDescription () {
    86. return description;
    87. }
    88. public void setDescription (String description) {
    89. this.description = description;
    90. }
    91. public static ErrorCodeEnum getDescriptionByCode (Integer code) {
    92. for (ErrorCodeEnum errorCodeEnum : ErrorCodeEnum.values()) {
    93. if (code.equals(errorCodeEnum.getCode())) {
    94. return errorCodeEnum;
    95. }
    96. }
    97. return ErrorCodeEnum.UNKNOWN;
    98. }
    99. }

    创建utils文件夹

    创建Base64DecodeMultipartFile

    1. package top.yangbuyi.utils;
    2. import org.springframework.web.multipart.MultipartFile;
    3. import java.io.*;
    4. /**
    5. * @author yangbuyi.top
    6. * @program: yangbuyi-rbac
    7. * @ClassName: Base64DecodeMultipartFile
    8. * @create: 2022-04-25 16:25
    9. * @since: JDK1.8
    10. * @Base64DecodeMultipartFile: $
    11. **/
    12. public class Base64DecodeMultipartFile implements MultipartFile {
    13. private final byte[] imgContent;
    14. private final String header;
    15. public Base64DecodeMultipartFile (byte[] imgContent, String header) {
    16. this.imgContent = imgContent;
    17. this.header = header.split(";")[0];
    18. }
    19. @Override
    20. public String getName () {
    21. return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
    22. }
    23. @Override
    24. public String getOriginalFilename () {
    25. return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1];
    26. }
    27. @Override
    28. public String getContentType () {
    29. return header.split(":")[1];
    30. }
    31. @Override
    32. public boolean isEmpty () {
    33. return imgContent == null || imgContent.length == 0;
    34. }
    35. @Override
    36. public long getSize () {
    37. return imgContent.length;
    38. }
    39. @Override
    40. public byte[] getBytes () throws IOException {
    41. return imgContent;
    42. }
    43. @Override
    44. public InputStream getInputStream () throws IOException {
    45. return new ByteArrayInputStream(imgContent);
    46. }
    47. @Override
    48. public void transferTo (File dest) throws IOException, IllegalStateException {
    49. new FileOutputStream(dest).write(imgContent);
    50. }
    51. }

    创建ImageUtils

    1. package top.yangbuyi.utils;
    2. import org.apache.tomcat.util.codec.binary.Base64;
    3. import org.slf4j.Logger;
    4. import org.slf4j.LoggerFactory;
    5. import org.springframework.web.multipart.MultipartFile;
    6. import java.io.ByteArrayInputStream;
    7. import java.io.ByteArrayOutputStream;
    8. import java.io.FileInputStream;
    9. import java.io.InputStream;
    10. import java.net.URL;
    11. import java.net.URLConnection;
    12. import java.util.Arrays;
    13. /**
    14. * 图片处理工具类
    15. *
    16. * @author yangbuyi.top
    17. */
    18. public class ImageUtils {
    19. private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);
    20. public static MultipartFile base64ToMultipartFile (String base64) {
    21. //base64编码后的图片有头信息所以要分离出来 [0]data:image/png;base64, 图片内容为索引[1]
    22. String[] baseStrs = base64.split(",");
    23. //取索引为1的元素进行处理
    24. byte[] b = Base64.decodeBase64(baseStrs[1]);
    25. for (int i = 0; i < b.length; ++i) {
    26. if (b[i] < 0) {
    27. b[i] += 256;
    28. }
    29. }
    30. //处理过后的数据通过Base64DecodeMultipartFile转换为MultipartFile对象
    31. return new Base64DecodeMultipartFile(b, baseStrs[0]);
    32. }
    33. }

    项目基本需要的配置与工具已经创建完毕接下来我们开始人脸识别业务编写

    实现BasePooledObjectFactory自定义引擎工厂

    创建factory文件夹->创建FaceEngineFactory类

    1. import com.arcsoft.face.EngineConfiguration;
    2. import com.arcsoft.face.FaceEngine;
    3. import com.arcsoft.face.enums.DetectMode;
    4. import com.arcsoft.face.enums.DetectOrient;
    5. import lombok.extern.slf4j.Slf4j;
    6. import org.apache.commons.pool2.BasePooledObjectFactory;
    7. import org.apache.commons.pool2.PooledObject;
    8. import org.apache.commons.pool2.impl.DefaultPooledObject;
    9. /**
    10. * 引擎工厂
    11. * @author yangbuyi.top
    12. */
    13. @Slf4j
    14. public class FaceEngineFactory extends BasePooledObjectFactory<FaceEngine> {
    15. private final String appId;
    16. private final String sdkKey;
    17. private final String sdkLibPath;
    18. private final EngineConfiguration engineConfiguration;
    19. private final Integer detectFaceMaxNum = 10;
    20. private final Integer detectFaceScaleVal = 16;
    21. private final DetectMode detectMode = DetectMode.ASF_DETECT_MODE_IMAGE;
    22. private final DetectMode detectVideo = DetectMode.ASF_DETECT_MODE_VIDEO;
    23. private final DetectOrient detectFaceOrientPriority = DetectOrient.ASF_OP_0_ONLY;
    24. public FaceEngineFactory (String sdkLibPath, String appId, String sdkKey, EngineConfiguration engineConfiguration) {
    25. this.sdkLibPath = sdkLibPath;
    26. this.appId = appId;
    27. this.sdkKey = sdkKey;
    28. this.engineConfiguration = engineConfiguration;
    29. }
    30. @Override
    31. public FaceEngine create () throws Exception {
    32. FaceEngine faceEngine = new FaceEngine(sdkLibPath);
    33. // 用于在线激活SDK---
    34. int activeCode = faceEngine.activeOnline(appId, sdkKey);
    35. log.info("在线激活SDK完毕!,{}", activeCode);
    36. int initCode = faceEngine.init(engineConfiguration);
    37. log.info("初始化功能引擎完毕!,{}", initCode);
    38. return faceEngine;
    39. }
    40. @Override
    41. public PooledObject<FaceEngine> wrap (FaceEngine faceEngine) {
    42. return new DefaultPooledObject<>(faceEngine);
    43. }
    44. @Override
    45. public void destroyObject (PooledObject<FaceEngine> p) throws Exception {
    46. FaceEngine faceEngine = p.getObject();
    47. int unInitCode = faceEngine.unInit();
    48. super.destroyObject(p);
    49. log.info("销毁对象完毕! faceEngineUnInitCode: {}", unInitCode);
    50. }
    51. }

    一、编写人脸识别业务接口

    在service目录下创建-> FaceEngineService

    1. package top.yangbuyi.service;
    2. import com.arcsoft.face.FaceInfo;
    3. import com.arcsoft.face.toolkit.ImageInfo;
    4. import top.yangbuyi.dto.FaceUserInfo;
    5. import top.yangbuyi.dto.ProcessInfo;
    6. import java.util.List;
    7. import java.util.concurrent.ExecutionException;
    8. /**
    9. * 人脸识别接口
    10. */
    11. public interface FaceEngineService {
    12. /**
    13. * 人脸检测
    14. * @param imageInfo
    15. * @return
    16. */
    17. List<FaceInfo> detectFaces (ImageInfo imageInfo);
    18. /**
    19. * 提取年龄-性别
    20. * @param imageInfo
    21. * @return
    22. */
    23. List<ProcessInfo> process (ImageInfo imageInfo);
    24. /**
    25. * 人脸特征
    26. * @param imageInfo
    27. * @return
    28. */
    29. byte[] extractFaceFeature (ImageInfo imageInfo) throws InterruptedException;
    30. /**
    31. * 人脸比对
    32. * @param groupId
    33. * @param faceFeature
    34. * @return
    35. */
    36. List<FaceUserInfo> compareFaceFeature (byte[] faceFeature, Integer groupId) throws InterruptedException, ExecutionException;
    37. }

    service.impl 包下创建 FaceEngineServiceImpl 实现类

    1. import cn.hutool.core.collection.CollectionUtil;
    2. import com.arcsoft.face.*;
    3. import com.arcsoft.face.enums.DetectMode;
    4. import com.arcsoft.face.enums.DetectOrient;
    5. import com.arcsoft.face.toolkit.ImageInfo;
    6. import com.google.common.collect.Lists;
    7. import org.apache.commons.pool2.impl.GenericObjectPool;
    8. import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
    9. import org.slf4j.Logger;
    10. import org.slf4j.LoggerFactory;
    11. import org.springframework.beans.factory.annotation.Autowired;
    12. import org.springframework.beans.factory.annotation.Value;
    13. import org.springframework.stereotype.Service;
    14. import top.yangbuyi.dto.FaceUserInfo;
    15. import top.yangbuyi.dto.ProcessInfo;
    16. import top.yangbuyi.factory.FaceEngineFactory;
    17. import top.yangbuyi.mapper.SysUserFaceInfoMapper;
    18. import top.yangbuyi.service.FaceEngineService;
    19. import javax.annotation.PostConstruct;
    20. import java.math.BigDecimal;
    21. import java.util.ArrayList;
    22. import java.util.List;
    23. import java.util.concurrent.*;
    24. /**
    25. * @author yangbuyi.top
    26. */
    27. @Service
    28. public class FaceEngineServiceImpl implements FaceEngineService {
    29. public final static Logger logger = LoggerFactory.getLogger(FaceEngineServiceImpl.class);
    30. @Value("${config.sdk-lib-path}")
    31. public String sdkLibPath;
    32. @Value("${config.app-id}")
    33. public String appId;
    34. @Value("${config.sdk-key}")
    35. public String sdkKey;
    36. @Value("${config.thread-pool-size}")
    37. public Integer threadPoolSize;
    38. /**
    39. * 人脸识别引擎
    40. */
    41. private static FaceEngine faceEngine;
    42. /**
    43. * 相似度
    44. */
    45. private final Integer passRate = 95;
    46. private ExecutorService executorService;
    47. @Autowired
    48. private SysUserFaceInfoMapper userFaceInfoMapper;
    49. /**
    50. * 线程池
    51. */
    52. private GenericObjectPool<FaceEngine> faceEngineObjectPool;
    53. /**
    54. * 项目启动时初始化线程池与人脸识别引擎配置
    55. */
    56. @PostConstruct
    57. public void init () {
    58. executorService = Executors.newFixedThreadPool(threadPoolSize);
    59. GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    60. poolConfig.setMaxIdle(threadPoolSize);
    61. poolConfig.setMaxTotal(threadPoolSize);
    62. poolConfig.setMinIdle(threadPoolSize);
    63. poolConfig.setLifo(false);
    64. //引擎配置
    65. EngineConfiguration engineConfiguration = new EngineConfiguration();
    66. engineConfiguration.setDetectMode(DetectMode.ASF_DETECT_MODE_IMAGE);
    67. engineConfiguration.setDetectFaceOrientPriority(DetectOrient.ASF_OP_0_ONLY);
    68. //功能配置 对应的功能请查看文档
    69. FunctionConfiguration functionConfiguration = new FunctionConfiguration();
    70. functionConfiguration.setSupportAge(true);
    71. functionConfiguration.setSupportFace3dAngle(true);
    72. functionConfiguration.setSupportFaceDetect(true);
    73. functionConfiguration.setSupportFaceRecognition(true);
    74. functionConfiguration.setSupportGender(true);
    75. functionConfiguration.setSupportLiveness(true);
    76. functionConfiguration.setSupportIRLiveness(true);
    77. engineConfiguration.setFunctionConfiguration(functionConfiguration);
    78. // 底层库算法对象池
    79. faceEngineObjectPool = new GenericObjectPool(new FaceEngineFactory(sdkLibPath, appId, sdkKey, engineConfiguration), poolConfig);
    80. try {
    81. faceEngine = faceEngineObjectPool.borrowObject();
    82. } catch (Exception e) {
    83. e.printStackTrace();
    84. }
    85. }
    86. /**
    87. * 确保精度
    88. * @param value
    89. * @return
    90. */
    91. private int plusHundred (Float value) {
    92. BigDecimal target = new BigDecimal(value);
    93. BigDecimal hundred = new BigDecimal(100f);
    94. return target.multiply(hundred).intValue();
    95. }
    96. }

    人脸识别逻辑

    1、必须进行人脸特征获取 -> 特征获取成功 -> 进入人脸对比 -> 人脸检测 -> 返回人脸数据
    2、必须进行人脸特征获取 -> 特征获取失败 -> 直接跳出返回 未检出到人脸

    编写人脸特征获取逻辑

    1. /**
    2. * 人脸特征
    3. *
    4. * @param imageInfo
    5. * @return
    6. */
    7. @Override
    8. public byte[]extractFaceFeature(ImageInfo imageInfo)throws InterruptedException{
    9. FaceEngine faceEngine=null;
    10. try{
    11. //获取引擎对象
    12. faceEngine=faceEngineObjectPool.borrowObject();
    13. //人脸检测得到人脸列表
    14. List<FaceInfo> faceInfoList=new ArrayList<FaceInfo>();
    15. //人脸检测
    16. int i=faceEngine.detectFaces(imageInfo.getImageData(),imageInfo.getWidth(),imageInfo.getHeight(),imageInfo.getImageFormat(),faceInfoList);
    17. if(CollectionUtil.isNotEmpty(faceInfoList)){
    18. FaceFeature faceFeature=new FaceFeature();
    19. //提取人脸特征
    20. faceEngine.extractFaceFeature(imageInfo.getImageData(),imageInfo.getWidth(),imageInfo.getHeight(),imageInfo.getImageFormat(),faceInfoList.get(0),faceFeature);
    21. return faceFeature.getFeatureData();
    22. }
    23. }catch(Exception e){
    24. logger.error("",e);
    25. }finally{
    26. if(faceEngine!=null){
    27. //释放引擎对象
    28. faceEngineObjectPool.returnObject(faceEngine);
    29. }
    30. }
    31. return null;
    32. }

    编写人脸对比逻辑

    1. /**
    2. * 人脸比对
    3. * @param groupId
    4. * @param faceFeature
    5. * @return 人脸组
    6. */
    7. @Override
    8. public List<FaceUserInfo> compareFaceFeature(byte[]faceFeature,Integer groupId)throws InterruptedException,ExecutionException{
    9. // 识别到的人脸列表
    10. List<FaceUserInfo> resultFaceInfoList=Lists.newLinkedList();
    11. // 创建人脸特征对象
    12. FaceFeature targetFaceFeature=new FaceFeature();
    13. targetFaceFeature.setFeatureData(faceFeature);
    14. // 根据分组拿人脸库,从数据库中取出人脸库
    15. List<FaceUserInfo> faceInfoList=userFaceInfoMapper.getUserFaceInfoByGroupId(groupId);
    16. // 分成50一组,多线程处理, 数据量大1000组
    17. List<List<FaceUserInfo>>faceUserInfoPartList=Lists.partition(faceInfoList,50);
    18. // 多线程
    19. CompletionService<List<FaceUserInfo>>completionService=new ExecutorCompletionService(executorService);
    20. for(List<FaceUserInfo> part:faceUserInfoPartList){
    21. // 开始线程扫描人脸匹配度
    22. completionService.submit(new CompareFaceTask(part,targetFaceFeature));
    23. }
    24. // 获取线程任务参数
    25. for(List<FaceUserInfo> faceUserInfos:faceUserInfoPartList){
    26. List<FaceUserInfo> faceUserInfoList=completionService.take().get();
    27. if(CollectionUtil.isNotEmpty(faceInfoList)){
    28. resultFaceInfoList.addAll(faceUserInfoList);
    29. }
    30. }
    31. // 从大到小排序
    32. resultFaceInfoList.sort((h1,h2)->h2.getSimilarValue().compareTo(h1.getSimilarValue()));
    33. return resultFaceInfoList;
    34. }
    35. /**
    36. * 多线程跑人脸对比逻辑
    37. */
    38. private class CompareFaceTask implements Callable<List<FaceUserInfo>> {
    39. private final List<FaceUserInfo> faceUserInfoList;
    40. private final FaceFeature targetFaceFeature;
    41. public CompareFaceTask (List<FaceUserInfo> faceUserInfoList, FaceFeature targetFaceFeature) {
    42. this.faceUserInfoList = faceUserInfoList;
    43. this.targetFaceFeature = targetFaceFeature;
    44. }
    45. @Override
    46. public List<FaceUserInfo> call () throws Exception {
    47. FaceEngine faceEngine = null;
    48. //识别到的人脸列表
    49. List<FaceUserInfo> resultFaceInfoList = Lists.newLinkedList();
    50. try {
    51. faceEngine = faceEngineObjectPool.borrowObject();
    52. for (FaceUserInfo faceUserInfo : faceUserInfoList) {
    53. FaceFeature sourceFaceFeature = new FaceFeature();
    54. // 设置人脸特征
    55. sourceFaceFeature.setFeatureData(faceUserInfo.getFaceFeature());
    56. FaceSimilar faceSimilar = new FaceSimilar();
    57. faceEngine.compareFaceFeature(targetFaceFeature, sourceFaceFeature, faceSimilar);
    58. //获取相似值
    59. Integer similarValue = plusHundred(faceSimilar.getScore());
    60. //相似值大于配置预期,加入到识别到人脸的列表
    61. if (similarValue > passRate) {
    62. FaceUserInfo info = new FaceUserInfo();
    63. info.setName(faceUserInfo.getName());
    64. info.setFaceId(faceUserInfo.getFaceId());
    65. info.setSimilarValue(similarValue);
    66. resultFaceInfoList.add(info);
    67. }
    68. }
    69. } catch (Exception e) {
    70. logger.error("", e);
    71. } finally {
    72. if (faceEngine != null) {
    73. faceEngineObjectPool.returnObject(faceEngine);
    74. }
    75. }
    76. return resultFaceInfoList;
    77. }
    78. }

    编写根据根据分组ID获取人脸库数据

    在mapper下SysUserFaceInfoMapper -> 创建接口 getUserFaceInfoByGroupId

    1. /**
    2. * 根据分组Id
    3. * 从数据库中取出人脸库
    4. *
    5. * @param groupId
    6. * @return 人脸库
    7. */
    8. List<FaceUserInfo> getUserFaceInfoByGroupId(Integer groupId);

    sql实现

    1. <resultMap id="userFace2" type="top.yangbuyi.dto.FaceUserInfo">
    2. <id column="id" property="id" javaType="int"/>
    3. <result column="group_id" property="groupId" javaType="java.lang.Integer"/>
    4. <result column="name" property="name" javaType="java.lang.String"/>
    5. <result column="face_id" property="faceId" javaType="String"/>
    6. <result column="face_feature" property="faceFeature"/>
    7. </resultMap>
    8. <
    9. select id = "getUserFaceInfoByGroupId" resultMap="userFace2" parameterType="java.lang.Integer"
    10. resultType="top.yangbuyi.dto.FaceUserInfo">
    11. select id, group_id, face_id, name, face_feature
    12. from `sys_user_face_info`
    13. where group_id = #{groupId}
    14. < /
    15. select>

    二、编写人脸添加业务接口

    userFaceInfoService 新增人脸业务接口

    1. /**
    2. * 新增用户人脸识别
    3. *
    4. * @param sysUserFaceInfo 用户人脸识别
    5. * @return 结果
    6. */
    7. public int insertSysUserFaceInfo(SysUserFaceInfo sysUserFaceInfo);
    就是一共简简单单的新增插入数据 这个就不用我教了吧?????????

    image-1652677051101

    三、 编写Controller业务控制层

    1. import top.yangbuyi.domain.AjaxResult;
    2. /**
    3. * (sys_user_face_info)表控制层
    4. *
    5. * @author yangbuyi.top
    6. */
    7. @RestController
    8. @Slf4j
    9. @RequestMapping("face")
    10. @RequiredArgsConstructor
    11. public class SysUserFaceInfoController {
    12. public final static Logger logger = LoggerFactory.getLogger(SysUserFaceInfoController.class);
    13. private final FaceEngineService faceEngineService;
    14. private final SysUserFaceInfoService userFaceInfoService;
    15. /**
    16. * 人脸添加
    17. *
    18. * @param file 人脸附件
    19. * @param groupId 分组id
    20. * @param name 用户登录名称
    21. */
    22. @RequestMapping(value = "/faceAdd", method = RequestMethod.POST)
    23. public AjaxResult faceAdd (@RequestBody Map<String, Object> map) {
    24. // 业务.... yangbuyi.top 版权所有
    25. return AjaxResult.success();
    26. }
    27. /**
    28. * 人脸识别
    29. *
    30. * @param file 人脸附件
    31. * @param groupId 分组ID 方便快速识别
    32. */
    33. @RequestMapping(value = "/faceSearch", method = RequestMethod.POST)
    34. public AjaxResult faceSearch (@RequestBody Map<String, Object> map) throws Exception {
    35. // 业务... yangbuyi.top 版权所有
    36. return AjaxResult.success();
    37. }

    faceAdd 具体业务编写

    1. 根据前端传递的
      file -> 人脸图片
      groupId -> 用户分组(用于缩小范围查询该人员的位置有效减少数据量大的问题)
      name -> 当前用户名称(实际开发当中应该是存储id)
    1. String file = String.valueOf(map.get("file"));
    2. String groupId = String.valueOf(map.get("groupId"));
    3. String name = String.valueOf(map.get("name"));
    4. try {
    5. if (file == null) {
    6. return AjaxResult.error("file is null");
    7. }
    8. if (groupId == null) {
    9. return AjaxResult.error("file is null");
    10. }
    11. if (name == null) {
    12. return AjaxResult.error("file is null");
    13. }
    14. // 转换实体
    15. byte[] decode = Base64.decode(base64Process(file));
    16. ImageInfo imageInfo = ImageFactory.getRGBData(decode);
    17. //人脸特征获取
    18. byte[] bytes = faceEngineService.extractFaceFeature(imageInfo);
    19. if (bytes == null) {
    20. return AjaxResult.error(ErrorCodeEnum.NO_FACE_DETECTED.getDescription());
    21. }
    22. List<ProcessInfo> processInfoList = faceEngineService.process(imageInfo);
    23. // 开始将人脸识别Base64转换文件流->用于文件上传
    24. // final MultipartFile multipartFile = ImageUtils.base64ToMultipartFile(file);
    25. final SysUserFaceInfo one = this.userFaceInfoService.lambdaQuery().eq(SysUserFaceInfo::getName, name).one();
    26. // 如果存在则更新人脸和特征
    27. if (null != one) {
    28. this.userFaceInfoService.lambdaUpdate().set(SysUserFaceInfo::getFaceFeature, bytes)
    29. .set(SysUserFaceInfo::getFpath, "存储头像地址")
    30. .eq(SysUserFaceInfo::getFaceId, name).update();
    31. } else {
    32. // 组装人脸实体
    33. SysUserFaceInfo userFaceInfo = new SysUserFaceInfo();
    34. userFaceInfo.setName(name);
    35. userFaceInfo.setAge(processInfoList.get(0).getAge());
    36. userFaceInfo.setGender(processInfoList.get(0).getGender().shortValue());
    37. userFaceInfo.setGroupId(Integer.valueOf(groupId));
    38. userFaceInfo.setFaceFeature(bytes);
    39. userFaceInfo.setFpath("存储头像地址");
    40. // 存储用户ID -> 我这里先使用name代替 -> 假如是唯一性
    41. userFaceInfo.setFaceId(name);
    42. //人脸特征插入到数据库
    43. userFaceInfoService.insertSysUserFaceInfo(userFaceInfo);
    44. }
    45. logger.info("faceAdd:" + name);
    46. return AjaxResult.success("人脸绑定成功!");
    47. } catch (Exception e) {
    48. logger.error("", e);
    49. }
    50. // 错误返回
    51. return AjaxResult.error(ErrorCodeEnum.UNKNOWN.getDescription());

    faceSearch 具体业务编写

    1. 根据前端传递的
      file -> 人脸图片
      groupId -> 用户分组(用于缩小范围查询该人员的位置有效减少数据量大的问题)
    1. String file = String.valueOf(map.get("file"));
    2. String groupId = String.valueOf(map.get("groupId"));
    3. if (groupId == null) {
    4. return AjaxResult.error("groupId is null");
    5. }
    6. byte[] decode = Base64.decode(base64Process(file));
    7. BufferedImage bufImage = ImageIO.read(new ByteArrayInputStream(decode));
    8. ImageInfo imageInfo = ImageFactory.bufferedImage2ImageInfo(bufImage);
    9. //人脸特征获取
    10. byte[] bytes = faceEngineService.extractFaceFeature(imageInfo);
    11. // 校验是否显示出人脸
    12. if (bytes == null) {
    13. return AjaxResult.error(ErrorCodeEnum.NO_FACE_DETECTED.getDescription());
    14. }
    15. //人脸比对,获取比对结果
    16. List<FaceUserInfo> userFaceInfoList = faceEngineService.compareFaceFeature(bytes, Integer.valueOf(groupId));
    17. if (CollectionUtil.isNotEmpty(userFaceInfoList)) {
    18. FaceUserInfo faceUserInfo = userFaceInfoList.get(0);
    19. FaceSearchResDto faceSearchResDto = new FaceSearchResDto();
    20. BeanUtil.copyProperties(faceUserInfo, faceSearchResDto);
    21. List<ProcessInfo> processInfoList = faceEngineService.process(imageInfo);
    22. if (CollectionUtil.isNotEmpty(processInfoList)) {
    23. //人脸检测
    24. List<FaceInfo> faceInfoList = faceEngineService.detectFaces(imageInfo);
    25. int left = faceInfoList.get(0).getRect().getLeft();
    26. int top = faceInfoList.get(0).getRect().getTop();
    27. int width = faceInfoList.get(0).getRect().getRight() - left;
    28. int height = faceInfoList.get(0).getRect().getBottom() - top;
    29. Graphics2D graphics2D = bufImage.createGraphics();
    30. // 红色
    31. graphics2D.setColor(Color.RED);
    32. BasicStroke stroke = new BasicStroke(5f);
    33. graphics2D.setStroke(stroke);
    34. graphics2D.drawRect(left, top, width, height);
    35. ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    36. ImageIO.write(bufImage, "jpg", outputStream);
    37. byte[] bytes1 = outputStream.toByteArray();
    38. faceSearchResDto.setImage("data:image/jpeg;base64," + Base64Utils.encodeToString(bytes1));
    39. faceSearchResDto.setAge(processInfoList.get(0).getAge());
    40. faceSearchResDto.setGender(processInfoList.get(0).getGender().equals(1) ? "女" : "男");
    41. }
    42. return AjaxResult.success(faceSearchResDto);
    43. }
    44. return AjaxResult.error(ErrorCodeEnum.FACE_DOES_NOT_MATCH.getDescription());

    测试接口流程

    准备两张图片
    百度随便搜索个在线转换 Base64

    (在线图片转Base64)

    image-1652703631886

    1、人脸添加

    新增有脸的

    image-1652702349484

    新增测试无脸的

    image-1652703497056

    2、人脸识别

    有脸的

    image-1652703318357

    无脸的

    image-1652703532069

    结尾在线演示

    (前往享受人脸识别)

    image-1652677885135

  • 相关阅读:
    设计模式--职责链模式(Chain of Responsibility Pattern)
    javacofig几个常用注解
    Mybatis日志框架
    【电气安全】安科瑞电气火灾监控系统在江苏某大学中设计与应用
    SQL查询语句中DISTINCT去重的方法,DISTINCT必须放在第一位
    Springboot内置Tomcat配置参数调优
    华为od面试记录
    力扣-228. 汇总区间
    ESP-RTC方案乐鑫ESP32-S3音视频通信应用,启明云端乐鑫代理商
    有财务自由的思维,才能实现财务自由!
  • 原文地址:https://blog.csdn.net/GenuineYangbuyi/article/details/124906276