小言_互联网的博客

百度离线人脸识别SDK

561人阅读  评论(0)

1,采坑备忘

(1)8.1版本的SDK在spring-boot接口访问第一次正常,第二次之后JVM会奔溃,可能是java gc 处理C++开出的内存有问题。

        换6.1.3版本的SDK。

java+Windows百度离线人脸识别SDK6.1.3-Java文档类资源-CSDN下载java+Windows百度离线人脸识别SDK6.1.3。支持spring-boot集成。更多下载资源、学习资料请访问CSDN下载频道.https://download.csdn.net/download/zj850324/87347677

(2)6.1.3版本SDK无法加载BaiduFaceApi.dll。依赖vc_redist.x64 2013,包里给的是2015。

javaOpenCV320依赖的动态链接库-Java文档类资源-CSDN下载javaOpenCV320依赖的动态链接库更多下载资源、学习资料请访问CSDN下载频道.https://download.csdn.net/download/zj850324/87283565

2,spring-boot项目示例

(1)pom.xml


  
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation= "http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0 </modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot </groupId>
  7. <artifactId>spring-boot-starter-parent </artifactId>
  8. <version>2.3.3.RELEASE </version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.ai </groupId>
  12. <artifactId>risun-ai </artifactId>
  13. <version>0.0.1-SNAPSHOT </version>
  14. <name>risun-ai </name>
  15. <description>Demo project for Spring Boot </description>
  16. <properties>
  17. <java.version>1.8 </java.version>
  18. </properties>
  19. <repositories>
  20. <repository>
  21. <id>huaweicloud </id>
  22. <url>https://repo.huaweicloud.com/repository/maven/ </url>
  23. <!--<url>http://maven.aliyun.com/nexus/content/groups/public/</url>-->
  24. <releases>
  25. <enabled>true </enabled>
  26. </releases>
  27. <snapshots>
  28. <enabled>true </enabled>
  29. <updatePolicy>always </updatePolicy>
  30. <checksumPolicy>fail </checksumPolicy>
  31. </snapshots>
  32. </repository>
  33. </repositories>
  34. <dependencies>
  35. <dependency>
  36. <groupId>javax.servlet </groupId>
  37. <artifactId>javax.servlet-api </artifactId>
  38. <scope>provided </scope>
  39. </dependency>
  40. <dependency>
  41. <groupId>org.springframework.boot </groupId>
  42. <artifactId>spring-boot-starter </artifactId>
  43. </dependency>
  44. <dependency>
  45. <groupId>org.springframework.boot </groupId>
  46. <artifactId>spring-boot-starter-web </artifactId>
  47. </dependency>
  48. <dependency>
  49. <groupId>org.springframework.boot </groupId>
  50. <artifactId>spring-boot-starter-test </artifactId>
  51. <scope>test </scope>
  52. </dependency>
  53. <dependency>
  54. <groupId>io.springfox </groupId>
  55. <artifactId>springfox-swagger2 </artifactId>
  56. <version>2.9.2 </version>
  57. </dependency>
  58. <dependency>
  59. <groupId>io.springfox </groupId>
  60. <artifactId>springfox-swagger-ui </artifactId>
  61. <version>2.9.2 </version>
  62. </dependency>
  63. <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
  64. <dependency>
  65. <groupId>org.projectlombok </groupId>
  66. <artifactId>lombok </artifactId>
  67. <version>1.18.22 </version>
  68. <scope>provided </scope>
  69. </dependency>
  70. <dependency>
  71. <groupId>com.baidu.aip </groupId>
  72. <artifactId>java-sdk </artifactId>
  73. <version>4.15.1 </version>
  74. </dependency>
  75. <dependency>
  76. <groupId>com.google.code.gson </groupId>
  77. <artifactId>gson </artifactId>
  78. <version>2.8.3 </version>
  79. </dependency>
  80. <dependency>
  81. <groupId>com.google.code.gson </groupId>
  82. <artifactId>gson </artifactId>
  83. <version>2.8.5 </version>
  84. </dependency>
  85. <dependency>
  86. <groupId>org.apache.httpcomponents </groupId>
  87. <artifactId>httpclient </artifactId>
  88. <version>4.5.2 </version>
  89. </dependency>
  90. </dependencies>
  91. <build>
  92. <plugins>
  93. <plugin>
  94. <groupId>org.springframework.boot </groupId>
  95. <artifactId>spring-boot-maven-plugin </artifactId>
  96. </plugin>
  97. </plugins>
  98. </build>
  99. </project>

(2)启动


  
  1. package com;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import com.ai.local.FaceLocalFactory;
  5. import com.jni.face.Face;
  6. @SpringBootApplication
  7. public class RisunAiApplication {
  8. public static void main (String[] args) {
  9. //FaceLocalFactory.sdkInit();
  10. //Face.loadDbFace();
  11. SpringApplication.run(RisunAiApplication.class, args);
  12. System.out.println( ":::主线程启动");
  13. }
  14. }

 


  
  1. package com;
  2. /**
  3. *@author created by Jerry
  4. *@date 2022年12月23日---下午4:51:37
  5. *@problem
  6. *@answer
  7. *@action
  8. */
  9. import com.jni.face.Face;
  10. import org.springframework.boot.ApplicationArguments;
  11. import org.springframework.boot.ApplicationRunner;
  12. import org.springframework.stereotype.Component;
  13. @Component
  14. public class SdkInit implements ApplicationRunner{
  15. @Override
  16. public void run (ApplicationArguments applicationArguments) throws Exception{
  17. /* sdk初始化 */
  18. Face api = new Face();
  19. // model_path为模型文件夹路径,即models文件夹(里面存的是人脸识别的模型文件)
  20. // 传空为采用默认路径,若想定置化路径,请填写全局路径如:d:\\face (models模型文件夹目录放置后为d:\\face\\models)
  21. // 若模型文件夹采用定置化路径,则激活文件(license.ini, license.key)也可采用定制化路径放置到该目录如d:\\face\\license
  22. // 亦可在激活文件默认生成的路径
  23. String modelPath = "";
  24. int res = api.sdkInit(modelPath);
  25. if (res != 0) {
  26. System.out.printf( "sdk init fail and error =%d\n", res);
  27. }
  28. Face.loadDbFace();
  29. // 获取设备指纹
  30. String deviceId = Face.getDeviceId();
  31. System.out.printf( "device id:" + deviceId);
  32. // 获取版本号
  33. String ver = Face.sdkVersion();
  34. System.out.printf( "sdk version:" + ver);
  35. }
  36. }

 


  
  1. package com;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.boot.CommandLineRunner;
  7. import org.springframework.stereotype.Component;
  8. import com.task.ClearFilesTask;
  9. /**
  10. *
  11. * @author jerry
  12. * 清理垃圾
  13. */
  14. @Component
  15. public class Branch_02 implements CommandLineRunner {
  16. Logger m_log = LoggerFactory.getLogger(getClass());
  17. @Value("${cacheTime}")
  18. Long m_cacheTime;
  19. @Autowired
  20. ClearFilesTask m_clearFilesTask;
  21. @Override
  22. public void run (String... arg0) throws Exception {
  23. if (m_cacheTime <= 0) {
  24. return;
  25. }
  26. this.m_log.info( ":::清理线程启动");
  27. Thread thread = new Thread( this.m_clearFilesTask);
  28. thread.start();
  29. }
  30. }

 


  
  1. package com;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.boot.CommandLineRunner;
  7. import org.springframework.stereotype.Component;
  8. import com.ai.local.FaceLocalFactory;
  9. import com.jni.face.Face;
  10. import com.task.CamersLocalTask;
  11. /**
  12. *
  13. * @author jerry
  14. * 截图识别 本地离线
  15. */
  16. @Component
  17. public class Branch_04 implements CommandLineRunner {
  18. Logger m_log = LoggerFactory.getLogger(getClass());
  19. @Value("${rtspLocalScreenshot}")
  20. String rtspLocalScreenshot;
  21. @Autowired
  22. CamersLocalTask m_camersLocalTask;
  23. @Override
  24. public void run (String... arg0) throws Exception {
  25. if ( this.rtspLocalScreenshot != null && this.rtspLocalScreenshot.equalsIgnoreCase( "false")) {
  26. return;
  27. }
  28. this.m_log.info( ":::本地离线截图识别线程启动");
  29. Thread thread = new Thread( this.m_camersLocalTask);
  30. thread.start();
  31. }
  32. }

(3)人脸库管理


  
  1. package com.controller;
  2. import java.io.File;
  3. import java.text.SimpleDateFormat;
  4. import java.util.Date;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. import java.util.UUID;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.beans.factory.annotation.Value;
  10. import org.springframework.stereotype.Controller;
  11. import org.springframework.web.bind.annotation.GetMapping;
  12. import org.springframework.web.bind.annotation.PathVariable;
  13. import org.springframework.web.bind.annotation.PostMapping;
  14. import org.springframework.web.bind.annotation.RequestBody;
  15. import org.springframework.web.bind.annotation.RequestMapping;
  16. import org.springframework.web.bind.annotation.RequestMethod;
  17. import org.springframework.web.bind.annotation.RequestParam;
  18. import org.springframework.web.bind.annotation.ResponseBody;
  19. import org.springframework.web.multipart.MultipartFile;
  20. import com.ai.local.FaceLibLocal;
  21. import com.ai.local.entity.UserFace;
  22. import com.util.AjaxResult;
  23. import com.util.FileUtil;
  24. import io.swagger.annotations.Api;
  25. import io.swagger.annotations.ApiImplicitParam;
  26. import io.swagger.annotations.ApiImplicitParams;
  27. import io.swagger.annotations.ApiModelProperty;
  28. import io.swagger.annotations.ApiOperation;
  29. @Api(value = "FaceLibController", description = "本地人脸库管理接口")
  30. @Controller
  31. @RequestMapping(value = "/facelib")
  32. @ResponseBody
  33. public class FaceLibController extends BasicController
  34. {
  35. @Autowired
  36. FaceLibLocal m_FaceLibLocal;
  37. @Value("${upload_path}")
  38. String upload_path;
  39. @ApiOperation(value="获取组列表",notes="获取组列表")
  40. @GetMapping(value = "/getGroupList")
  41. @ApiImplicitParams({
  42. @ApiImplicitParam(name = "pageStart", value = "起始页码", example="0", required = true ,dataType = "int",paramType = "query"),
  43. @ApiImplicitParam(name = "pageSize", value = "每页条数", example="10", required = true ,dataType = "int",paramType = "query")
  44. })
  45. public AjaxResult getGroupList (@RequestParam(defaultValue = "pageStart") int pageStart, @RequestParam(defaultValue = "pageSize") int pageSize) throws Exception
  46. {
  47. return AjaxResult.success(m_FaceLibLocal.getGroupList(pageStart, pageSize));
  48. }
  49. @ApiOperation(value="添加组",notes="添加组")
  50. @GetMapping(value = "/addGroup")
  51. @ApiImplicitParams({
  52. @ApiImplicitParam(name = "groupid", value = "组ID", required = true ,dataType = "string",paramType = "query")
  53. })
  54. public AjaxResult addGroup (@RequestParam(defaultValue = "groupid") String groupid) throws Exception
  55. {
  56. return AjaxResult.success(m_FaceLibLocal.addGroup(groupid));
  57. }
  58. @ApiOperation(value="删除组",notes="删除组")
  59. @GetMapping(value = "/removeGroup")
  60. @ApiImplicitParams({
  61. @ApiImplicitParam(name = "groupid", value = "组ID", required = true ,dataType = "string",paramType = "query")
  62. })
  63. public AjaxResult removeGroup (@RequestParam(defaultValue = "groupid") String groupid) throws Exception
  64. {
  65. return AjaxResult.success(m_FaceLibLocal.removeGroup(groupid));
  66. }
  67. @ApiOperation(value="获取某组的用户列表",notes="获取某组的用户列表")
  68. @GetMapping(value = "/getUserList")
  69. @ApiImplicitParams({
  70. @ApiImplicitParam(name = "groupid", value = "组ID", required = true ,dataType = "string",paramType = "query"),
  71. @ApiImplicitParam(name = "pageStart", value = "起始页码", example="0", required = true ,dataType = "int",paramType = "query"),
  72. @ApiImplicitParam(name = "pageSize", value = "每页条数", example="10", required = true ,dataType = "int",paramType = "query")
  73. })
  74. public AjaxResult getUserList (
  75. @RequestParam(defaultValue = "groupid") String groupid,
  76. @RequestParam(defaultValue = "pageStart") int pageStart,
  77. @RequestParam(defaultValue = "pageSize") int pageSize) throws Exception
  78. {
  79. return AjaxResult.success(m_FaceLibLocal.getUserList(groupid, pageStart, pageSize));
  80. }
  81. @ApiOperation(value="删除用户",notes="删除用户")
  82. @GetMapping(value = "/removeUser")
  83. @ApiImplicitParams({
  84. @ApiImplicitParam(name = "userid", value = "用户ID", required = true ,dataType = "string",paramType = "query"),
  85. @ApiImplicitParam(name = "groupid", value = "组ID", required = true ,dataType = "string",paramType = "query")
  86. })
  87. public AjaxResult removeUser (
  88. @RequestParam(defaultValue = "userid") String userid,
  89. @RequestParam(defaultValue = "groupid") String groupid ) throws Exception
  90. {
  91. return AjaxResult.success(m_FaceLibLocal.removeUser(userid, groupid));
  92. }
  93. @ApiOperation(value="获取用户详情",notes="获取用户详情")
  94. @GetMapping(value = "/getUser")
  95. @ApiImplicitParams({
  96. @ApiImplicitParam(name = "userid", value = "用户ID", required = true ,dataType = "string",paramType = "query"),
  97. @ApiImplicitParam(name = "groupid", value = "组ID", required = true ,dataType = "string",paramType = "query")
  98. })
  99. public AjaxResult getUser (
  100. @RequestParam(defaultValue = "userid") String userid,
  101. @RequestParam(defaultValue = "groupid") String groupid) throws Exception
  102. {
  103. return AjaxResult.success(m_FaceLibLocal.getUser(userid, groupid));
  104. }
  105. @ApiOperation(value="获取人脸数量",notes="获取人脸数量")
  106. @GetMapping(value = "/getDbFaceCount")
  107. @ApiImplicitParams({
  108. @ApiImplicitParam(name = "groupid", value = "组ID", required = true ,dataType = "string",paramType = "query")
  109. })
  110. public AjaxResult getDbFaceCount (@RequestParam(defaultValue = "groupid") String groupid) throws Exception
  111. {
  112. return AjaxResult.success(m_FaceLibLocal.getDbFaceCount(groupid));
  113. }
  114. @ApiOperation(value="用户入组",notes="用户入组")
  115. @PostMapping(value = "/addUser")
  116. public AjaxResult addUser (@RequestBody UserFace face) throws Exception
  117. {
  118. return AjaxResult.success(m_FaceLibLocal.addUser(face));
  119. }
  120. @ApiOperation(value="用户更新",notes="用户更新")
  121. @PostMapping(value = "/updateUser")
  122. public AjaxResult updateUser (@RequestBody UserFace face) throws Exception
  123. {
  124. return AjaxResult.success(m_FaceLibLocal.updateUser(face));
  125. }
  126. @ApiOperation(value="上传图像", notes="上传图像")
  127. @RequestMapping(value="/uploadImage",method = RequestMethod.POST)
  128. @ResponseBody
  129. public Map<String,Object> uploadImg (@RequestParam(value="filename", required=false) MultipartFile file) throws Exception
  130. {
  131. Map<String,Object> map = new HashMap<String,Object>();
  132. if (file.isEmpty()) {
  133. map.put( "status", 0);
  134. map.put( "message", "上传失败,请选择文件");
  135. return map;
  136. }
  137. try {
  138. // String fileName = file.getOriginalFilename();
  139. String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf( "."));
  140. String fileName = UUID.randomUUID() + fileSuffix;
  141. SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy/MM/dd");
  142. String currentDate = dateFormat.format( new Date() );
  143. String filePath = upload_path + "/" + currentDate + "/";
  144. if(FileUtil.createDir(filePath))
  145. {
  146. filePath += fileName;
  147. File dest = new File(filePath);
  148. file.transferTo(dest);
  149. map.put( "status", 200);
  150. map.put( "message", "上传成功");
  151. map.put( "data", filePath);
  152. } else {
  153. map.put( "status", 5001);
  154. map.put( "message", "上传失败");
  155. map.put( "data", "创建文件夹失败");
  156. }
  157. } catch(Exception e) {
  158. map.put( "status", 5002);
  159. map.put( "message", "上传失败");
  160. map.put( "data", e.getMessage());
  161. }
  162. return map;
  163. }
  164. }

  
  1. package com.ai.local;
  2. import org.opencv.core.Core;
  3. import org.opencv.core.Mat;
  4. import org.opencv.core.MatOfByte;
  5. import org.opencv.imgcodecs.Imgcodecs;
  6. import org.springframework.stereotype.Component;
  7. import com.ai.local.entity.UserFace;
  8. import com.jni.face.Face;
  9. import com.util.ImageTools;
  10. @Component
  11. public class FaceLibLocal {
  12. /** 获取组列表 */
  13. public String getGroupList (int pageStart, int pageSize) throws Exception {
  14. return Face.getGroupList(pageStart, pageSize);
  15. }
  16. /** 添加组 */
  17. public String addGroup (String groupId) throws Exception{
  18. return Face.groupAdd(groupId);
  19. }
  20. /** 删除组 */
  21. public String removeGroup (String groupId) throws Exception{
  22. return Face.groupDelete(groupId);
  23. }
  24. /** 获取某组的用户列表 */
  25. public String getUserList (String groupId, int pageStart, int pageSize) throws Exception{
  26. return Face.getUserList(groupId, pageStart, pageSize);
  27. }
  28. /** 用户入组 */
  29. public String addUser (UserFace uf) throws Exception{
  30. byte[] bytes = ImageTools.loadNetImage(uf.getImage());
  31. MatOfByte mb = new MatOfByte(bytes);
  32. Mat mat = Imgcodecs.imdecode(mb, - 1);
  33. // Imgcodecs.imwrite("jerry.png", mat);
  34. long matAddr = mat.getNativeObjAddr();
  35. String res = Face.userAddByMat(matAddr, uf.getUserId(), uf.getGroupId(), uf.getUserInfo());
  36. Face.loadDbFace();
  37. return res;
  38. }
  39. /** 用户删除 */
  40. public String removeUser (String userId, String groupId) throws Exception{
  41. String res = Face.userDelete(userId, groupId);
  42. Face.loadDbFace();
  43. return res;
  44. }
  45. /** 用户更新 */
  46. public String updateUser (UserFace uf) throws Exception{
  47. byte[] bytes = ImageTools.loadNetImage(uf.getImage());
  48. MatOfByte mb = new MatOfByte(bytes);
  49. Mat mat = Imgcodecs.imdecode(mb, - 1);
  50. // Imgcodecs.imwrite("jerry.png", mat);
  51. long matAddr = mat.getNativeObjAddr();
  52. String res = Face.userUpdate(matAddr, uf.getUserId(), uf.getGroupId(), uf.getUserInfo());
  53. Face.loadDbFace();
  54. return res;
  55. }
  56. /** 获取用户详情 */
  57. public String getUser (String userId, String groupId) throws Exception{
  58. return Face.getUserInfo(userId, groupId);
  59. }
  60. /** 获取人脸数量 */
  61. public int getDbFaceCount (String groupId) throws Exception{
  62. return Face.dbFaceCount(groupId);
  63. }
  64. }

(4)对象实体


  
  1. package com.ai.local.entity;
  2. import com.jni.struct.Attribute;
  3. import com.jni.struct.FeatureInfo;
  4. import io.swagger.annotations.ApiModel;
  5. @ApiModel(value = "FaceAttribute", description = "人脸识别结果")
  6. public class FaceAttribute extends FeatureInfo {
  7. // 人脸属性
  8. Attribute[] attribute;
  9. // 库搜索结果
  10. String identify;
  11. // 口罩
  12. float wearMask;
  13. public FaceAttribute () {
  14. }
  15. public FaceAttribute (FeatureInfo featureInfo) {
  16. this.box = featureInfo.box;
  17. this.feature = featureInfo.feature;
  18. }
  19. public Attribute[] getAttribute() {
  20. return attribute;
  21. }
  22. public void setAttribute (Attribute[] attribute) {
  23. this.attribute = attribute;
  24. }
  25. public String getIdentify () {
  26. return identify;
  27. }
  28. public void setIdentify (String identify) {
  29. this.identify = identify;
  30. }
  31. public float getWearMask () {
  32. return wearMask;
  33. }
  34. public void setWearMask (float wearMask) {
  35. this.wearMask = wearMask;
  36. }
  37. }

  
  1. package com.ai.local.entity;
  2. import io.swagger.annotations.ApiModel;
  3. @ApiModel(value = "UserFace", description = "人脸库对象")
  4. public class UserFace {
  5. // 人脸图像
  6. private String image;
  7. // 用户id
  8. private String userId;
  9. // 组id
  10. private String groupId;
  11. // 其它信息
  12. private String userInfo;
  13. public String getImage () {
  14. return image;
  15. }
  16. public void setImage (String image) {
  17. this.image = image;
  18. }
  19. public String getUserId () {
  20. return userId;
  21. }
  22. public void setUserId (String userId) {
  23. this.userId = userId;
  24. }
  25. public String getGroupId () {
  26. return groupId;
  27. }
  28. public void setGroupId (String groupId) {
  29. this.groupId = groupId;
  30. }
  31. public String getUserInfo () {
  32. return userInfo;
  33. }
  34. public void setUserInfo (String userInfo) {
  35. this.userInfo = userInfo;
  36. }
  37. }

(5)摄像头切图识别


  
  1. package com.task;
  2. import java.io.IOException;
  3. import java.time.LocalDateTime;
  4. import java.time.ZoneOffset;
  5. import java.util.ArrayList;
  6. import java.util.HashMap;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.UUID;
  10. import org.opencv.core.Mat;
  11. import org.opencv.core.Size;
  12. import org.opencv.imgcodecs.Imgcodecs;
  13. import org.opencv.imgproc.Imgproc;
  14. import org.opencv.videoio.VideoCapture;
  15. import org.apache.http.io.EofSensor;
  16. import org.json.JSONObject;
  17. import org.slf4j.Logger;
  18. import org.slf4j.LoggerFactory;
  19. import org.springframework.beans.factory.annotation.Autowired;
  20. import org.springframework.beans.factory.annotation.Value;
  21. import org.springframework.scheduling.annotation.EnableAsync;
  22. import org.springframework.stereotype.Component;
  23. import com.ai.local.entity.FaceAttribute;
  24. import com.jni.face.Face;
  25. import com.jni.face.FaceDraw;
  26. import com.jni.struct.FeatureInfo;
  27. import com.util.GsonUtils;
  28. import com.util.HttpUtil;
  29. /**
  30. *@author created by Jerry
  31. *@date 2022年11月15日---上午9:14:56
  32. *@problem
  33. *@answer
  34. *@action
  35. */
  36. @Component
  37. @EnableAsync
  38. public class CamersLocalTask implements Runnable{
  39. private Logger m_log = LoggerFactory.getLogger(CamersLocalTask.class);
  40. @Value("${rtspURL}")
  41. String m_rtspURL;
  42. @Value("${rtspImage}")
  43. String m_rtspImage;
  44. @Value("${rtspImage_down}")
  45. String m_rtspImage_down;
  46. @Value("${samplingRate}")
  47. Long m_samplingRate;
  48. @Value("${sendURL}")
  49. String m_sendURL;
  50. @Autowired
  51. HttpUtil m_HttpUtil;
  52. @Override
  53. public void run () {
  54. try {
  55. this.screenshot_ex();
  56. } catch (java.lang.Exception e) {
  57. e.printStackTrace();
  58. }
  59. }
  60. /** 摄像头截图 */
  61. public void screenshot_ex () throws IOException {
  62. // 内存不能实时释放,尽量不new
  63. VideoCapture capture = new VideoCapture();
  64. capture.open(m_rtspURL);
  65. capture.set( 3, 960);
  66. capture.set( 4, 540);
  67. if (!capture.isOpened()) {
  68. m_log.error( "ERROR:could not open camera {}", m_rtspURL);
  69. return;
  70. }
  71. // type 0: 表示rgb 人脸检测 1:表示nir人脸检测
  72. int type = 0;
  73. Mat frame = new Mat();
  74. int index = 0;
  75. while ( true) {
  76. boolean have = capture.read(frame);
  77. if (!have) {
  78. m_log.error( "切图失败");
  79. capture.release();
  80. capture.open(m_rtspURL);
  81. continue;
  82. }
  83. // 切一下 resize(原矩阵,新矩阵,宽,高)
  84. Imgproc.resize(frame, frame, new Size( 960, 540));
  85. // 截一下 submat(起始行,截止行,起始列,截止列)
  86. // frame = frame.submat(20, 540 - 88, 96, 960 - 96);
  87. if(index++ < m_samplingRate)
  88. {
  89. continue;
  90. }
  91. index = 0;
  92. if (!frame.empty()) {
  93. long matAddr = frame.getNativeObjAddr();
  94. // 获取特征
  95. FeatureInfo[] featureInfo = Face.faceFeature(matAddr, type);
  96. if (featureInfo == null || featureInfo.length <= 0) {
  97. // m_log.info("无人脸");
  98. continue;
  99. }
  100. List<FaceAttribute> eatureInfoList = new ArrayList<>();
  101. for ( int i = 0; i < featureInfo.length; i++) {
  102. FeatureInfo fi = featureInfo[i];
  103. FaceAttribute faceAttribute = new FaceAttribute(fi);
  104. // 抠图
  105. Mat mat_sub = new Mat();
  106. long outAddr = mat_sub.getNativeObjAddr();
  107. Face.faceCrop(matAddr, outAddr);
  108. // 属性
  109. faceAttribute.setAttribute(Face.faceAttr(outAddr));
  110. // 口罩
  111. faceAttribute.setWearMask(Face.faceMouthMask(outAddr)[ 0]);
  112. // 搜索
  113. faceAttribute.setIdentify(Face.identifyWithAll(fi.feature, type).replaceAll( "\\n|\\t", ""));
  114. // 绘制
  115. FaceDraw.drawRects(frame, fi.box);
  116. eatureInfoList.add(faceAttribute);
  117. mat_sub = null;
  118. }
  119. // 保存
  120. String fname = UUID.randomUUID().toString() + ".jpg";
  121. Imgcodecs.imwrite(m_rtspImage + fname, frame);
  122. // 发送
  123. Long timestamp = LocalDateTime.now().toInstant(ZoneOffset.of( "+8")).toEpochMilli()/ 1000;
  124. JSONObject jo = new JSONObject();
  125. jo.put( "error_code", 0);
  126. jo.put( "img_src", m_rtspImage_down + fname);
  127. String str = GsonUtils.toJson(eatureInfoList);
  128. jo.put( "face_list", str);
  129. jo.put( "log_id", timestamp);
  130. jo.put( "timestamp", timestamp);
  131. Map<String, Object> map = new HashMap<>();
  132. map.put( "JsonData", GsonUtils.toJson(jo));
  133. map.put( "UseState", 0);
  134. map.put( "CreateDate", LocalDateTime.now().toString());
  135. String param = GsonUtils.toJson(map);
  136. try {
  137. m_HttpUtil.postAsync(m_sendURL, param);
  138. m_log.info( "INFO::向{}推发送数据成功{}",m_sendURL, param);
  139. } catch (java.lang.Exception e) {
  140. m_log.error( "ERROR::向{}推送数据失败 ",m_sendURL);
  141. }
  142. eatureInfoList = null;
  143. jo = null;
  144. map = null;
  145. System.gc();
  146. }
  147. }
  148. }
  149. }

(6)清理临时存储


  
  1. package com.task;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.nio.file.Files;
  5. import java.nio.file.Path;
  6. import java.nio.file.Paths;
  7. import java.nio.file.attribute.BasicFileAttributes;
  8. import java.nio.file.attribute.FileTime;
  9. import java.time.LocalDateTime;
  10. import java.time.ZoneOffset;
  11. import java.util.ArrayList;
  12. import java.util.List;
  13. import org.slf4j.Logger;
  14. import org.slf4j.LoggerFactory;
  15. import org.springframework.beans.factory.annotation.Value;
  16. import org.springframework.scheduling.annotation.EnableAsync;
  17. import org.springframework.stereotype.Component;
  18. /**
  19. *@author created by Jerry
  20. *@date 2022年11月15日---上午9:14:56
  21. *@problem
  22. *@answer
  23. *@action
  24. */
  25. @Component
  26. @EnableAsync
  27. public class ClearFilesTask implements Runnable{
  28. Logger m_log = LoggerFactory.getLogger(ClearFilesTask.class);
  29. @Value("${cacheTime}")
  30. Long m_cacheTime;
  31. @Value("${rtspImage}")
  32. String m_rtspImage;
  33. @Override
  34. public void run () {
  35. while ( true) {
  36. try {
  37. File file = new File(m_rtspImage);
  38. List<File> objects = new ArrayList<File>();
  39. getFilesList(file, objects);
  40. Thread.sleep( 1000L * 300);
  41. } catch (IOException | InterruptedException e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. }
  46. private void getFilesList (File file, List<File> temp) throws IOException{
  47. File[] listFiles = file.listFiles();
  48. if(listFiles == null) {
  49. return;
  50. }
  51. for (File file2 : listFiles) {
  52. if (file2.isDirectory()) {
  53. getFilesList(file2, temp);
  54. } else {
  55. if(file2.getAbsolutePath().contains( ".jpg")){
  56. Path path = Paths.get(file2.getAbsolutePath());
  57. BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
  58. FileTime fileTime = attrs.creationTime();
  59. if(LocalDateTime.now().toEpochSecond(ZoneOffset.UTC) - 28800 - fileTime.toMillis()/ 1000 > m_cacheTime) {
  60. file2.delete();
  61. }
  62. }
  63. }
  64. }
  65. }
  66. }


转载:https://blog.csdn.net/zj850324/article/details/128422431
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场