百度离线人脸识别SDK

news2024/11/24 5:48:12

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();
		    	   }
		       }
		    }
		}
	}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/116732.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Harmony/OpenHarmony应用开发-转场动画页面间转场

在全局pageTransition方法内配置页面入场和页面退场时的自定义转场动效。 说明&#xff1a;从API Version 7开始支持。开发语言ets. 名称 参数 参数描述 PageTransitionEnter { type: RouteType, duration: number, curve: Curve | string, delay: number } 设置当前页面…

1998-2014年企业绿色发展数据库

1998-2014年工业企业的排放排污和环境治理等信息数据 1、时间&#xff1a;1998-2014年 2、数据来源&#xff1a;原环保部。 3、统计字段&#xff1a;主要有企业基本信息、生产信息、水环境、大气环境&#xff0c;内容涵盖了资源利用类指标&#xff08;工业用水量、煤炭消费量…

YGG 与 Thirdverse 达成合作,将《足球小将》IP 带入 Web3

YGG 与 Thirdverse 建立了合作关系&#xff0c;Thirdverse 是一家专注于多人 VR 和 Web3 游戏的游戏工作室&#xff0c;在日本和美国分别设有办事处。 YGG 通过购买未来股权的简单协议&#xff08;SAFE&#xff09;参与了 Thirdverse 近期的 1500 万美元融资。这种合作关系将使…

FastAPI从入门到实战(16)——依赖项

依赖注入是耳熟能详的一个词了&#xff0c;听起来很复杂&#xff0c;实际上并没那么复杂&#xff0c;正常的访问需要接受各种参数来构造一个对象&#xff0c;依赖注入就变成了只接收一个实例化对象&#xff0c;主要用于共享业务逻辑、共享数据库连接、实现安全、验证、权限等相…

原油投资怎么样赚钱?原油投资赚钱技巧有哪些?

以前没有交易过原油的投资者&#xff0c;看到其他投资者从中获得了较好的盈利&#xff0c;也想通过原油投资来赚钱。那么原油投资到底能不能赚钱&#xff0c;是很多新手投资者比较想了解的问题。其实原油投资想盈利并不能全部依靠运气&#xff0c;只有掌握了原油投资赚钱技巧&a…

【Java基础】Java日志—什么是日志级别?如何配置数据源到不同的位置?配置文件内容都是什么含义?

目录 一、log4j1详情&#xff1a;记录器和日志级别 二、 log4j1详情&#xff1a;输出源【输出到不同的位置】 1、ConsoleAppender【将日志输出到控制台】 2、FileAppender【将日志输出到文件】 3、DailyRollingFileAppender【每日输出到一个新文件】 4、JDBCAppender【输…

FineReport开源报表系统-JS实现切换Tab块时进行数据联动

1. 概述 1.1 预期效果 在决策报表中&#xff0c;希望 Tab 块轮播切换时&#xff0c;可实现与报表块的数据联动。如下图所示&#xff1a; 1.2 实现思路 通过 JS 获取每个 Tab 块的轮播标题&#xff0c;转换为参数值&#xff0c;再通过控件进行界面传参&#xff0c;实现联动效果…

程序员工作五年后一般会怎样?

最近看到一些吐血言论“一个程序员工作5年后还没成为大牛&#xff0c;是不是该考虑别的路子了&#xff1f;”还有“程序员入行五年&#xff0c;有可能攒够80吗&#xff1f;”不是&#xff0c;程序员工作五年&#xff0c;是戳中了谁的痛点吗&#xff1f;&#xff1f;大家对五年经…

128页4万字某智慧能源集团数字化管理平台项目建议书

【版权声明】本资料来源网络&#xff0c;仅用于行业知识分享&#xff0c;供个人学习参考&#xff0c;请勿商用。【侵删致歉】如有侵权请联系小编&#xff0c;将在收到信息后第一时间进行删除&#xff01;完整资料领取见文末&#xff0c;部分资料内容&#xff1a; 方案设计 在当…

公司新来的软件测试工程师接私活被抓了,难怪他天天加班到凌晨

昨天和我一起进公司的测试部门同事上班接私活被老板抓了&#xff0c;这人才来不到两个月&#xff0c;每天加班到凌晨。刚开始还以为他是个卷王&#xff0c;没想到此人上班时间接单&#xff0c;用加班时间来完成公司需求&#xff0c;造成努力的假象。被老板在办公室骂了俩小时&a…

v$asm_disk中free_mb低于300m导致加盘报ora-15041

背景&#xff1a; 某项目扩容加盘到磁盘组中报磁盘组空间耗尽的错误&#xff0c;如下 明明是加盘&#xff0c;却报空间不足的错误&#xff0c;令人费解 报错的磁盘组为normal冗余&#xff0c;且Usable_file_MB为负&#xff0c;且Free_MB剩余很少或为0 问题排查&#xff1a; …

MS 训练笔记【2】:nnFormer

文章目录前言1. 安装2. 训练与测试2.1. 数据处理2.1.1. 整理数据路径2.1.2. 设置 nnFormer 读取文件的路径2.1.3. 数据集预处理2.2. 训练2.2.1. 训练代码2.2.2. 可能出现的问题及解决办法2.3. 预测总结前言 本文主要记载 nnFormer 从安装到训练再到推理的过程。nnFormer 的环境…

invokeBeanFactoryPostProcessors的理解

invokeBeanFactoryPostProcessors的理解 Spring中有两个非常重要的扩展点&#xff1a; BeanFactoryPostProcessorBeanPostProcessor 其中第一个是可以对BeanDefinition注册时进行扩展&#xff0c;而第二个是对spring中IOC容器中的对象进行实例化的时候进行扩展。 今天主要谈一…

【安全漏洞】水平权限漏洞和垂直权限漏洞

前言 权限校验非常重要。如果不对水平、垂直权限做校验&#xff0c;就会发生泄漏用户数据的事故&#xff0c;造成P0故障。 一、水平权限漏洞 1、水平权限漏洞基本概念 什么是水平权限漏洞呢&#xff1f; 简单来说&#xff0c;水平权限漏洞是用户CURD了本不属于他的资源。以上图…

复活天若OCR的谷歌翻译接口

文章目录1. 资源2. 效果3. 前言4. 网络相关4.1. 网络判断4.2. 网络设置5. 修改5.1. 代码修改原理5.2. 代码修改1. 资源 这里直接放出来我已经修改编译好的天若OCR&#xff0c;开箱即用&#xff1a;https://www.lanzoui.com/ifT8t0jfv1gd 访问码&#xff1a;24647 不过需要说明…

性能优化系列之如何为不同格式的图片选择合适的应用场景?

文章の目录一、JPEG&#xff08;Joint Photographic Experts Group&#xff09;1、介绍2、不适合情形3、非常适合的情形二、PNG&#xff08;Portable Network Graphics&#xff09;1、介绍2、不适合的情形3、非常适合的情形三、GIF&#xff08;Graphics Interchange Format&…

【nowcoder】笔试强训Day9

目录 一、选择题 二、编程题 2.1另类加法 2.2走方格的方案数 一、选择题 1.下面程序的输出是:() String x"fmn"; x.toUpperCase(); String yx.replace(f,F); yy"wxy"; System.out.println(y); A FmNwxy B fmnwxy C wxyfmn D Fmnwxy String x “…

决胜「年货时代」:一场关于零食的品质突围

“都说冰糖葫芦儿酸&#xff0c;酸里面它裹着甜&#xff1b;都说冰糖葫芦儿甜&#xff0c;可甜里面它透着那酸。” 1995年春节&#xff0c;伴随着《冰糖葫芦》唱响大街小巷&#xff0c;小贩骑着自行车&#xff0c;后车座的草靶子上插满冰糖葫芦&#xff0c;或摆在集市上&#…

大数据系列——什么是hive?hive用来干什么的?hive常见问题是啥?

目录 一、什么是hive 二、为什么要使用Hive 三、Hive与Hadoop的关系 四、Hive与HDFS的关系 五、Hive与传统数据库区别 六、Hive中的数据存储是怎样的 七、对hive进行增删改查 八、排序逻辑 九、hive不支持update数据的解决方案 十、Hive中支持的分区类型有两种 十…

Linux部署前端Vue项目

Linux部署前端Vue项目 1 部署到tomcat上 1.1 部署Vue项目 打包项目 在命令行终端&#xff0c;输入命令&#xff0c;打包项目&#xff1a; npm run build将生成的dist文件夹下的所有内容复制到tomcat的webapps下 "推荐":在webapps下新建一个文件夹&#xff0c;例…