Deep Java Library(三)人体检测demo摄像机抽帧推理绘制结果和围栏

1.主程序文件

package com.xxx.onnx;import ai.djl.Application;
import ai.djl.Device;
import ai.djl.MalformedModelException;
import ai.djl.inference.Predictor;
import ai.djl.modality.cv.BufferedImageFactory;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.output.DetectedObjects;
import ai.djl.modality.cv.translator.YoloV5Translator;
import ai.djl.repository.zoo.Criteria;
import ai.djl.repository.zoo.ModelNotFoundException;
import ai.djl.repository.zoo.ZooModel;
import ai.djl.training.util.ProgressBar;
import ai.djl.translate.TranslateException;
import ai.djl.translate.Translator;
import org.bytedeco.ffmpeg.global.avutil;
import org.bytedeco.javacv.Java2DFrameUtils;
import org.bytedeco.javacv.*;
import org.bytedeco.opencv.opencv_core.Mat;
import org.opencv.core.Core;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Arrays;public class Rtsp {/*** 原始RTSP流地址*/private static final String RTSP = "rtsp://admin:admin1234@192.168.66.150:554/cam/realmonitor?channel=4&subtype=1";/*** 模型路径*/private static final String path = "D:\\LIHAOWORK\\models\\yolov5-pt\\model\\person\\person.onnx";/*** 围栏多边形顶点*/private static final org.opencv.core.Point[] points = {new org.opencv.core.Point(0, 300),new org.opencv.core.Point(350, 340),new org.opencv.core.Point(400, 500),new org.opencv.core.Point(0, 720),};private static  Predictor<Image, DetectedObjects> predictor;private static  DetectedObjects result;private static float threshold = 0.2f;/*** 视频帧率*/private static int frameRate = 30;/*** 视频帧宽度*/private static int width = 640;/*** 视频帧高度*/private static int height = 640;/*** 初始化*/private static void init(){//初始化转换器Translator<Image, DetectedObjects> translator = YoloV5Translator.builder().optThreshold(threshold).optSynsetArtifactName("synset.txt").build();YoloV5RelativeTranslator myTranslator = new YoloV5RelativeTranslator(translator);try {//模型加载ZooModel<Image, DetectedObjects> model = Criteria.builder().optApplication(Application.CV.OBJECT_DETECTION).optDevice(Device.cpu()).optEngine("OnnxRuntime").setTypes(Image.class, DetectedObjects.class) // 设置输入输出.optTranslator(myTranslator).optModelPath(Paths.get(path)).optProgress(new ProgressBar()) // 进度条.build().loadModel();predictor = model.newPredictor();System.out.println("模型加载完成");System.loadLibrary(Core.NATIVE_LIBRARY_NAME);System.out.println("底层库加载完成");} catch (IOException e) {e.printStackTrace();} catch (ModelNotFoundException e) {e.printStackTrace();} catch (MalformedModelException e) {e.printStackTrace();}}public static void main(String[] args) {//开始抽帧System.out.println("开始抽帧");FFmpegFrameGrabber  grabber = null;try {grabber = FFmpegFrameGrabber.createDefault(RTSP);grabber.setOption("rtsp_transport", "tcp"); // 使用tcp的方式grabber.setOption("stimeout", "5000000");grabber.setPixelFormat(avutil.AV_PIX_FMT_RGB24);  // 像素格式grabber.setImageWidth(width);grabber.setImageHeight(height);grabber.setFrameRate(frameRate);grabber.start();//初始化模型System.out.println("初始化模型");init();//播放窗口System.out.println("播放窗口");CanvasFrame canvasFrame = new CanvasFrame("摄像机");canvasFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);canvasFrame.setAlwaysOnTop(true);//核心处理逻辑System.out.println("核心处理逻辑");int i = 0;//初始化计数器为0while (true) {//测试环境下无线循环Frame frame = grabber.grabFrame();//抽取一帧frame = processFrame(frame,i);//转换、推理、识别、绘制、转换canvasFrame.showImage(frame);//展示i++;//计数器累加if(i >= frameRate) i=0;//当计数器大于等于帧率时候重置为0}} catch (Exception e) {System.out.println(e);} finally {}}/*** 推理* @param frame* @param i* @return*/private static Frame processFrame(Frame frame,int i) {System.out.println("1(frame2Image)");Long start1 = System.currentTimeMillis();Image image =  frame2Image(frame);Long end1 = System.currentTimeMillis();System.out.println("frame2Image耗时:"+(end1-start1)+"ms");if(i%10==0){//5帧推理一帧try {System.out.println("2(推理)");Long start2 = System.currentTimeMillis();result = predictor.predict(image);Long end2 = System.currentTimeMillis();System.out.println("推理耗时:"+(end2-start2)+"ms");} catch (TranslateException e) {e.printStackTrace();}}System.out.println("3(结果)");System.out.println(result);System.out.println("4(绘制)");Long start3 = System.currentTimeMillis();image.drawBoundingBoxes(result);Long end3 = System.currentTimeMillis();System.out.println("绘制耗时:"+(end3-start3)+"ms");System.out.println("5(image2Frame)");Long start4 = System.currentTimeMillis();Mat mat = image2Mat(image);drawRect(mat,points);//绘制围栏Frame frameout = mat2Frame(mat);Long end4 = System.currentTimeMillis();System.out.println("image2Frame耗时:"+(end4-start4)+"ms");return frameout;}/*** frame2Image* @param frame* @return*/private static Image frame2Image(Frame frame){BufferedImage temp  = Java2DFrameUtils.toBufferedImage (frame);Image image = BufferedImageFactory.getInstance().fromImage(temp);return image;}/*** image2Frame* @param image* @return*/private static Frame image2Frame(Image image){BufferedImage temp  = (BufferedImage) image.getWrappedImage();Frame frame = Java2DFrameUtils.toFrame(temp);return frame;}/*** image2Mat* @param image* @return*/private static Mat image2Mat(Image image){BufferedImage temp  = (BufferedImage) image.getWrappedImage();Mat mat = Java2DFrameUtils.toMat(temp);return mat;}/*** mat2Frame* @param mat* @return*/private static Frame mat2Frame(Mat mat){Frame frame = Java2DFrameUtils.toFrame(mat);return frame;}/*** 模拟绘制电子围栏* @param mat* @param points*/private static void drawRect(Mat mat,org.opencv.core.Point[] points){OpenCVFrameConverter.ToMat converter1 = new OpenCVFrameConverter.ToMat();OpenCVFrameConverter.ToOrgOpenCvCoreMat converter2 = new OpenCVFrameConverter.ToOrgOpenCvCoreMat();org.opencv.core.Mat cvmat = converter2.convert(converter1.convert(mat));MatOfPoint ps = new MatOfPoint();ps.fromArray(points);//Scalar 颜色Scalar scalar = new Scalar(255,0,255);Imgproc.polylines(cvmat, Arrays.asList(ps), true, scalar, 5, Imgproc.LINE_8);}
}

2.转换器文件

package com.xxx.onnx;import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.output.BoundingBox;
import ai.djl.modality.cv.output.DetectedObjects;
import ai.djl.modality.cv.output.Rectangle;
import ai.djl.ndarray.NDList;
import ai.djl.translate.Batchifier;
import ai.djl.translate.Translator;
import ai.djl.translate.TranslatorContext;
import java.util.ArrayList;
import java.util.List;public class YoloV5RelativeTranslator implements Translator<Image, DetectedObjects> {private final Translator<Image, DetectedObjects> delegated;private final Integer width;private final Integer height;public YoloV5RelativeTranslator(Translator<Image, DetectedObjects> translator) {this.delegated = translator;this.width = 640;this.height = 640;}@Overridepublic DetectedObjects processOutput(TranslatorContext ctx, NDList list) throws Exception {DetectedObjects output = delegated.processOutput(ctx, list);List<String> classList = new ArrayList<>();List<Double> probList = new ArrayList<>();List<BoundingBox> rectList = new ArrayList<>();final List<DetectedObjects.DetectedObject> items = output.items();items.forEach(item -> {classList.add(item.getClassName());probList.add(item.getProbability());Rectangle b = item.getBoundingBox().getBounds();Rectangle newBox = new Rectangle(b.getX() / width, b.getY() / height, b.getWidth() / width, b.getHeight() / height);rectList.add(newBox);});return new DetectedObjects(classList, probList, rectList);}@Overridepublic NDList processInput(TranslatorContext ctx, Image input) throws Exception {return  delegated.processInput(ctx,input);}@Overridepublic void prepare(TranslatorContext ctx) throws Exception {delegated.prepare(ctx);}@Overridepublic Batchifier getBatchifier() {return delegated.getBatchifier();}
}

3.POM文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.lihao</groupId><artifactId>djl</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><name>Spring Boot Blank Project (from https://github.com/making/spring-boot-blank)</name><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.12</version></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><start-class>com.lihao.App</start-class><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>ai.djl</groupId><artifactId>api</artifactId><version>0.23.0</version></dependency><dependency><groupId>ai.djl</groupId><artifactId>basicdataset</artifactId><version>0.23.0</version></dependency><dependency><groupId>ai.djl</groupId><artifactId>model-zoo</artifactId><version>0.23.0</version></dependency><dependency><groupId>org</groupId><artifactId>opencv</artifactId><scope>system</scope><systemPath>${project.basedir}\src\main\resources\lib\opencv-480.jar</systemPath></dependency><!--javacv抽帧--><dependency><groupId>org.bytedeco</groupId><artifactId>javacv</artifactId><version>1.5.6</version></dependency><dependency><groupId>org.bytedeco</groupId><artifactId>ffmpeg-platform</artifactId><version>4.4-1.5.6</version></dependency><dependency><groupId>org.bytedeco</groupId><artifactId>javacv-platform</artifactId><version>1.5.6</version></dependency><!--DJLServing--><dependency><groupId>ai.djl.serving</groupId><artifactId>wlm</artifactId><version>0.23.0</version></dependency><!--mxnet引擎必须包--><!--<dependency><groupId>ai.djl.mxnet</groupId><artifactId>mxnet-engine</artifactId><version>0.23.0</version></dependency>--><!--mxnet引擎必须包--><!--onnx引擎必须包--><dependency><groupId>ai.djl.onnxruntime</groupId><artifactId>onnxruntime-engine</artifactId><version>0.23.0</version><scope>runtime</scope></dependency><!--onnx引擎必须包--><!--pytorch引擎必须包--><dependency><groupId>ai.djl.pytorch</groupId><artifactId>pytorch-model-zoo</artifactId><version>0.23.0</version></dependency><dependency><groupId>ai.djl.pytorch</groupId><artifactId>pytorch-engine</artifactId><version>0.23.0</version></dependency><dependency><groupId>ai.djl.pytorch</groupId><artifactId>pytorch-native-cpu</artifactId><classifier>win-x86_64</classifier><scope>runtime</scope><version>2.0.1</version></dependency><dependency><groupId>ai.djl.pytorch</groupId><artifactId>pytorch-jni</artifactId><version>2.0.1-0.23.0</version><scope>runtime</scope></dependency><!--pytorch引擎必须包--></dependencies><build><finalName>djl</finalName><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>1.8</source><target>1.8</target></configuration></plugin><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.6.0</version></plugin></plugins></build></project>

4.demo运行结果

请添加图片描述请添加图片描述

请添加图片描述

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

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【类和对象】日期类总结

日期类是我们学习类和对象这部分知识的常客&#xff0c;本篇博客我们就对日期类成员函数进行全面总结 目录 一、一览Date.h函数声明 二、Date.cpp逐部分实现 一、流插入与流提取运算符重载 二、日期之间比较大小相等运算符重载 1. > 2. 3. > 4. ! 5. <…

mac前端代码编辑 Sublime Text 4 Dev 中文v4.0(4151)

Sublime Text 4 for Mac是一款功能强大的代码编辑器&#xff0c;适合所有需要高效编写代码和进行代码管理的程序员使用。 快速响应&#xff1a;Sublime Text 4在加载文件和执行命令时非常快速&#xff0c;能够让用户在高效的开发过程中体验到无缝的交互。 多种语言支持&#…

LNMP搭建

LNMP&#xff1a;目前成熟的企业网站的应用模式之一&#xff0c;指的是一套协同工作的系统和相关软件 能够提供静态页面服务&#xff0c;也可以提供动态web服务。 这是一个缩写 L linux系统&#xff0c;操作系统。 N nginx网站服务&#xff0c;也可也理解为前端&#xff0c…

STM32——STM32F401x系列标准库的下载+环境搭建+建工程步骤(更完整)

文章目录 标准库的下载环境搭建建工程最后的话 标准库的下载 1.STM32标准库的官网下载网站https://www.st.com/content/st_com/en.html 2. 3. 4. 5. 6. 7.点击之后下滑 8.选择自己需要的版本下载 环境搭建建工程 大致步骤同之前我写的一篇STM32——建工程差不多&#xff0…

记录下:win10 AMD CPU 下载 Chromium 源码并编译(版本 103.0.5060.66)

文章目录 一、一些主要地址连接二、环境配置1、如何找官方环境文档&#xff1a;1.1 如何找到这个不同版本的文档&#xff1a; 2、电脑配置&#xff1a;3、visual studio 2019安装&#xff1a;3.1 社区版下载&#xff1a;3.2 安装配置&#xff1a; 4、debugtools配置4.1 如何判断…

webpack基础知识八:说说如何借助webpack来优化前端性能?

一、背景 随着前端的项目逐渐扩大&#xff0c;必然会带来的一个问题就是性能 尤其在大型复杂的项目中&#xff0c;前端业务可能因为一个小小的数据依赖&#xff0c;导致整个页面卡顿甚至奔溃 一般项目在完成后&#xff0c;会通过webpack进行打包&#xff0c;利用webpack对前…

【Linux】冯诺伊曼体系结构|操作系统概念理解

个人主页&#xff1a;&#x1f35d;在肯德基吃麻辣烫 我的gitee&#xff1a;Linux仓库 个人专栏&#xff1a;Linux专栏 分享一句喜欢的话&#xff1a;热烈的火焰&#xff0c;冰封在最沉默的火山深处 文章目录 前言一、先谈硬件——冯诺依曼体系结构1.什么是冯诺依曼体系结构&am…

sql 关联了2张表的 update 语句(转)

转自&#xff1a;SQL Update&#xff1a;使用一个表的数据更新另一张表 、update 关联两个表 基本上 select 能支持的关联和子查询操作&#xff0c;都能在 update 语句中使用。 在 where 条件中使用子查询 update a set a.age 1 where id in (select device_id from b) 在 wher…

shell 脚本

一、使用PID过滤该进程的所有信息 #! /bin/bash # Function: 根据用户输入的PID&#xff0c;过滤出该PID所有的信息 read -p "请输入要查询的PID: " P nps -aux| awk $2~/^$P$/{print $11}|wc -l if [ $n -eq 0 ];thenecho "该PID不存在&#xff01;&#xff0…

Flink开发环境准备: centos-jdk8

linux-jdk8 - Flink开发环境准备 一、基本介绍二、环境准备1.1 JDK环境1.2 开发工具1.3 Maven环境 三、flink下载安装配置3.1 Flink下载3.2 flink本地模式安装 - linux3.3 常用配置3.4 日志的查看和配置 四、单机 Standalone 的方式运行 Flink 一、基本介绍 Flink底层源码是基于…

CSS元素的显示模式

1、现在我想做成小米左侧边栏这样的效果&#xff0c;该怎么做呢&#xff1f; 2、小米商城触碰之后会显示出新的商品案例 3、一碰到之后会出现这个列表 4、这里涉及到了元素显示模式&#xff1a; 5、用人进行划分可以分为男人和女人&#xff0c;根据男人和女人的特性进行相应的…

Kill OOM

1、什么是OOM&#xff1f; OOM是每个程序员早晚都必须面对的问题&#xff0c;通常情况下&#xff0c;Java程序员所说的OOM是JVM OOM,即java.lang.OutOfMemoryError&#xff0c;是指Java程序在运行时申请内存超过JVM可用内存限制&#xff0c;导致JVM无法继续分配内存&#xff0…