-
Notifications
You must be signed in to change notification settings - Fork 770
/
Copy pathTNNPoseDetectLandmarkViewModel.mm
276 lines (235 loc) · 11.2 KB
/
TNNPoseDetectLandmarkViewModel.mm
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
// Tencent is pleased to support the open source community by making TNN available.
//
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
#import "TNNPoseDetectLandmarkViewModel.h"
#import "blazepose_detector.h"
#import "blazepose_landmark.h"
#import "pose_detect_landmark.h"
using namespace std;
@interface TNNPoseDetectLandmarkViewModel ()
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) NSArray<UIButton *> *modelButtons;
@property (nonatomic, strong) NSArray<UILabel *> *modelLabels;
@property (nonatomic, assign) NSInteger activeModel; // 0: upper_body, 1: full_body
@property (nonatomic, assign) std::array<std::shared_ptr<TNNSDKSample>, 2> landmarkPredictors;
-(Status) switchLandmarkModel:(NSInteger)modelIndex;
@end
@implementation TNNPoseDetectLandmarkViewModel
- (std::shared_ptr<BlazePoseDetector>) loadPoseDetector:(TNNComputeUnits)units {
std::shared_ptr<BlazePoseDetector> predictor = nullptr;
auto library_path = [[NSBundle mainBundle] pathForResource:@"tnn.metallib" ofType:nil];
auto model_path = [[NSBundle mainBundle] pathForResource:@"model/blazepose/pose_detection.tnnmodel"
ofType:nil];
auto proto_path = [[NSBundle mainBundle] pathForResource:@"model/blazepose/pose_detection.tnnproto"
ofType:nil];
if (proto_path.length <= 0 || model_path.length <= 0) {
LOGE("Error: proto or model or anchor path is invalid\n");
return predictor;
}
string proto_content =
[NSString stringWithContentsOfFile:proto_path encoding:NSUTF8StringEncoding error:nil].UTF8String;
NSData *data_mode = [NSData dataWithContentsOfFile:model_path];
string model_content = [data_mode length] > 0 ? string((const char *)[data_mode bytes], [data_mode length]) : "";
if (proto_content.size() <= 0 || model_content.size() <= 0) {
LOGE("Error: proto or model path is invalid\n");
return predictor;
}
auto option = std::make_shared<BlazePoseDetectorOption>();
{
option->proto_content = proto_content;
option->model_content = model_content;
option->library_path = library_path.UTF8String;
option->compute_units = units;
option->cache_path = NSTemporaryDirectory().UTF8String;
option->min_score_threshold = 0.5;
option->min_suppression_threshold = 0.3;
}
predictor = std::make_shared<BlazePoseDetector>();
auto status = predictor->Init(option);
if (status != TNN_OK) {
LOGE("Error: %s\n", status.description().c_str());
return nullptr;
}
return predictor;
}
- (std::shared_ptr<BlazePoseLandmark>) loadPoseLandmark:(TNNComputeUnits)units full_body:(bool)full_body {
std::shared_ptr<BlazePoseLandmark> predictor = nullptr;
auto library_path = [[NSBundle mainBundle] pathForResource:@"tnn.metallib" ofType:nil];
auto model_path = [[NSBundle mainBundle] pathForResource:@"model/blazepose/pose_landmark_upper_body.tnnmodel"
ofType:nil];
auto proto_path = [[NSBundle mainBundle] pathForResource:@"model/blazepose/pose_landmark_upper_body.tnnproto"
ofType:nil];
if (full_body) {
model_path = [[NSBundle mainBundle] pathForResource:@"model/blazepose/pose_landmark_full_body.tnnmodel"
ofType:nil];
proto_path = [[NSBundle mainBundle] pathForResource:@"model/blazepose/pose_landmark_full_body.tnnproto"
ofType:nil];
}
if (proto_path.length <= 0 || model_path.length <= 0) {
LOGE("Error: proto or model or anchor path is invalid\n");
return predictor;
}
string proto_content =
[NSString stringWithContentsOfFile:proto_path encoding:NSUTF8StringEncoding error:nil].UTF8String;
NSData *data_mode = [NSData dataWithContentsOfFile:model_path];
string model_content = [data_mode length] > 0 ? string((const char *)[data_mode bytes], [data_mode length]) : "";
if (proto_content.size() <= 0 || model_content.size() <= 0) {
LOGE("Error: proto or model path is invalid\n");
return predictor;
}
auto option = std::make_shared<BlazePoseLandmarkOption>();
{
option->proto_content = proto_content;
option->model_content = model_content;
option->library_path = library_path.UTF8String;
option->compute_units = units;
option->cache_path = NSTemporaryDirectory().UTF8String;
option->pose_presence_threshold = 0.5;
option->landmark_visibility_threshold = 0.1;
option->full_body = full_body;
}
predictor = std::make_shared<BlazePoseLandmark>();
auto status = predictor->Init(option);
if (status != TNN_OK) {
LOGE("Error: %s\n", status.description().c_str());
return nullptr;
}
return predictor;
}
-(Status)loadNeuralNetworkModel:(TNNComputeUnits)units {
Status status = TNN_OK;
auto pose_detector = [self loadPoseDetector:units];
RETURN_VALUE_ON_NEQ(!pose_detector,
false,
Status(TNNERR_MODEL_ERR,
"loadPoseDetector failed: pls make sure the pose detect model is downloaded"));
auto pose_landmark_ub = [self loadPoseLandmark:units full_body:false];
RETURN_VALUE_ON_NEQ(!pose_landmark_ub,
false,
Status(TNNERR_MODEL_ERR,
"loadPoseLandmark failed: pls make sure the pose landmark model is downloaded"));
auto pose_landmark_fb = [self loadPoseLandmark:units full_body:true];
RETURN_VALUE_ON_NEQ(!pose_landmark_fb,
false,
Status(TNNERR_MODEL_ERR,
"loadPoseLandmark failed: pls make sure the pose landmark model is downloaded"));
self.landmarkPredictors = {pose_landmark_ub, pose_landmark_fb};
auto active_landmarkmodel = self.landmarkPredictors[self.activeModel];
auto predictor = std::make_shared<PoseDetectLandmark>();
status = predictor->Init({pose_detector, active_landmarkmodel});
RETURN_ON_NEQ(status, TNN_OK);
self.predictor = predictor;
return status;
}
-(Status)switchLandmarkModel:(NSInteger)modelIndex {
auto activeLandmarkModel = self.landmarkPredictors[modelIndex];
// update detect_landmark
auto predictor_cast = dynamic_cast<PoseDetectLandmark *>(self.predictor.get());
RETURN_VALUE_ON_NEQ(!predictor_cast, false, Status(TNNERR_PARAM_ERR, "invalid sdk!"));
auto status = predictor_cast->SwitchLandmarkModel(self.landmarkPredictors[modelIndex], modelIndex==1);
return status;
}
-(std::vector<std::shared_ptr<ObjectInfo> >)getObjectList:(std::shared_ptr<TNNSDKOutput>)sdk_output {
std::vector<std::shared_ptr<ObjectInfo> > body_list;
if (sdk_output && dynamic_cast<BlazePoseLandmarkOutput *>(sdk_output.get())) {
auto body_output = dynamic_cast<BlazePoseLandmarkOutput *>(sdk_output.get());
for (auto item : body_output->body_list) {
auto body = std::make_shared<BlazePoseInfo>();
for(const auto& kp3d: item.key_points_3d) {
item.key_points.push_back(std::make_pair(std::get<0>(kp3d), std::get<1>(kp3d)));
}
*body = item;
body_list.push_back(body);
}
}
return body_list;
}
-(NSString*)labelForObject:(std::shared_ptr<ObjectInfo>)object {
if (object) {
return [NSString stringWithUTF8String:"body"];
}
return nil;
}
#pragma mark - UI control
- (void)setupCustomView:(UIView *)view
layoutHeight:(NSLayoutConstraint *)viewLayoutHeight {
viewLayoutHeight.constant = 75;
// initialize buttons
auto label = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 80, viewLayoutHeight.constant)];
label.font = [UIFont systemFontOfSize:14];
label.text = @"选择模型:";
label.textColor = [UIColor whiteColor];
[view addSubview:label];
const int modelCnt = 2;
std::array<std::string, modelCnt> assetNames = {"blazepose_upper_body", "blazepose_full_body"};
std::array<std::string, modelCnt> labelTexts = {"上半身", "全身"};
auto modeButtons = [NSMutableArray new];
auto modeLabels = [NSMutableArray new];
NSString* iconDir = @"assets/";
for(int i=0; i<modelCnt; ++i) {
// set button
NSString *iconName = [NSString stringWithUTF8String:assetNames[i].c_str()];
NSMutableString *iconPath = [NSMutableString stringWithString:iconDir];
[iconPath appendString: iconName];
NSString *imagePath = [[NSBundle mainBundle] pathForResource:iconPath
ofType:@"png"];
UIImage *btnImage = [UIImage imageNamed:imagePath];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setBackgroundImage:btnImage forState:UIControlStateNormal];
btn.tag = i;
[btn addTarget:self action:@selector(onButtonClick:) forControlEvents:UIControlEventTouchUpInside];
auto btnFrame = CGRectMake(15 + 80 + i*(45 + 20),
12, 45, 45);
btn.frame = btnFrame;
btn.selected = i == 0;
if (btn.selected) {
[btn setBackgroundColor:[UIColor redColor]];
}
[modeButtons addObject:btn];
// set label
auto labelFrame = CGRectMake(btnFrame.origin.x, btnFrame.origin.y+50, btnFrame.size.width, 10);
UILabel *label = [[UILabel alloc] initWithFrame:labelFrame];
label.font = [UIFont systemFontOfSize:12];
label.text = [NSString stringWithUTF8String:labelTexts[i].c_str()];
label.textColor = [UIColor whiteColor];
label.textAlignment = NSTextAlignmentCenter;
[modeLabels addObject:label];
[view addSubview:btn];
[view addSubview:label];
}
self.modelButtons = modeButtons;
self.modelLabels = modeLabels;
self.label = label;
// use big mode for default
self.activeModel = 0;
}
- (void) onButtonClick:(UIButton *)button {
auto selected = button.selected;
if (selected) {
for(UIButton *item in self.modelButtons) {
item.selected = NO;
}
} else {
for(UIButton *item in self.modelButtons) {
item.selected = NO;
[item setBackgroundColor:[UIColor clearColor]];
}
button.selected = YES;
[button setBackgroundColor:[UIColor redColor]];
}
if (button.selected) {
self.activeModel = button.tag;
[self switchLandmarkModel:self.activeModel];
}
}
@end