-
Notifications
You must be signed in to change notification settings - Fork 3k
/
model.py
155 lines (132 loc) · 6.5 KB
/
model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
from jetson_inference import imageNet, detectNet, segNet, poseNet, actionNet, backgroundNet
from jetson_utils import cudaFont, cudaAllocMapped, Log
class Model:
"""
Represents DNN models for classification, detection, pose, ect.
"""
def __init__(self, type, model, labels='', colors='', input_layer='', output_layer='', **kwargs):
"""
Load the model, either from a built-in pre-trained model or from a user-provided model.
Parameters:
type (string) -- the type of the model (classification, detection, ect)
model (string) -- either a path to the model or name of the built-in model
labels (string) -- path to the model's labels.txt file (optional)
input_layer (string or dict) -- the model's input layer(s)
output_layer (string or dict) -- the model's output layers()
"""
self.type = type
self.model = model
self.enabled = True
self.results = None
self.frames = 0
if type == 'classification':
self.net = imageNet(model=model, labels=labels, input_blob=input_layer, output_blob=output_layer)
if 'threshold' in kwargs:
self.net.SetThreshold(kwargs['threshold'])
if 'smoothing' in kwargs:
self.net.SetSmoothing(kwargs['smoothing'])
elif type == 'detection':
if not output_layer:
output_layer = {'scores': '', 'bbox': ''}
elif isinstance(output_layer, str):
output_layer = output_layer.split(',')
output_layer = {'scores': output_layer[0], 'bbox': output_layer[1]}
elif not isinstance(output_layer, dict) or output_layer.keys() < {'scores', 'bbox'}:
raise ValueError("for detection models, output_layer should be a dict with keys 'scores' and 'bbox'")
print(input_layer)
print(output_layer)
self.net = detectNet(model=model, labels=labels, colors=colors,
input_blob=input_layer,
output_cvg=output_layer['scores'],
output_bbox=output_layer['bbox'])
elif type == 'segmentation':
self.net = segNet(model=model, labels=labels, colors=colors, input_blob=input_layer, output_blob=output_layer)
self.overlayImg = None
elif type == 'pose':
self.net = poseNet(model)
elif type == 'action':
self.net = actionNet(model)
elif type == 'background':
self.net = backgroundNet(model)
else:
raise ValueError(f"invalid model type '{type}'")
if type == 'classification' or type == 'action':
self.font = cudaFont()
self.fontLine = 0
def Process(self, img):
"""
Process an image with the model and return the results.
"""
if not self.enabled:
return
if self.type == 'classification' or self.type == 'action':
self.results = self.net.Classify(img)
elif self.type == 'detection':
self.results = self.net.Detect(img, overlay='none')
elif self.type == 'segmentation':
self.results = self.net.Process(img)
elif self.type == 'pose':
self.results = self.net.Process(img)
self.frames += 1
return self.results
def Visualize(self, img, results=None):
"""
Visualize the results on an image.
"""
if not self.enabled:
return img
if results is None:
results = self.results
if self.type == 'classification' or self.type == 'action':
if results[0] >= 0:
str = f"{results[1] * 100:05.2f}% {self.net.GetClassLabel(results[0])}"
self.font.OverlayText(img, img.width, img.height, str, 5, 5 + (self.fontLine * 37), self.font.White, self.font.Gray40)
elif self.type == 'detection':
self.net.Overlay(img, results)
elif self.type == 'segmentation':
if not self.overlayImg or self.overlayImg.width != img.width or self.overlayImg.height != img.height:
self.overlayImg = cudaAllocMapped(like=img)
self.net.Overlay(self.overlayImg, filter_mode='linear')
return self.overlayImg
elif self.type == 'pose':
self.net.Overlay(img, self.results, 'links,keypoints')
elif self.type == 'background':
self.net.Process(img)
return img
def IsEnabled(self):
"""
Returns true if the model is enabled for processing, false otherwise.
"""
return self.enabled
def SetEnabled(self, enabled):
"""
Enable/disable processing of the model.
"""
self.enabled = enabled
@staticmethod
def Usage():
"""
Return help text for when the app is started with -h or --help
"""
return imageNet.Usage() + detectNet.Usage() + segNet.Usage() + actionNet.Usage() + poseNet.Usage() + backgroundNet.Usage()