百度离线人脸识别SDK

17 篇文章 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

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.3.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.ai</groupId>
	<artifactId>risun-ai</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>risun-ai</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	
	<repositories>
        <repository>
            <id>huaweicloud</id>
            <url>https://repo.huaweicloud.com/repository/maven/</url>
            <!--<url>http://maven.aliyun.com/nexus/content/groups/public/</url>-->
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
                <updatePolicy>always</updatePolicy>
                <checksumPolicy>fail</checksumPolicy>
            </snapshots>
        </repository>
    </repositories>
    
	<dependencies>
	    <dependency>
		    <groupId>javax.servlet</groupId>
		    <artifactId>javax.servlet-api</artifactId>
		    <scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		
		<dependency>
		   <groupId>io.springfox</groupId>
		   <artifactId>springfox-swagger2</artifactId>
		   <version>2.9.2</version>
		</dependency>
		<dependency>
		   <groupId>io.springfox</groupId>
		   <artifactId>springfox-swagger-ui</artifactId>
		   <version>2.9.2</version>
		</dependency>
        
		<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
		<dependency>
		    <groupId>org.projectlombok</groupId>
		    <artifactId>lombok</artifactId>
		    <version>1.18.22</version>
		    <scope>provided</scope>
		</dependency>
		
		<dependency>
		    <groupId>com.baidu.aip</groupId>
		    <artifactId>java-sdk</artifactId>
		    <version>4.15.1</version>
		</dependency>
		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.8.3</version>
		</dependency>
		<dependency>
		  <groupId>com.google.code.gson</groupId>
		  <artifactId>gson</artifactId>
		  <version>2.8.5</version>
		</dependency>
		
		 <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
        
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

(2)启动

package com;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.ai.local.FaceLocalFactory;
import com.jni.face.Face;

@SpringBootApplication
public class RisunAiApplication {
	public static void main(String[] args) {
		//FaceLocalFactory.sdkInit();
		//Face.loadDbFace();
		SpringApplication.run(RisunAiApplication.class, args);
		System.out.println(":::主线程启动");
	}

}

 

package com;
/**
*@author    created by Jerry
*@date  2022年12月23日---下午4:51:37
*@problem
*@answer
*@action
*/

import com.jni.face.Face;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class SdkInit implements ApplicationRunner{
    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception{
        /*  sdk初始化 */
        Face api = new Face();
        // model_path为模型文件夹路径,即models文件夹(里面存的是人脸识别的模型文件)
        // 传空为采用默认路径,若想定置化路径,请填写全局路径如:d:\\face (models模型文件夹目录放置后为d:\\face\\models)
        // 若模型文件夹采用定置化路径,则激活文件(license.ini, license.key)也可采用定制化路径放置到该目录如d:\\face\\license
        // 亦可在激活文件默认生成的路径
        String modelPath ="";
        int res = api.sdkInit(modelPath);
        if (res != 0) {
            System.out.printf("sdk init fail and error =%d\n", res);
        }
        
        Face.loadDbFace();

        // 获取设备指纹
        String deviceId = Face.getDeviceId();
        System.out.printf("device id:" + deviceId);
        // 获取版本号
        String ver = Face.sdkVersion();
        System.out.printf("sdk version:" + ver);
    }
}

 

package com;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import com.task.ClearFilesTask;

/**
 * 
 * @author jerry
 * 清理垃圾
 */
@Component
public class Branch_02 implements CommandLineRunner {
	Logger m_log = LoggerFactory.getLogger(getClass());
	@Value("${cacheTime}")
	Long m_cacheTime;
	
	@Autowired
	ClearFilesTask m_clearFilesTask;
	
	@Override
	public void run(String... arg0) throws Exception {
		if (m_cacheTime <= 0) {
			return;
		}
		this.m_log.info(":::清理线程启动");
		Thread thread = new Thread(this.m_clearFilesTask);
		thread.start();
	}

}

 

package com;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.ai.local.FaceLocalFactory;
import com.jni.face.Face;
import com.task.CamersLocalTask;

/**
 * 
 * @author jerry
 * 截图识别 本地离线
 */
@Component
public class Branch_04 implements CommandLineRunner {
	Logger m_log = LoggerFactory.getLogger(getClass());
	
	@Value("${rtspLocalScreenshot}")
	String rtspLocalScreenshot;
	
	@Autowired
	CamersLocalTask m_camersLocalTask;
	
	@Override
	public void run(String... arg0) throws Exception {
		if (this.rtspLocalScreenshot != null && this.rtspLocalScreenshot.equalsIgnoreCase("false")) {
			return;
		}
		this.m_log.info(":::本地离线截图识别线程启动");
		Thread thread = new Thread(this.m_camersLocalTask);
		thread.start();
	}

}

(3)人脸库管理

package com.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ai.local.FaceLibLocal;
import com.ai.local.entity.UserFace;
import com.util.AjaxResult;
import com.util.FileUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;

@Api(value = "FaceLibController", description = "本地人脸库管理接口")
@Controller
@RequestMapping(value = "/facelib")
@ResponseBody
public class FaceLibController extends BasicController 
{	
	@Autowired
	FaceLibLocal m_FaceLibLocal;
	
	@Value("${upload_path}")
    String upload_path;

	@ApiOperation(value="获取组列表",notes="获取组列表")
	@GetMapping(value = "/getGroupList")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "pageStart", value = "起始页码", example="0", required = true ,dataType = "int",paramType = "query"),
		@ApiImplicitParam(name = "pageSize", value = "每页条数", example="10", required = true ,dataType = "int",paramType = "query")
	})
    public AjaxResult getGroupList(@RequestParam(defaultValue = "pageStart") int pageStart, @RequestParam(defaultValue = "pageSize") int pageSize)  throws Exception
    {
        return AjaxResult.success(m_FaceLibLocal.getGroupList(pageStart, pageSize));
    }
	
	@ApiOperation(value="添加组",notes="添加组")
	@GetMapping(value = "/addGroup")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "groupid", value = "组ID", required = true ,dataType = "string",paramType = "query")
	})
	public AjaxResult addGroup(@RequestParam(defaultValue = "groupid") String groupid)  throws Exception
    {
        return AjaxResult.success(m_FaceLibLocal.addGroup(groupid));
    }
	
	@ApiOperation(value="删除组",notes="删除组")
	@GetMapping(value = "/removeGroup")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "groupid", value = "组ID", required = true ,dataType = "string",paramType = "query")
	})
	public AjaxResult removeGroup(@RequestParam(defaultValue = "groupid") String groupid)  throws Exception
    {
        return AjaxResult.success(m_FaceLibLocal.removeGroup(groupid));
    }
	
	@ApiOperation(value="获取某组的用户列表",notes="获取某组的用户列表")
	@GetMapping(value = "/getUserList")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "groupid", value = "组ID", required = true ,dataType = "string",paramType = "query"),
		@ApiImplicitParam(name = "pageStart", value = "起始页码", example="0", required = true ,dataType = "int",paramType = "query"),
		@ApiImplicitParam(name = "pageSize", value = "每页条数", example="10", required = true ,dataType = "int",paramType = "query")
	})
	public AjaxResult getUserList(
			@RequestParam(defaultValue = "groupid") String groupid,
			@RequestParam(defaultValue = "pageStart") int pageStart, 
			@RequestParam(defaultValue = "pageSize") int pageSize)  throws Exception
    {
        return AjaxResult.success(m_FaceLibLocal.getUserList(groupid, pageStart, pageSize));
    }
	
	@ApiOperation(value="删除用户",notes="删除用户")
	@GetMapping(value = "/removeUser")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "userid", value = "用户ID", required = true ,dataType = "string",paramType = "query"),
		@ApiImplicitParam(name = "groupid", value = "组ID", required = true ,dataType = "string",paramType = "query")
	})
	public AjaxResult removeUser(
			@RequestParam(defaultValue = "userid") String userid,
			@RequestParam(defaultValue = "groupid") String groupid )  throws Exception
    {
        return AjaxResult.success(m_FaceLibLocal.removeUser(userid, groupid));
    }
	
	@ApiOperation(value="获取用户详情",notes="获取用户详情")
	@GetMapping(value = "/getUser")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "userid", value = "用户ID", required = true ,dataType = "string",paramType = "query"),
		@ApiImplicitParam(name = "groupid", value = "组ID", required = true ,dataType = "string",paramType = "query")
	})
	public AjaxResult getUser(
			@RequestParam(defaultValue = "userid") String userid,
			@RequestParam(defaultValue = "groupid") String groupid)  throws Exception
    {
        return AjaxResult.success(m_FaceLibLocal.getUser(userid, groupid));
    }
	
	@ApiOperation(value="获取人脸数量",notes="获取人脸数量")
	@GetMapping(value = "/getDbFaceCount")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "groupid", value = "组ID", required = true ,dataType = "string",paramType = "query")
	})
	public AjaxResult getDbFaceCount(@RequestParam(defaultValue = "groupid") String groupid)  throws Exception
    {
        return AjaxResult.success(m_FaceLibLocal.getDbFaceCount(groupid));
    }
	
	@ApiOperation(value="用户入组",notes="用户入组")
	@PostMapping(value = "/addUser")
    public AjaxResult addUser(@RequestBody UserFace face)  throws Exception
    {
		return AjaxResult.success(m_FaceLibLocal.addUser(face));
    }
	
	@ApiOperation(value="用户更新",notes="用户更新")
	@PostMapping(value = "/updateUser")
    public AjaxResult updateUser(@RequestBody UserFace face) throws Exception
    {		
		return AjaxResult.success(m_FaceLibLocal.updateUser(face));
    }
	
	@ApiOperation(value="上传图像", notes="上传图像")
	@RequestMapping(value="/uploadImage",method = RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> uploadImg(@RequestParam(value="filename", required=false) MultipartFile file)  throws Exception
	{
		Map<String,Object> map = new HashMap<String,Object>();
		if (file.isEmpty()) {
			map.put("status", 0);
			map.put("message", "上传失败,请选择文件");
            return map;
        }
		
		try {
			// String fileName =  file.getOriginalFilename();
			String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			String fileName =  UUID.randomUUID() + fileSuffix;
	        
	        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
	        String currentDate =   dateFormat.format( new Date() );
	        String filePath = upload_path + "/" + currentDate + "/";
	        if(FileUtil.createDir(filePath)) 
	        {
	        	filePath += fileName;
	        	File dest = new File(filePath);
	        	file.transferTo(dest);
	        	
	        	map.put("status", 200);
				map.put("message", "上传成功");
				map.put("data", filePath);
	        }else {
	        	map.put("status", 5001);
				map.put("message", "上传失败");
				map.put("data", "创建文件夹失败");
	        }
	        
		}catch(Exception e) {
			map.put("status", 5002);
			map.put("message", "上传失败");
			map.put("data", e.getMessage());
		}
		return map;
	}

}
package com.ai.local;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;
import org.springframework.stereotype.Component;
import com.ai.local.entity.UserFace;
import com.jni.face.Face;
import com.util.ImageTools;

@Component
public class FaceLibLocal {
	/** 获取组列表 */
	public String getGroupList(int pageStart, int pageSize) throws Exception {
        return Face.getGroupList(pageStart, pageSize);
	}
	
	/** 添加组 */
	public String addGroup(String groupId)  throws Exception{
        return Face.groupAdd(groupId);
	}
	
	/** 删除组 */
	public String removeGroup(String groupId)  throws Exception{
        return Face.groupDelete(groupId);
	}
	
	/** 获取某组的用户列表 */
	public String getUserList(String groupId, int pageStart, int pageSize)  throws Exception{
        return Face.getUserList(groupId, pageStart, pageSize);
	}
		
	/** 用户入组 */
	public String addUser(UserFace uf)  throws Exception{
		byte[] bytes = ImageTools.loadNetImage(uf.getImage());
		MatOfByte mb = new MatOfByte(bytes);
		Mat mat = Imgcodecs.imdecode(mb, -1);
		// Imgcodecs.imwrite("jerry.png", mat); 
		long matAddr = mat.getNativeObjAddr();
		String res = Face.userAddByMat(matAddr, uf.getUserId(), uf.getGroupId(), uf.getUserInfo());
		Face.loadDbFace();
		return res;
	}
	
	/** 用户删除 */
	public String removeUser(String userId, String groupId)  throws Exception{
		String res = Face.userDelete(userId, groupId);
		Face.loadDbFace();
		return res;
	}
	
	/** 用户更新 */
	public String updateUser(UserFace uf)  throws Exception{
		byte[] bytes = ImageTools.loadNetImage(uf.getImage());
		MatOfByte mb = new MatOfByte(bytes);
		Mat mat = Imgcodecs.imdecode(mb, -1);
		// Imgcodecs.imwrite("jerry.png", mat); 
		long matAddr = mat.getNativeObjAddr();
		String res = Face.userUpdate(matAddr, uf.getUserId(), uf.getGroupId(), uf.getUserInfo());
		Face.loadDbFace();
		return res;
	}
	
	/** 获取用户详情 */
	public String getUser(String userId, String groupId)  throws Exception{
		return  Face.getUserInfo(userId, groupId);
	}

	/** 获取人脸数量 */
    public int getDbFaceCount(String groupId)  throws Exception{
        return Face.dbFaceCount(groupId);
    }
    
}

(4)对象实体

package com.ai.local.entity;

import com.jni.struct.Attribute;
import com.jni.struct.FeatureInfo;
import io.swagger.annotations.ApiModel;

@ApiModel(value = "FaceAttribute", description = "人脸识别结果")
public class FaceAttribute extends FeatureInfo {
	// 人脸属性
	Attribute[] attribute;
	// 库搜索结果
	String identify;
	// 口罩
	float wearMask;
	
	public FaceAttribute() {
		
	}
	
	public FaceAttribute(FeatureInfo featureInfo) {
		this.box = featureInfo.box;
		this.feature = featureInfo.feature;
	}
	
	public Attribute[] getAttribute() {
		return attribute;
	}
	public void setAttribute(Attribute[] attribute) {
		this.attribute = attribute;
	}
	public String getIdentify() {
		return identify;
	}
	public void setIdentify(String identify) {
		this.identify = identify;
	}

	public float getWearMask() {
		return wearMask;
	}

	public void setWearMask(float wearMask) {
		this.wearMask = wearMask;
	}
	
}
package com.ai.local.entity;

import io.swagger.annotations.ApiModel;

@ApiModel(value = "UserFace", description = "人脸库对象")
public class UserFace {
	// 人脸图像
	private String image;
    // 用户id
	private String userId;
    // 组id
	private String groupId;
    // 其它信息
	private String userInfo;
	
	public String getImage() {
		return image;
	}
	public void setImage(String image) {
		this.image = image;
	}
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	public String getGroupId() {
		return groupId;
	}
	public void setGroupId(String groupId) {
		this.groupId = groupId;
	}
	public String getUserInfo() {
		return userInfo;
	}
	public void setUserInfo(String userInfo) {
		this.userInfo = userInfo;
	}
}

(5)摄像头切图识别

package com.task;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.videoio.VideoCapture;
import org.apache.http.io.EofSensor;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import com.ai.local.entity.FaceAttribute;
import com.jni.face.Face;
import com.jni.face.FaceDraw;
import com.jni.struct.FeatureInfo;
import com.util.GsonUtils;
import com.util.HttpUtil;

/**
*@author    created by Jerry
*@date  2022年11月15日---上午9:14:56
*@problem
*@answer
*@action
*/
@Component
@EnableAsync
public class CamersLocalTask implements Runnable{
	private Logger m_log = LoggerFactory.getLogger(CamersLocalTask.class);

	@Value("${rtspURL}")
	String m_rtspURL;
	
	@Value("${rtspImage}")
	String m_rtspImage;
	
	@Value("${rtspImage_down}")
	String m_rtspImage_down;
	
	@Value("${samplingRate}")
	Long m_samplingRate;
	
	@Value("${sendURL}")
	String m_sendURL;
	
	@Autowired
	HttpUtil m_HttpUtil;
	
	@Override
	public void run() {
		try {
			this.screenshot_ex();
		} catch (java.lang.Exception e) {
			e.printStackTrace();
		}
	}
	
	/** 摄像头截图 */
	public void screenshot_ex() throws IOException {
		// 内存不能实时释放,尽量不new
	  	VideoCapture capture = new VideoCapture();
        capture.open(m_rtspURL);
        capture.set(3, 960);
	  	capture.set(4, 540);
        if (!capture.isOpened()) {
            m_log.error("ERROR:could not open camera {}", m_rtspURL);
            return;
        }
        // type 0: 表示rgb 人脸检测 1:表示nir人脸检测
        int type = 0;
        Mat frame = new Mat();
        int index = 0;
        while (true) {
        	boolean have = capture.read(frame);
        	if (!have) {
            	m_log.error("切图失败");
            	capture.release();
            	capture.open(m_rtspURL);
                continue;
            }
        	
        	// 切一下 resize(原矩阵,新矩阵,宽,高)
            Imgproc.resize(frame, frame, new Size(960,540));
            // 截一下 submat(起始行,截止行,起始列,截止列)
            // frame = frame.submat(20, 540 - 88, 96, 960 - 96);
        	
        	if(index++ < m_samplingRate)
			{
        		continue;
			}
            index = 0;
            
            if (!frame.empty()) {	                
                long matAddr = frame.getNativeObjAddr();
                // 获取特征
                FeatureInfo[] featureInfo = Face.faceFeature(matAddr, type);
                if (featureInfo == null || featureInfo.length <= 0) {
                	// m_log.info("无人脸");
                    continue;
                }
                List<FaceAttribute> eatureInfoList = new ArrayList<>();
                for (int i = 0; i < featureInfo.length; i++) {
                	FeatureInfo fi = featureInfo[i];
                	FaceAttribute faceAttribute = new FaceAttribute(fi);
                	// 抠图
                	Mat mat_sub = new Mat();
                    long outAddr = mat_sub.getNativeObjAddr();
                    Face.faceCrop(matAddr, outAddr);
                    // 属性
                    faceAttribute.setAttribute(Face.faceAttr(outAddr));
                    // 口罩
                    faceAttribute.setWearMask(Face.faceMouthMask(outAddr)[0]);
                	// 搜索
                	faceAttribute.setIdentify(Face.identifyWithAll(fi.feature, type).replaceAll("\\n|\\t",""));
                	// 绘制
	                FaceDraw.drawRects(frame, fi.box);
	                eatureInfoList.add(faceAttribute);
	                
	                mat_sub = null;
				}

                // 保存
				String fname = UUID.randomUUID().toString() + ".jpg";
                Imgcodecs.imwrite(m_rtspImage + fname, frame);
                
                // 发送
                Long timestamp = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli()/1000;
                JSONObject jo = new JSONObject();
                jo.put("error_code", 0);
                jo.put("img_src", m_rtspImage_down + fname);
                String str = GsonUtils.toJson(eatureInfoList);
                jo.put("face_list", str);
                jo.put("log_id", timestamp);
                jo.put("timestamp", timestamp);
                
                Map<String, Object> map = new HashMap<>();
		        map.put("JsonData", GsonUtils.toJson(jo));
		        map.put("UseState", 0);
		        map.put("CreateDate", LocalDateTime.now().toString());
		        String param = GsonUtils.toJson(map);
				
		        try {
		        	m_HttpUtil.postAsync(m_sendURL, param);
			        m_log.info("INFO::向{}推发送数据成功{}",m_sendURL, param);
				} catch (java.lang.Exception e) {
					m_log.error("ERROR::向{}推送数据失败 ",m_sendURL);
				}
		        
		        eatureInfoList = null;
		        jo = null;
		        map = null;
		        System.gc();
            }           
        }
	}

}

(6)清理临时存储

package com.task;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

/**
*@author    created by Jerry
*@date  2022年11月15日---上午9:14:56
*@problem
*@answer
*@action
*/
@Component
@EnableAsync
public class ClearFilesTask implements Runnable{
	Logger m_log = LoggerFactory.getLogger(ClearFilesTask.class);

	@Value("${cacheTime}")
	Long m_cacheTime;
	
	@Value("${rtspImage}")
	String m_rtspImage;
	
	@Override
	public void run() {
		while (true) {
			try {
				File file = new File(m_rtspImage);
				List<File> objects = new ArrayList<File>();
				getFilesList(file, objects);
				Thread.sleep(1000L * 300);
			} catch (IOException | InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void getFilesList(File file, List<File> temp) throws IOException{
		File[] listFiles = file.listFiles();
		if(listFiles == null) {
			return;
		}
		for (File file2 : listFiles) {
		    if (file2.isDirectory()) {
		        getFilesList(file2, temp);
		    } else {
		       if(file2.getAbsolutePath().contains(".jpg")){
		    	   Path path = Paths.get(file2.getAbsolutePath());
		    	   BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
		    	   FileTime fileTime = attrs.creationTime();
		    	   if(LocalDateTime.now().toEpochSecond(ZoneOffset.UTC)  - 28800 - fileTime.toMillis()/1000 > m_cacheTime) {
		    		   file2.delete();
		    	   }
		       }
		    }
		}
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

外码斯迪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值