Linux 36.3 + JetPack v6.0@jetson-inference之图像分类

news2024/10/7 12:19:19

Linux 36.3 + JetPack v6.0@jetson-inference之图像分类

  • 1. 源由
  • 2. imagenet
    • 2.1 命令选项
    • 2.2 下载模型
    • 2.3 操作示例
      • 2.3.1 单张照片
      • 2.3.2 视频
  • 3. 代码
    • 3.1 Python
    • 3.2 C++
  • 4. 参考资料
  • 5. 补充
    • 5.1 第一次运行模型本地适应初始化
    • 5.2 samba软连接

1. 源由

从应用角度来说,图像分类是计算机视觉里面最基本的一个操作。

2. imagenet

imageNet对象接受输入图像并输出每个类别的概率。GoogleNet和ResNet-18模型在构建过程中自动下载,这些模型已在包含1000个物体的ImageNet ILSVRC数据集上进行了训练。

2.1 命令选项

$ imagenet --help
usage: imagenet [--help] [--network=NETWORK] ...
                input_URI [output_URI]

Classify a video/image stream using an image recognition DNN.
See below for additional arguments that may not be shown above.

optional arguments:
  --help            show this help message and exit
  --network=NETWORK pre-trained model to load (see below for options)
  --topK=N         show the topK number of class predictions (default: 1)
positional arguments:
    input_URI       resource URI of input stream  (see videoSource below)
    output_URI      resource URI of output stream (see videoOutput below)

imageNet arguments:
  --network=NETWORK    pre-trained model to load, one of the following:
                           * alexnet
                           * googlenet (default)
                           * googlenet-12
                           * resnet-18
                           * resnet-50
                           * resnet-101
                           * resnet-152
                           * vgg-16
                           * vgg-19
                           * inception-v4
  --model=MODEL        path to custom model to load (caffemodel, uff, or onnx)
  --prototxt=PROTOTXT  path to custom prototxt to load (for .caffemodel only)
  --labels=LABELS      path to text file containing the labels for each class
  --input-blob=INPUT   name of the input layer (default is 'data')
  --output-blob=OUTPUT name of the output layer (default is 'prob')
  --threshold=CONF     minimum confidence threshold for classification (default is 0.01)
  --smoothing=WEIGHT   weight between [0,1] or number of frames (disabled by default)
  --profile            enable layer profiling in TensorRT

videoSource arguments:
    input                resource URI of the input stream, for example:
                             * /dev/video0               (V4L2 camera #0)
                             * csi://0                   (MIPI CSI camera #0)
                             * rtp://@:1234              (RTP stream)
                             * rtsp://user:pass@ip:1234  (RTSP stream)
                             * webrtc://@:1234/my_stream (WebRTC stream)
                             * file://my_image.jpg       (image file)
                             * file://my_video.mp4       (video file)
                             * file://my_directory/      (directory of images)
  --input-width=WIDTH    explicitly request a width of the stream (optional)
  --input-height=HEIGHT  explicitly request a height of the stream (optional)
  --input-rate=RATE      explicitly request a framerate of the stream (optional)
  --input-save=FILE      path to video file for saving the input stream to disk
  --input-codec=CODEC    RTP requires the codec to be set, one of these:
                             * h264, h265
                             * vp8, vp9
                             * mpeg2, mpeg4
                             * mjpeg
  --input-decoder=TYPE   the decoder engine to use, one of these:
                             * cpu
                             * omx  (aarch64/JetPack4 only)
                             * v4l2 (aarch64/JetPack5 only)
  --input-flip=FLIP      flip method to apply to input:
                             * none (default)
                             * counterclockwise
                             * rotate-180
                             * clockwise
                             * horizontal
                             * vertical
                             * upper-right-diagonal
                             * upper-left-diagonal
  --input-loop=LOOP      for file-based inputs, the number of loops to run:
                             * -1 = loop forever
                             *  0 = don't loop (default)
                             * >0 = set number of loops

videoOutput arguments:
    output               resource URI of the output stream, for example:
                             * file://my_image.jpg       (image file)
                             * file://my_video.mp4       (video file)
                             * file://my_directory/      (directory of images)
                             * rtp://<remote-ip>:1234    (RTP stream)
                             * rtsp://@:8554/my_stream   (RTSP stream)
                             * webrtc://@:1234/my_stream (WebRTC stream)
                             * display://0               (OpenGL window)
  --output-codec=CODEC   desired codec for compressed output streams:
                            * h264 (default), h265
                            * vp8, vp9
                            * mpeg2, mpeg4
                            * mjpeg
  --output-encoder=TYPE  the encoder engine to use, one of these:
                            * cpu
                            * omx  (aarch64/JetPack4 only)
                            * v4l2 (aarch64/JetPack5 only)
  --output-save=FILE     path to a video file for saving the compressed stream
                         to disk, in addition to the primary output above
  --bitrate=BITRATE      desired target VBR bitrate for compressed streams,
                         in bits per second. The default is 4000000 (4 Mbps)
  --headless             don't create a default OpenGL GUI window

logging arguments:
  --log-file=FILE        output destination file (default is stdout)
  --log-level=LEVEL      message output threshold, one of the following:
                             * silent
                             * error
                             * warning
                             * success
                             * info
                             * verbose (default)
                             * debug
  --verbose              enable verbose logging (same as --log-level=verbose)
  --debug                enable debug logging   (same as --log-level=debug)

注:关于照片、视频等基本操作,详见: 《Linux 36.3 + JetPack v6.0@jetson-inference之视频操作》

2.2 下载模型

两种方式:

  1. 创建imageNet对象时,初始化会自动下载
  2. 通过手动将模型文件放置到data/networks/目录下

国内,由于“墙”的存在,对于我们这种处于起飞阶段的菜鸟来说就是“障碍”。有条件的朋友可以参考《apt-get通过代理更新系统》进行设置网络。

不过,NVIDIA还是很热心的帮助我们做了“Work around”,所有的模型都已经预先存放在中国大陆能访问的位置:Github - model-mirror-190618

  --network=NETWORK    pre-trained model to load, one of the following:
                           * alexnet
                           * googlenet (default)
                           * googlenet-12
                           * resnet-18
                           * resnet-50
                           * resnet-101
                           * resnet-152
                           * vgg-16
                           * vgg-19
                           * inception-v4
  --model=MODEL        path to custom model to load (caffemodel, uff, or onnx)

根据以上Model方面信息,该命令支持:

  • alexnet
  • googlenet (default)
  • googlenet-12
  • resnet-18
  • resnet-50
  • resnet-101
  • resnet-152
  • vgg-16
  • vgg-19
  • inception-v4
  • 支持定制模型(需要用到通用的模型文件caffemodel, uff, or onnx)

作为示例,就下载一个googlenet (default)模型

$ mkdir model-mirror-190618
$ cd model-mirror-190618
$ wget https://github.com/dusty-nv/jetson-inference/releases/download/model-mirror-190618/GoogleNet.tar.gz
$ mkdir -p ../data/networks/Googlenet
$ tar -zxvf GoogleNet.tar.gz -C ../data/networks/Googlenet
$ cd ..

注:这个模型文件下载要注意,将解压缩文件放置到Googlenet目录下。

2.3 操作示例

它加载图像(或多张图像),使用TensorRT和imageNet类进行推理,然后叠加分类结果并保存输出图像。该项目附带了供您使用的示例图像,这些图像位于images/目录下。

  • What’s wrong with imagenet, continous printf?
$ cd build/aarch64/bin/

2.3.1 单张照片

# C++
$ ./imagenet images/orange_0.jpg images/test/output_imagenet_cpp.jpg

在这里插入图片描述

# Python
$ ./imagenet.py images/strawberry_0.jpg images/test/output_imagenet_python.jpg

在这里插入图片描述

2.3.2 视频

# Download test video (thanks to jell.yfish.us)
$ wget https://nvidia.box.com/shared/static/tlswont1jnyu3ix2tbf7utaekpzcx4rc.mkv -O jellyfish.mkv
# C++
$ ./imagenet --network=resnet-18 ../../../jellyfish.mkv images/test/output_imagenet_jellyfish_cpp.mkv
# Python
$ ./imagenet.py --network=resnet-18 ../../../jellyfish.mkv images/test/output_imagenet_jellyfish_python.mkv

这里视频就放一份了,理论上将既然有概率性的问题求解方式,不同时间运算的结果可能会有差异。但是基于这个模型,计算机没有记忆,所以理论上是同一个概率。

那么问题来了,照片的CPP和Python两次运算概率确是是不一样的。这是什么原因呢?

output_imagenet_jellyfish_cpp

3. 代码

3.1 Python

Import statements
├── sys
├── argparse
├── jetson_inference
│   └── imageNet
└── jetson_utils
    ├── videoSource
    ├── videoOutput
    ├── cudaFont
    └── Log

Command line parsing
├── Create ArgumentParser
│   ├── description
│   ├── formatter_class
│   └── epilog
├── Add arguments
│   ├── input
│   ├── output
│   ├── --network
│   └── --topK
└── Parse arguments
    ├── try
    │   └── args = parser.parse_known_args()[0]
    └── except
        ├── print("")
        ├── parser.print_help()
        └── sys.exit(0)

Load the recognition network
└── net = imageNet(args.network, sys.argv)

Optional hard-coded model loading (commented out)
└── net = imageNet(model="model/resnet18.onnx", labels="model/labels.txt", 
                   input_blob="input_0", output_blob="output_0")

Create video sources & outputs
├── input = videoSource(args.input, argv=sys.argv)
├── output = videoOutput(args.output, argv=sys.argv)
└── font = cudaFont()

Process frames until EOS or user exits
└── while True
    ├── Capture the next image
    │   ├── img = input.Capture()
    │   └── if img is None
    │       └── continue
    ├── Classify the image and get the topK predictions
    │   └── predictions = net.Classify(img, topK=args.topK)
    ├── Draw predicted class labels
    │   └── for n, (classID, confidence) in enumerate(predictions)
    │       ├── classLabel = net.GetClassLabel(classID)
    │       ├── confidence *= 100.0
    │       ├── print(f"imagenet:  {confidence:05.2f}% class #{classID} ({classLabel})")
    │       └── font.OverlayText(img, text=f"{confidence:05.2f}% {classLabel}", 
    │                            x=5, y=5 + n * (font.GetSize() + 5),
    │                            color=font.White, background=font.Gray40)
    ├── Render the image
    │   └── output.Render(img)
    ├── Update the title bar
    │   └── output.SetStatus("{:s} | Network {:.0f} FPS".format(net.GetNetworkName(), net.GetNetworkFPS()))
    ├── Print out performance info
    │   └── net.PrintProfilerTimes()
    └── Exit on input/output EOS
        └── if not input.IsStreaming() or not output.IsStreaming()
            └── break

3.2 C++

#include statements
├── "videoSource.h"
├── "videoOutput.h"
├── "cudaFont.h"
├── "imageNet.h"
└── <signal.h>

Global variables
└── bool signal_recieved = false;

Function definitions
├── void sig_handler(int signo)
│   └── if (signo == SIGINT)
│       ├── LogVerbose("received SIGINT\n");
│       └── signal_recieved = true;
└── int usage()
    ├── printf("usage: imagenet [--help] [--network=NETWORK] ...\n");
    ├── printf("                input_URI [output_URI]\n\n");
    ├── printf("Classify a video/image stream using an image recognition DNN.\n");
    ├── printf("See below for additional arguments that may not be shown above.\n\n");
    ├── printf("optional arguments:\n");
    ├── printf("  --help            show this help message and exit\n");
    ├── printf("  --network=NETWORK pre-trained model to load (see below for options)\n");
    ├── printf("  --topK=N          show the topK number of class predictions (default: 1)\n");
    ├── printf("positional arguments:\n");
    ├── printf("    input_URI       resource URI of input stream  (see videoSource below)\n");
    ├── printf("    output_URI      resource URI of output stream (see videoOutput below)\n\n");
    ├── printf("%s", imageNet::Usage());
    ├── printf("%s", videoSource::Usage());
    ├── printf("%s", videoOutput::Usage());
    └── printf("%s", Log::Usage());

main function
├── Parse command line
│   ├── commandLine cmdLine(argc, argv);
│   └── if (cmdLine.GetFlag("help"))
│       └── return usage();
├── Attach signal handler
│   └── if (signal(SIGINT, sig_handler) == SIG_ERR)
│       └── LogError("can't catch SIGINT\n");
├── Create input stream
│   ├── videoSource* input = videoSource::Create(cmdLine, ARG_POSITION(0));
│   └── if (!input)
│       ├── LogError("imagenet:  failed to create input stream\n");
│       └── return 1;
├── Create output stream
│   ├── videoOutput* output = videoOutput::Create(cmdLine, ARG_POSITION(1));
│   └── if (!output)
│       ├── LogError("imagenet:  failed to create output stream\n");
│       └── return 1;
├── Create font for image overlay
│   ├── cudaFont* font = cudaFont::Create();
│   └── if (!font)
│       ├── LogError("imagenet:  failed to load font for overlay\n");
│       └── return 1;
├── Create recognition network
│   ├── imageNet* net = imageNet::Create(cmdLine);
│   └── if (!net)
│       ├── LogError("imagenet:  failed to initialize imageNet\n");
│       └── return 1;
│   ├── const int topK = cmdLine.GetInt("topK", 1);  // default top result
├── Processing loop
│   └── while (!signal_recieved)
│       ├── uchar3* image = NULL;
│       ├── int status = 0;
│       ├── if (!input->Capture(&image, &status))
│       │   └── if (status == videoSource::TIMEOUT)
│       │       └── continue;
│       │   └── break; // EOS
│       ├── imageNet::Classifications classifications; // classID, confidence
│       ├── if (net->Classify(image, input->GetWidth(), input->GetHeight(), classifications, topK) < 0)
│       │   └── continue;
│       ├── for (uint32_t n=0; n < classifications.size(); n++)
│       │   ├── const uint32_t classID = classifications[n].first;
│       │   ├── const char* classLabel = net->GetClassLabel(classID);
│       │   ├── const float confidence = classifications[n].second * 100.0f;
│       │   ├── LogVerbose("imagenet:  %2.5f%% class #%i (%s)\n", confidence, classID, classLabel);
│       │   ├── char str[256];
│       │   ├── sprintf(str, "%05.2f%% %s", confidence, classLabel);
│       │   └── font->OverlayText(image, input->GetWidth(), input->GetHeight(),
│       │       str, 5, 5 + n * (font->GetSize() + 5), 
│       │       make_float4(255,255,255,255), make_float4(0,0,0,100));
│       ├── if (output != NULL)
│       │   ├── output->Render(image, input->GetWidth(), input->GetHeight());
│       │   ├── char str[256];
│       │   ├── sprintf(str, "TensorRT %i.%i.%i | %s | Network %.0f FPS", NV_TENSORRT_MAJOR, NV_TENSORRT_MINOR, NV_TENSORRT_PATCH, net->GetNetworkName(), net->GetNetworkFPS());
│       │   └── output->SetStatus(str);
│       │   └── if (!output->IsStreaming())
│       │       └── break;
│       └── net->PrintProfilerTimes();
├── Destroy resources
│   ├── LogVerbose("imagenet:  shutting down...\n");
│   ├── SAFE_DELETE(input);
│   ├── SAFE_DELETE(output);
│   ├── SAFE_DELETE(net);
└── LogVerbose("imagenet:  shutdown complete.\n");
    return 0;

4. 参考资料

【1】jetson-inference - Classifying Images with ImageNet

5. 补充

5.1 第一次运行模型本地适应初始化

第一次运行神经网络,虽然模型是预训练的,但是本地部署还是有个初始化过程,好像是建立一些cache的过程,具体有待进一步研究。

注:有知道为什么是这样,也请评论区告诉我,谢谢!

  • imagenet can’t work as readme says, see attached log #1858
  • could not find engine cache … MonoDepth-FCN-Mobilenet/monodepth_fcn_mobilenet.onnx.1.1.8602.GPU.FP16.engine ? #1855
  • What’s wrong with imagenet/detectnet, continous printf?

5.2 samba软连接

注:share请替换为samba共享目录,比如:home

  • ubuntu22.04 配置
[global]
allow insecure wide links = yes

[share]
follow symlinks = yes
wide links = yes
  • 之前的版本
[global]
unix extensions = no

[share]
follow symlinks = yes
wide links = yes

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

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

相关文章

Linux下gcc编译32位程序报错

gcc使用-m32选项&#xff0c;编译32位程序时&#xff0c;报错&#xff1a;/usr/include/stdio.h:27:10: fatal error: bits/libc-header-start.h: No such file or directory gcc编译32位程序时&#xff0c;报错&#xff1a;/usr/include/stdio.h:27:10: fatal error: bits/li…

vue3+ elementPlus PC端开发 遇到页面已进入就form校验了的问题

form表单一进页面就校验了 rules里配置的 require 提示语 如图所示代码是这样的 最后发现是form表单下面的一个按钮的展示规则 会导致规则校验 canAddInsured 这个字段的变化会导致form表单校验 这个字段是computed maxInsureds 也是个computed监听 maxInsured.value >1 就…

MySQL 导出导入的101个坑

最近接到一个业务自行运维的MySQL库迁移至标准化环境的需求&#xff0c;库不大&#xff0c;迁移方式也很简单&#xff0c;由开发用myqldump导出数据、DBA导入&#xff0c;但迁移过程坎坷十足&#xff0c;记录一下遇到的各项报错及后续迁移注意事项。 一、 概要 空间问题源与目…

亚马逊新品如何快速吸引流量?自养号测评助卖家一臂之力

在亚马逊平台上每天都会有大量的新品推出&#xff0c;而这些新品中有部分可能并没有什么流量和订单&#xff0c;有些可能上架后立马就能获得流量了&#xff0c;那么亚马逊上新品一般几天出单&#xff1f; 一、亚马逊上新品一般几天出单&#xff1f; 亚马逊上新品出单的时间因…

@Validated 前端表单数据校验

1. 整合 1.1 依赖引入 <dependency><groupId>org.hibernate.validator</groupId><artifactId>hibernate-validator</artifactId></dependency>1.2 控制层 /*** 新增胎架计划** param subsectionPlanVo* return*/PostMapping("/sched…

从混乱到有序:PDM系统如何优化物料编码

在现代制造业中&#xff0c;物料管理是企业运营的核心。物料编码作为物料管理的基础&#xff0c;对于确保物料的准确性、唯一性和高效性至关重要。随着产品种类的不断增加和产品变型的多样化&#xff0c;传统的物料编码管理方式已经不能满足企业的需求。本文将探讨产品数据管理…

1000Base-T协议解读

一、说明 千兆以太网家族包括1000Base-SX(短距)、1000Base-LX(长距)、1000Base-CX(铜缆短距)、1000Base-T1(车载以太网)和1000Base-T等多种标准,我们这边主要了解下1000Base-T,也就是工业千兆以太网,PC电脑的网口都是这个。 1000Base-T采用了4D-PAM5编码技术(4D代…

MYSQL基础_02_MySQL环境搭建

第02章_MySQL环境搭建 1. MySQL的卸载 步骤1&#xff1a;停止MySQL服务 在卸载之前&#xff0c;先停止MySQL8.0的服务。按键盘上的“Ctrl Alt Delete”组合键&#xff0c;打开“任务管理器”对话框&#xff0c;可以在“服务”列表找到“MySQL8.0”的服务&#xff0c;如果现…

GAT1399协议分析(8)--批量图像查询

一、请求消息定义 视频图像包含视频片段、 图像、 文件、 人员、 人脸、 机动车、 非机动车、 物品、 场景和视频案事件、 视频图像标签等对象 在消息体中,可以包含其中一种类,加上Data字段即可。 ImageInfo对象 二、请求消息实例 wireshark 抓包实例 请求: 文本化: /V…

Java 还能不能继续搞了?

金三银四招聘季已落幕&#xff0c;虽说行情不是很乐观&#xff0c;但真正的强者从不抱怨。 在此期间&#xff0c;我收到众多小伙伴的宝贵反馈&#xff0c;整理出132道面试题&#xff0c;从基础到高级&#xff0c;有八股文&#xff0c;也有对某个知识点的深度解析。包括以下几部…

交流回馈老化测试负载:行业竞争态势

在当今的科技行业中&#xff0c;交流回馈老化测试负载设备已经成为了一个重要的组成部分。这种设备主要用于模拟电力系统中的各种负载情况&#xff0c;以便对电力系统进行全面的测试和评估。随着科技的不断发展&#xff0c;这个行业的竞争态势也在不断变化。 从市场竞争的角度来…

小牛翻译API详解:功能、优势介绍及案例实战(附完整代码)

写在前面小牛翻译是做什么的案例-调用图片翻译API进行英文翻译✔准备工作✔获取密钥✔调用API✔完整代码✔运行项目 使用建议 写在前面 随着全球化的快速发展和跨国交流的增多&#xff0c;翻译软件的市场需求持续增长。根据市场数据&#xff0c;全球语言翻译软件市场规模在过去…

红海边的这座城,如何点亮人类可持续发展之梦

导读&#xff1a;造一座100%清洁能源供电的城市&#xff1f; 城市是人类最伟大的成就之一&#xff0c;数千年来城市承载了人类文明的跃迁。21世纪&#xff0c;在人类追求可持续发展的蓝图中&#xff0c;城市有了新的使命。 容纳全球50%以上人口&#xff0c;但碳排放量超过70%的…

无线:wireless

第一节&#xff1a;无线链路和网络特征 无线链路特征 与有线链路的重要差别表现在&#xff1a; 衰减的信号强度&#xff1a;decreased signal strength来自其他信号源的干扰&#xff1a;interference from other sources多路径传输&#xff1a;multipath propagation&#xf…

Linux-vi编辑器命令使用

一、初始-vi 1、 vi-打开文件并且定位行 有可能会遇到打开一个文件&#xff0c;并定位到指定行的情况 例如&#xff0c;知道某一行代码有错误&#xff0c;可以快速定位到出错代码的位置 可以使用以下命令打开文件$ vi 文件名 行数 提示&#xff1a;如果只带上 而不指定行号&…

Python离线查询IP地址对应的国家和城市

使用场景&#xff1a; 在没网的情况下使用python代码实现对ip地址进行查询国家和地市 代码实现&#xff1a; 需要安装 pip install geoip2 库 import geoip2.databasedef get_location_by_ip(ip_address, db_path):reader geoip2.database.Reader(db_path)try:response r…

[网络基础]——计算机网络(OSI)参考模型 详解

&#x1f3e1;作者主页&#xff1a;点击&#xff01; &#x1f310;网络通信基础TCP/IP专栏&#xff1a;点击&#xff01; ⏰️创作时间&#xff1a;2024年6月2日21点59分 &#x1f004;️文章质量&#xff1a;93分 目录 &#x1f39f;️OSI基本概念 &#x1f384;分层架构…

基于jeecgboot-vue3的Flowable流程-已办任务(一)

因为这个项目license问题无法开源&#xff0c;更多技术支持与服务请加入我的知识星球。 1、api接口部分 import { defHttp } from //utils/http/axios;enum Api {flowRecord /flowable/task/flowRecord,finishedListNew /flowable/task/finishedListNew,revokeProcess /flo…

LeetCode---二叉树

144/94/145. 二叉树的前、中、后序的递归遍历 以中序遍历为例&#xff0c;其余类似&#xff1a; 给定一个二叉树的根节点 root &#xff0c;返回 它的 中序 遍历 。 代码示例&#xff1a; /*** Definition for a binary tree node.* struct TreeNode {* int val;* Tr…

Hive的常规操作

Hive常规操作 hive常用交互命令 -e执行sql语句 [rootmaster ~]# hive -e "show databases";-f执行sql脚本 [rootmaster ~]# hive -f /usr/local/demo.sql查看hive中输入的所有命令 [rootmaster ~]# cat ~/.hivehistory操作库 创建库 语法&#xff1a; create…