-
Notifications
You must be signed in to change notification settings - Fork 206
/
Copy pathrtpose.cpp
1780 lines (1598 loc) · 73.7 KB
/
rtpose.cpp
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <ctime>
#include <iostream>
#include <mutex>
#include <string>
#include <vector>
#include <utility> //std::pair
#include <pthread.h>
#include <time.h>
#include <signal.h>
#include <stdio.h> // snprintf
#include <unistd.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <boost/thread/thread.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <gflags/gflags.h>
#include <google/protobuf/text_format.h>
#include <opencv2/core/core.hpp>
// #include <opencv2/contrib/contrib.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "caffe/cpm/frame.h"
#include "caffe/cpm/layers/imresize_layer.hpp"
#include "caffe/cpm/layers/nms_layer.hpp"
#include "caffe/net.hpp"
#include "caffe/util/blocking_queue.hpp"
// #include "caffe/util/render_functions.hpp"
// #include "caffe/blob.hpp"
// #include "caffe/common.hpp"
// #include "caffe/proto/caffe.pb.h"
// #include "caffe/util/db.hpp"
// #include "caffe/util/io.hpp"
// #include "caffe/util/benchmark.hpp"
#include "rtpose/modelDescriptor.h"
#include "rtpose/modelDescriptorFactory.h"
#include "rtpose/renderFunctions.h"
// Flags (rtpose.bin --help)
DEFINE_bool(fullscreen, false, "Run in fullscreen mode (press f during runtime to toggle)");
DEFINE_int32(part_to_show, 0, "Part to show from the start.");
DEFINE_string(write_frames, "", "Write frames with format prefix%06d.jpg");
DEFINE_bool(no_frame_drops, false, "Dont drop frames.");
DEFINE_string(write_json, "", "Write joint data with json format as prefix%06d.json");
DEFINE_int32(camera, 0, "The camera index for VideoCapture.");
DEFINE_string(video, "", "Use a video file instead of the camera.");
DEFINE_string(image_dir, "", "Process a directory of images.");
DEFINE_int32(start_frame, 0, "Skip to frame # of video");
DEFINE_string(caffemodel, "model/coco/pose_iter_440000.caffemodel", "Caffe model.");
DEFINE_string(caffeproto, "model/coco/pose_deploy_linevec.prototxt", "Caffe deploy prototxt.");
// DEFINE_string(caffemodel, "model/mpi/pose_iter_160000.caffemodel", "Caffe model.");
// DEFINE_string(caffeproto, "model/mpi/pose_deploy_linevec.prototxt", "Caffe deploy prototxt.");
DEFINE_string(resolution, "1280x720", "The image resolution (display).");
DEFINE_string(net_resolution, "656x368", "Multiples of 16.");
DEFINE_string(camera_resolution, "1280x720", "Size of the camera frames to ask for.");
DEFINE_int32(start_device, 0, "GPU device start number.");
DEFINE_int32(num_gpu, 1, "The number of GPU devices to use.");
DEFINE_double(start_scale, 1, "Initial scale. Must cv::Match net_resolution");
DEFINE_double(scale_gap, 0.3, "Scale gap between scales. No effect unless num_scales>1");
DEFINE_int32(num_scales, 1, "Number of scales to average");
DEFINE_bool(no_display, false, "Do not open a display window.");
DEFINE_bool(no_text, false, "Do not write text on output images.");
// Global parameters
int DISPLAY_RESOLUTION_WIDTH;
int DISPLAY_RESOLUTION_HEIGHT;
int CAMERA_FRAME_WIDTH;
int CAMERA_FRAME_HEIGHT;
int NET_RESOLUTION_WIDTH;
int NET_RESOLUTION_HEIGHT;
int BATCH_SIZE;
double SCALE_GAP;
double START_SCALE;
int NUM_GPU;
std::string PERSON_DETECTOR_CAFFEMODEL; //person detector
std::string PERSON_DETECTOR_PROTO; //person detector
std::string POSE_ESTIMATOR_PROTO; //pose estimator
const auto MAX_PEOPLE = RENDER_MAX_PEOPLE; // defined in render_functions.hpp
const auto BOX_SIZE = 368;
const auto BUFFER_SIZE = 4; //affects latency
const auto MAX_NUM_PARTS = 70;
// global queues for I/O
struct Global {
caffe::BlockingQueue<Frame> input_queue; //have to pop
caffe::BlockingQueue<Frame> output_queue; //have to pop
caffe::BlockingQueue<Frame> output_queue_ordered;
caffe::BlockingQueue<Frame> output_queue_mated;
std::priority_queue<int, std::vector<int>, std::greater<int> > dropped_index;
std::vector< std::string > image_list;
std::mutex mutex;
int part_to_show;
bool quit_threads;
// Parameters
float nms_threshold;
int connect_min_subset_cnt;
float connect_min_subset_score;
float connect_inter_threshold;
int connect_inter_min_above_threshold;
struct UIState {
UIState() :
is_fullscreen(0),
is_video_paused(0),
is_shift_down(0),
is_googly_eyes(0),
current_frame(0),
seek_to_frame(-1),
fps(0) {}
bool is_fullscreen;
bool is_video_paused;
bool is_shift_down;
bool is_googly_eyes;
int current_frame;
int seek_to_frame;
double fps;
};
UIState uistate;
};
// network copy for each gpu thread
struct NetCopy {
caffe::Net<float> *person_net;
std::vector<int> num_people;
int nblob_person;
int nms_max_peaks;
int nms_num_parts;
std::unique_ptr<ModelDescriptor> up_model_descriptor;
float* canvas; // GPU memory
float* joints; // GPU memory
};
struct ColumnCompare
{
bool operator()(const std::vector<double>& lhs,
const std::vector<double>& rhs) const
{
return lhs[2] > rhs[2];
//return lhs[0] > rhs[0];
}
};
Global global;
std::vector<NetCopy> net_copies;
int rtcpm();
bool handleKey(int c);
void warmup(int);
void process_and_pad_image(float* target, cv::Mat oriImg, int tw, int th, bool normalize);
double get_wall_time() {
struct timeval time;
if (gettimeofday(&time,NULL)) {
// Handle error
return 0;
}
return (double)time.tv_sec + (double)time.tv_usec * 1e-6;
//return (double)time.tv_usec;
}
void warmup(int device_id) {
int logtostderr = FLAGS_logtostderr;
LOG(INFO) << "Setting GPU " << device_id;
caffe::Caffe::SetDevice(device_id); //cudaSetDevice(device_id) inside
caffe::Caffe::set_mode(caffe::Caffe::GPU); //
LOG(INFO) << "GPU " << device_id << ": copying to person net";
FLAGS_logtostderr = 0;
net_copies[device_id].person_net = new caffe::Net<float>(PERSON_DETECTOR_PROTO, caffe::TEST);
net_copies[device_id].person_net->CopyTrainedLayersFrom(PERSON_DETECTOR_CAFFEMODEL);
net_copies[device_id].nblob_person = net_copies[device_id].person_net->blob_names().size();
net_copies[device_id].num_people.resize(BATCH_SIZE);
const std::vector<int> shape { {BATCH_SIZE, 3, NET_RESOLUTION_HEIGHT, NET_RESOLUTION_WIDTH} };
net_copies[device_id].person_net->blobs()[0]->Reshape(shape);
net_copies[device_id].person_net->Reshape();
FLAGS_logtostderr = logtostderr;
caffe::NmsLayer<float> *nms_layer = (caffe::NmsLayer<float>*)net_copies[device_id].person_net->layer_by_name("nms").get();
net_copies[device_id].nms_max_peaks = nms_layer->GetMaxPeaks();
caffe::ImResizeLayer<float> *resize_layer =
(caffe::ImResizeLayer<float>*)net_copies[device_id].person_net->layer_by_name("resize").get();
resize_layer->SetStartScale(START_SCALE);
resize_layer->SetScaleGap(SCALE_GAP);
LOG(INFO) << "start_scale = " << START_SCALE;
net_copies[device_id].nms_max_peaks = nms_layer->GetMaxPeaks();
net_copies[device_id].nms_num_parts = nms_layer->GetNumParts();
CHECK_LE(net_copies[device_id].nms_num_parts, MAX_NUM_PARTS)
<< "num_parts in NMS layer (" << net_copies[device_id].nms_num_parts << ") "
<< "too big ( MAX_NUM_PARTS )";
if (net_copies[device_id].nms_num_parts==15) {
ModelDescriptorFactory::createModelDescriptor(ModelDescriptorFactory::Type::MPI_15, net_copies[device_id].up_model_descriptor);
global.nms_threshold = 0.2;
global.connect_min_subset_cnt = 3;
global.connect_min_subset_score = 0.4;
global.connect_inter_threshold = 0.01;
global.connect_inter_min_above_threshold = 8;
LOG(INFO) << "Selecting MPI model.";
} else if (net_copies[device_id].nms_num_parts==18) {
ModelDescriptorFactory::createModelDescriptor(ModelDescriptorFactory::Type::COCO_18, net_copies[device_id].up_model_descriptor);
global.nms_threshold = 0.05;
global.connect_min_subset_cnt = 3;
global.connect_min_subset_score = 0.4;
global.connect_inter_threshold = 0.050;
global.connect_inter_min_above_threshold = 9;
} else {
CHECK(0) << "Unknown number of parts! Couldn't set model";
}
//dry run
LOG(INFO) << "Dry running...";
net_copies[device_id].person_net->ForwardFrom(0);
LOG(INFO) << "Success.";
cudaMalloc(&net_copies[device_id].canvas, DISPLAY_RESOLUTION_WIDTH * DISPLAY_RESOLUTION_HEIGHT * 3 * sizeof(float));
cudaMalloc(&net_copies[device_id].joints, MAX_NUM_PARTS*3*MAX_PEOPLE * sizeof(float) );
}
void process_and_pad_image(float* target, cv::Mat oriImg, int tw, int th, bool normalize) {
int ow = oriImg.cols;
int oh = oriImg.rows;
int offset2_target = tw * th;
int padw = (tw-ow)/2;
int padh = (th-oh)/2;
//LOG(ERROR) << " padw " << padw << " padh " << padh;
CHECK_GE(padw,0) << "Image too big for target size.";
CHECK_GE(padh,0) << "Image too big for target size.";
//parallel here
unsigned char* pointer = (unsigned char*)(oriImg.data);
for(int c = 0; c < 3; c++) {
for(int y = 0; y < th; y++) {
int oy = y - padh;
for(int x = 0; x < tw; x++) {
int ox = x - padw;
if (ox>=0 && ox < ow && oy>=0 && oy < oh ) {
if (normalize)
target[c * offset2_target + y * tw + x] = float(pointer[(oy * ow + ox) * 3 + c])/256.0f - 0.5f;
else
target[c * offset2_target + y * tw + x] = float(pointer[(oy * ow + ox) * 3 + c]);
}
else {
target[c * offset2_target + y * tw + x] = 0;
}
}
}
}
}
void render(int gid, float *heatmaps /*GPU*/) {
float* centers = 0;
float* poses = net_copies[gid].joints;
double tic = get_wall_time();
if (net_copies[gid].up_model_descriptor->get_number_parts()==15) {
render_mpi_parts(net_copies[gid].canvas, DISPLAY_RESOLUTION_WIDTH, DISPLAY_RESOLUTION_HEIGHT, NET_RESOLUTION_WIDTH, NET_RESOLUTION_HEIGHT,
heatmaps, BOX_SIZE, centers, poses, net_copies[gid].num_people, global.part_to_show);
} else if (net_copies[gid].up_model_descriptor->get_number_parts()==18) {
if (global.part_to_show-1<=net_copies[gid].up_model_descriptor->get_number_parts()) {
render_coco_parts(net_copies[gid].canvas,
DISPLAY_RESOLUTION_WIDTH, DISPLAY_RESOLUTION_HEIGHT,
NET_RESOLUTION_WIDTH, NET_RESOLUTION_HEIGHT,
heatmaps, BOX_SIZE, centers, poses,
net_copies[gid].num_people, global.part_to_show, global.uistate.is_googly_eyes);
} else {
int aff_part = ((global.part_to_show-1)-net_copies[gid].up_model_descriptor->get_number_parts()-1)*2;
int num_parts_accum = 1;
if (aff_part==0) {
num_parts_accum = 19;
} else {
aff_part = aff_part-2;
}
aff_part += 1+net_copies[gid].up_model_descriptor->get_number_parts();
render_coco_aff(net_copies[gid].canvas, DISPLAY_RESOLUTION_WIDTH, DISPLAY_RESOLUTION_HEIGHT, NET_RESOLUTION_WIDTH, NET_RESOLUTION_HEIGHT,
heatmaps, BOX_SIZE, centers, poses, net_copies[gid].num_people, aff_part, num_parts_accum);
}
}
VLOG(2) << "Render time " << (get_wall_time()-tic)*1000.0 << " ms.";
}
void* getFrameFromDir(void *i) {
int global_counter = 1;
int frame_counter = 0;
cv::Mat image_uchar;
cv::Mat image_uchar_orig;
cv::Mat image_uchar_prev;
while(1) {
if (global.quit_threads) break;
// If the queue is too long, wait for a bit
if (global.input_queue.size()>10) {
usleep(10*1000.0);
continue;
}
// Keep a count of how many frames we've seen in the video
frame_counter++;
// This should probably be protected.
global.uistate.current_frame = frame_counter-1;
std::string filename = global.image_list[global.uistate.current_frame];
image_uchar_orig = cv::imread(filename.c_str(), CV_LOAD_IMAGE_COLOR);
double scale = 0;
if (image_uchar_orig.cols/(double)image_uchar_orig.rows>DISPLAY_RESOLUTION_WIDTH/(double)DISPLAY_RESOLUTION_HEIGHT) {
scale = DISPLAY_RESOLUTION_WIDTH/(double)image_uchar_orig.cols;
} else {
scale = DISPLAY_RESOLUTION_HEIGHT/(double)image_uchar_orig.rows;
}
cv::Mat M = cv::Mat::eye(2,3,CV_64F);
M.at<double>(0,0) = scale;
M.at<double>(1,1) = scale;
cv::warpAffine(image_uchar_orig, image_uchar, M,
cv::Size(DISPLAY_RESOLUTION_WIDTH, DISPLAY_RESOLUTION_HEIGHT),
CV_INTER_CUBIC,
cv::BORDER_CONSTANT, cv::Scalar(0,0,0));
// resize(image_uchar, image_uchar, cv::Size(new_width, new_height), 0, 0, CV_INTER_CUBIC);
image_uchar_prev = image_uchar;
if ( image_uchar.empty() ) continue;
Frame frame;
frame.ori_width = image_uchar_orig.cols;
frame.ori_height = image_uchar_orig.rows;
frame.index = global_counter++;
frame.video_frame_number = global.uistate.current_frame;
frame.data_for_wrap = new unsigned char [DISPLAY_RESOLUTION_HEIGHT * DISPLAY_RESOLUTION_WIDTH * 3]; //fill after process
frame.data_for_mat = new float [DISPLAY_RESOLUTION_HEIGHT * DISPLAY_RESOLUTION_WIDTH * 3];
process_and_pad_image(frame.data_for_mat, image_uchar, DISPLAY_RESOLUTION_WIDTH, DISPLAY_RESOLUTION_HEIGHT, 0);
frame.scale = scale;
//pad and transform to float
int offset = 3 * NET_RESOLUTION_HEIGHT * NET_RESOLUTION_WIDTH;
frame.data = new float [BATCH_SIZE * offset];
int target_width, target_height;
cv::Mat image_temp;
//LOG(ERROR) << "frame.index: " << frame.index;
for(int i=0; i < BATCH_SIZE; i++) {
float scale = START_SCALE - i*SCALE_GAP;
target_width = 16 * ceil(NET_RESOLUTION_WIDTH * scale /16);
target_height = 16 * ceil(NET_RESOLUTION_HEIGHT * scale /16);
CHECK_LE(target_width, NET_RESOLUTION_WIDTH);
CHECK_LE(target_height, NET_RESOLUTION_HEIGHT);
resize(image_uchar, image_temp, cv::Size(target_width, target_height), 0, 0, CV_INTER_AREA);
process_and_pad_image(frame.data + i * offset, image_temp, NET_RESOLUTION_WIDTH, NET_RESOLUTION_HEIGHT, 1);
}
frame.commit_time = get_wall_time();
frame.preprocessed_time = get_wall_time();
global.input_queue.push(frame);
// If we reach the end of a video, loop
if (frame_counter >= global.image_list.size()) {
LOG(INFO) << "Done, exiting. # frames: " << frame_counter;
// Wait until the queues are clear before exiting
while (global.input_queue.size()
|| global.output_queue.size()
|| global.output_queue_ordered.size()) {
// Should actually wait until they finish writing to disk
// This could exit before the last frame is written.
usleep(1000*1000.0);
continue;
}
global.quit_threads = true;
global.uistate.is_video_paused = true;
}
}
return nullptr;
}
void* getFrameFromCam(void *i) {
cv::VideoCapture cap;
double target_frame_time = 0;
double target_frame_rate = 0;
if (!FLAGS_image_dir.empty()) {
return getFrameFromDir(i);
}
if (FLAGS_video.empty()) {
CHECK(cap.open(FLAGS_camera)) << "Couldn't open camera " << FLAGS_camera;
cap.set(CV_CAP_PROP_FRAME_WIDTH,CAMERA_FRAME_WIDTH);
cap.set(CV_CAP_PROP_FRAME_HEIGHT,CAMERA_FRAME_HEIGHT);
} else {
CHECK(cap.open(FLAGS_video)) << "Couldn't open video file " << FLAGS_video;
target_frame_rate = cap.get(CV_CAP_PROP_FPS);
target_frame_time = 1.0/target_frame_rate;
if (FLAGS_start_frame) {
cap.set(CV_CAP_PROP_POS_FRAMES, FLAGS_start_frame);
}
}
int global_counter = 1;
int frame_counter = 0;
cv::Mat image_uchar;
cv::Mat image_uchar_orig;
cv::Mat image_uchar_prev;
double last_frame_time = -1;
while(1) {
if (global.quit_threads) {
break;
}
if (!FLAGS_video.empty() && FLAGS_no_frame_drops) {
// If the queue is too long, wait for a bit
if (global.input_queue.size()>10) {
usleep(10*1000.0);
continue;
}
}
cap >> image_uchar_orig;
// Keep a count of how many frames we've seen in the video
if (!FLAGS_video.empty()) {
if (global.uistate.seek_to_frame!=-1) {
cap.set(CV_CAP_PROP_POS_FRAMES, global.uistate.current_frame);
global.uistate.seek_to_frame = -1;
}
frame_counter = cap.get(CV_CAP_PROP_POS_FRAMES);
VLOG(3) << "Frame: " << frame_counter << " / " << cap.get(CV_CAP_PROP_FRAME_COUNT);
// This should probably be protected.
global.uistate.current_frame = frame_counter-1;
if (global.uistate.is_video_paused) {
cap.set(CV_CAP_PROP_POS_FRAMES, frame_counter-1);
frame_counter -= 1;
}
// Sleep to get the right frame rate.
double cur_frame_time = get_wall_time();
double interval = (cur_frame_time-last_frame_time);
VLOG(3) << "cur_frame_time " << (cur_frame_time);
VLOG(3) << "last_frame_time " << (last_frame_time);
VLOG(3) << "cur-last_frame_time " << (cur_frame_time - last_frame_time);
VLOG(3) << "Video target frametime " << 1.0/target_frame_time
<< " read frametime " << 1.0/interval;
if (interval<target_frame_time) {
VLOG(3) << "Sleeping for " << (target_frame_time-interval)*1000.0;
usleep((target_frame_time-interval)*1000.0*1000.0);
cur_frame_time = get_wall_time();
}
last_frame_time = cur_frame_time;
} else {
// From camera, just increase counter.
if (global.uistate.is_video_paused) {
image_uchar_orig = image_uchar_prev;
}
image_uchar_prev = image_uchar_orig;
frame_counter++;
}
// TODO: The entire scaling code should be rewritten and better matched
// to the imresize_layer. Confusingly, for the demo, there's an intermediate
// display resolution to which the original image is resized.
double scale = 0;
if (image_uchar_orig.cols/(double)image_uchar_orig.rows>DISPLAY_RESOLUTION_WIDTH/(double)DISPLAY_RESOLUTION_HEIGHT) {
scale = DISPLAY_RESOLUTION_WIDTH/(double)image_uchar_orig.cols;
} else {
scale = DISPLAY_RESOLUTION_HEIGHT/(double)image_uchar_orig.rows;
}
VLOG(4) << "Scale to DISPLAY_RESOLUTION_WIDTH/HEIGHT: " << scale;
cv::Mat M = cv::Mat::eye(2,3,CV_64F);
M.at<double>(0,0) = scale;
M.at<double>(1,1) = scale;
warpAffine(image_uchar_orig, image_uchar, M,
cv::Size(DISPLAY_RESOLUTION_WIDTH, DISPLAY_RESOLUTION_HEIGHT),
CV_INTER_CUBIC,
cv::BORDER_CONSTANT, cv::Scalar(0,0,0));
// resize(image_uchar, image_uchar, Size(new_width, new_height), 0, 0, CV_INTER_CUBIC);
image_uchar_prev = image_uchar_orig;
if ( image_uchar.empty() )
continue;
Frame frame;
frame.scale = scale;
frame.index = global_counter++;
frame.video_frame_number = global.uistate.current_frame;
frame.data_for_wrap = new unsigned char [DISPLAY_RESOLUTION_HEIGHT * DISPLAY_RESOLUTION_WIDTH * 3]; //fill after process
frame.data_for_mat = new float [DISPLAY_RESOLUTION_HEIGHT * DISPLAY_RESOLUTION_WIDTH * 3];
process_and_pad_image(frame.data_for_mat, image_uchar, DISPLAY_RESOLUTION_WIDTH, DISPLAY_RESOLUTION_HEIGHT, 0);
//pad and transform to float
int offset = 3 * NET_RESOLUTION_HEIGHT * NET_RESOLUTION_WIDTH;
frame.data = new float [BATCH_SIZE * offset];
int target_width;
int target_height;
cv::Mat image_temp;
for(int i=0; i < BATCH_SIZE; i++) {
float scale = START_SCALE - i*SCALE_GAP;
target_width = 16 * ceil(NET_RESOLUTION_WIDTH * scale /16);
target_height = 16 * ceil(NET_RESOLUTION_HEIGHT * scale /16);
CHECK_LE(target_width, NET_RESOLUTION_WIDTH);
CHECK_LE(target_height, NET_RESOLUTION_HEIGHT);
cv::resize(image_uchar, image_temp, cv::Size(target_width, target_height), 0, 0, CV_INTER_AREA);
process_and_pad_image(frame.data + i * offset, image_temp, NET_RESOLUTION_WIDTH, NET_RESOLUTION_HEIGHT, 1);
}
frame.commit_time = get_wall_time();
frame.preprocessed_time = get_wall_time();
global.input_queue.push(frame);
// If we reach the end of a video, loop
if (!FLAGS_video.empty() && frame_counter >= cap.get(CV_CAP_PROP_FRAME_COUNT)) {
if (!FLAGS_write_frames.empty()) {
LOG(INFO) << "Done, exiting. # frames: " << frame_counter;
// This is the last frame (also the last emmitted frame)
// Wait until the queues are clear before exiting
while (global.input_queue.size()
|| global.output_queue.size()
|| global.output_queue_ordered.size()) {
// Should actually wait until they finish writing to disk.
// This could exit before the last frame is written.
usleep(1000*1000.0);
continue;
}
global.quit_threads = true;
global.uistate.is_video_paused = true;
} else {
LOG(INFO) << "Looping video after " << cap.get(CV_CAP_PROP_FRAME_COUNT) << " frames";
cap.set(CV_CAP_PROP_POS_FRAMES, 0);
}
}
}
return nullptr;
}
int connectLimbs(
std::vector< std::vector<double>> &subset,
std::vector< std::vector< std::vector<double> > > &connection,
const float *heatmap_pointer,
const float *peaks,
int max_peaks,
float *joints,
ModelDescriptor *model_descriptor) {
const auto num_parts = model_descriptor->get_number_parts();
const auto limbSeq = model_descriptor->get_limb_sequence();
const auto mapIdx = model_descriptor->get_map_idx();
const auto number_limb_seq = model_descriptor->number_limb_sequence();
int SUBSET_CNT = num_parts+2;
int SUBSET_SCORE = num_parts+1;
int SUBSET_SIZE = num_parts+3;
CHECK_EQ(num_parts, 15);
CHECK_EQ(number_limb_seq, 14);
int peaks_offset = 3*(max_peaks+1);
subset.clear();
connection.clear();
for(int k = 0; k < number_limb_seq; k++) {
const float* map_x = heatmap_pointer + mapIdx[2*k] * NET_RESOLUTION_HEIGHT * NET_RESOLUTION_WIDTH;
const float* map_y = heatmap_pointer + mapIdx[2*k+1] * NET_RESOLUTION_HEIGHT * NET_RESOLUTION_WIDTH;
const float* candA = peaks + limbSeq[2*k]*peaks_offset;
const float* candB = peaks + limbSeq[2*k+1]*peaks_offset;
std::vector< std::vector<double> > connection_k;
int nA = candA[0];
int nB = candB[0];
// add parts into the subset in special case
if (nA ==0 && nB ==0) {
continue;
}
else if (nA ==0) {
for(int i = 1; i <= nB; i++) {
std::vector<double> row_vec(SUBSET_SIZE, 0);
row_vec[ limbSeq[2*k+1] ] = limbSeq[2*k+1]*peaks_offset + i*3 + 2; //store the index
row_vec[SUBSET_CNT] = 1; //last number in each row is the parts number of that person
row_vec[SUBSET_SCORE] = candB[i*3+2]; //second last number in each row is the total score
subset.push_back(row_vec);
}
continue;
}
else if (nB ==0) {
for(int i = 1; i <= nA; i++) {
std::vector<double> row_vec(SUBSET_SIZE, 0);
row_vec[ limbSeq[2*k] ] = limbSeq[2*k]*peaks_offset + i*3 + 2; //store the index
row_vec[SUBSET_CNT] = 1; //last number in each row is the parts number of that person
row_vec[SUBSET_SCORE] = candA[i*3+2]; //second last number in each row is the total score
subset.push_back(row_vec);
}
continue;
}
std::vector< std::vector<double>> temp;
const int num_inter = 10;
for(int i = 1; i <= nA; i++) {
for(int j = 1; j <= nB; j++) {
float s_x = candA[i*3];
float s_y = candA[i*3+1];
float d_x = candB[j*3] - candA[i*3];
float d_y = candB[j*3+1] - candA[i*3+1];
float norm_vec = sqrt( pow(d_x,2) + pow(d_y,2) );
if (norm_vec<1e-6) {
continue;
}
float vec_x = d_x/norm_vec;
float vec_y = d_y/norm_vec;
float sum = 0;
int count = 0;
for(int lm=0; lm < num_inter; lm++) {
int my = round(s_y + lm*d_y/num_inter);
int mx = round(s_x + lm*d_x/num_inter);
int idx = my * NET_RESOLUTION_WIDTH + mx;
float score = (vec_x*map_x[idx] + vec_y*map_y[idx]);
if (score > global.connect_inter_threshold) {
sum = sum + score;
count ++;
}
}
//float score = sum / count; // + std::min((130/dist-1),0.f)
if (count > global.connect_inter_min_above_threshold) {//num_inter*0.8) { //thre/2
// parts score + cpnnection score
std::vector<double> row_vec(4, 0);
row_vec[3] = sum/count + candA[i*3+2] + candB[j*3+2]; //score_all
row_vec[2] = sum/count;
row_vec[0] = i;
row_vec[1] = j;
temp.push_back(row_vec);
}
}
}
//** select the top num connection, assuming that each part occur only once
// sort rows in descending order based on parts + connection score
if (temp.size() > 0)
std::sort(temp.begin(), temp.end(), ColumnCompare());
int num = std::min(nA, nB);
int cnt = 0;
std::vector<int> occurA(nA, 0);
std::vector<int> occurB(nB, 0);
for(int row =0; row < temp.size(); row++) {
if (cnt==num) {
break;
}
else{
int i = int(temp[row][0]);
int j = int(temp[row][1]);
float score = temp[row][2];
if ( occurA[i-1] == 0 && occurB[j-1] == 0 ) { // && score> (1+thre)
std::vector<double> row_vec(3, 0);
row_vec[0] = limbSeq[2*k]*peaks_offset + i*3 + 2;
row_vec[1] = limbSeq[2*k+1]*peaks_offset + j*3 + 2;
row_vec[2] = score;
connection_k.push_back(row_vec);
cnt = cnt+1;
occurA[i-1] = 1;
occurB[j-1] = 1;
}
}
}
if (k==0) {
std::vector<double> row_vec(num_parts+3, 0);
for(int i = 0; i < connection_k.size(); i++) {
double indexA = connection_k[i][0];
double indexB = connection_k[i][1];
row_vec[limbSeq[0]] = indexA;
row_vec[limbSeq[1]] = indexB;
row_vec[SUBSET_CNT] = 2;
// add the score of parts and the connection
row_vec[SUBSET_SCORE] = peaks[int(indexA)] + peaks[int(indexB)] + connection_k[i][2];
subset.push_back(row_vec);
}
}
else{
if (connection_k.size()==0) {
continue;
}
// A is already in the subset, find its connection B
for(int i = 0; i < connection_k.size(); i++) {
int num = 0;
double indexA = connection_k[i][0];
double indexB = connection_k[i][1];
for(int j = 0; j < subset.size(); j++) {
if (subset[j][limbSeq[2*k]] == indexA) {
subset[j][limbSeq[2*k+1]] = indexB;
num = num+1;
subset[j][SUBSET_CNT] = subset[j][SUBSET_CNT] + 1;
subset[j][SUBSET_SCORE] = subset[j][SUBSET_SCORE] + peaks[int(indexB)] + connection_k[i][2];
}
}
// if can not find partA in the subset, create a new subset
if (num==0) {
std::vector<double> row_vec(SUBSET_SIZE, 0);
row_vec[limbSeq[2*k]] = indexA;
row_vec[limbSeq[2*k+1]] = indexB;
row_vec[SUBSET_CNT] = 2;
row_vec[SUBSET_SCORE] = peaks[int(indexA)] + peaks[int(indexB)] + connection_k[i][2];
subset.push_back(row_vec);
}
}
}
}
//** joints by deleting some rows of subset which has few parts occur
int cnt = 0;
for(int i = 0; i < subset.size(); i++) {
if (subset[i][SUBSET_CNT]>=global.connect_min_subset_cnt && (subset[i][SUBSET_SCORE]/subset[i][SUBSET_CNT])>global.connect_min_subset_score) {
for(int j = 0; j < num_parts; j++) {
int idx = int(subset[i][j]);
if (idx) {
joints[cnt*num_parts*3 + j*3 +2] = peaks[idx];
joints[cnt*num_parts*3 + j*3 +1] = peaks[idx-1] * DISPLAY_RESOLUTION_HEIGHT/ (float)NET_RESOLUTION_HEIGHT;
joints[cnt*num_parts*3 + j*3] = peaks[idx-2] * DISPLAY_RESOLUTION_WIDTH/ (float)NET_RESOLUTION_WIDTH;
}
else{
joints[cnt*num_parts*3 + j*3 +2] = 0;
joints[cnt*num_parts*3 + j*3 +1] = 0;
joints[cnt*num_parts*3 + j*3] = 0;
}
}
cnt++;
if (cnt==MAX_PEOPLE) break;
}
}
return cnt;
}
int distanceThresholdPeaks(const float *in_peaks, int max_peaks,
float *peaks, ModelDescriptor *model_descriptor) {
// Post-process peaks to remove those which are within sqrt(dist_threshold2)
// of each other.
const auto num_parts = model_descriptor->get_number_parts();
const float dist_threshold2 = 6*6;
int peaks_offset = 3*(max_peaks+1);
int total_peaks = 0;
for(int p = 0; p < num_parts; p++) {
const float *pipeaks = in_peaks + p*peaks_offset;
float *popeaks = peaks + p*peaks_offset;
int num_in_peaks = int(pipeaks[0]);
int num_out_peaks = 0; // Actual number of peak count
for (int c1=0;c1<num_in_peaks;c1++) {
float x1 = pipeaks[(c1+1)*3+0];
float y1 = pipeaks[(c1+1)*3+1];
float s1 = pipeaks[(c1+1)*3+2];
bool keep = true;
for (int c2=0;c2<num_out_peaks;c2++) {
float x2 = popeaks[(c2+1)*3+0];
float y2 = popeaks[(c2+1)*3+1];
float s2 = popeaks[(c2+1)*3+2];
float dist2 = (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2);
if (dist2<dist_threshold2) {
// This peak is too close to a peak already in the output buffer
// so don't add it.
keep = false;
if (s1>s2) {
// It's better than the one in the output buffer
// so we swap it.
popeaks[(c2+1)*3+0] = x1;
popeaks[(c2+1)*3+1] = y1;
popeaks[(c2+1)*3+2] = s1;
}
}
}
if (keep && num_out_peaks<max_peaks) {
// We don't already have a better peak within the threshold distance
popeaks[(num_out_peaks+1)*3+0] = x1;
popeaks[(num_out_peaks+1)*3+1] = y1;
popeaks[(num_out_peaks+1)*3+2] = s1;
num_out_peaks++;
}
}
// if (num_in_peaks!=num_out_peaks) {
//LOG(INFO) << "Part: " << p << " in peaks: "<< num_in_peaks << " out: " << num_out_peaks;
// }
popeaks[0] = float(num_out_peaks);
total_peaks += num_out_peaks;
}
return total_peaks;
}
int connectLimbsCOCO(
std::vector< std::vector<double>> &subset,
std::vector< std::vector< std::vector<double> > > &connection,
const float *heatmap_pointer,
const float *in_peaks,
int max_peaks,
float *joints,
ModelDescriptor *model_descriptor) {
/* Parts Connection ---------------------------------------*/
const auto num_parts = model_descriptor->get_number_parts();
const auto limbSeq = model_descriptor->get_limb_sequence();
const auto mapIdx = model_descriptor->get_map_idx();
const auto number_limb_seq = model_descriptor->number_limb_sequence();
CHECK_EQ(num_parts, 18) << "Wrong connection function for model";
CHECK_EQ(number_limb_seq, 19) << "Wrong connection function for model";
int SUBSET_CNT = num_parts+2;
int SUBSET_SCORE = num_parts+1;
int SUBSET_SIZE = num_parts+3;
const int peaks_offset = 3*(max_peaks+1);
const float *peaks = in_peaks;
subset.clear();
connection.clear();
for(int k = 0; k < number_limb_seq; k++) {
const float* map_x = heatmap_pointer + mapIdx[2*k] * NET_RESOLUTION_HEIGHT * NET_RESOLUTION_WIDTH;
const float* map_y = heatmap_pointer + mapIdx[2*k+1] * NET_RESOLUTION_HEIGHT * NET_RESOLUTION_WIDTH;
const float* candA = peaks + limbSeq[2*k]*peaks_offset;
const float* candB = peaks + limbSeq[2*k+1]*peaks_offset;
std::vector< std::vector<double> > connection_k;
int nA = candA[0];
int nB = candB[0];
// add parts into the subset in special case
if (nA ==0 && nB ==0) {
continue;
} else if (nA ==0) {
for(int i = 1; i <= nB; i++) {
int num = 0;
int indexB = limbSeq[2*k+1];
for(int j = 0; j < subset.size(); j++) {
int off = limbSeq[2*k+1]*peaks_offset + i*3 + 2;
if (subset[j][indexB] == off) {
num = num+1;
continue;
}
}
if (num!=0) {
//LOG(INFO) << " else if (nA==0) shouldn't have any nB already assigned?";
} else {
std::vector<double> row_vec(SUBSET_SIZE, 0);
row_vec[ limbSeq[2*k+1] ] = limbSeq[2*k+1]*peaks_offset + i*3 + 2; //store the index
row_vec[SUBSET_CNT] = 1; //last number in each row is the parts number of that person
row_vec[SUBSET_SCORE] = candB[i*3+2]; //second last number in each row is the total score
subset.push_back(row_vec);
}
//LOG(INFO) << "nA==0 New subset on part " << k << " subsets: " << subset.size();
}
continue;
} else if (nB ==0) {
for(int i = 1; i <= nA; i++) {
int num = 0;
int indexA = limbSeq[2*k];
for(int j = 0; j < subset.size(); j++) {
int off = limbSeq[2*k]*peaks_offset + i*3 + 2;
if (subset[j][indexA] == off) {
num = num+1;
continue;
}
}
if (num==0) {
std::vector<double> row_vec(SUBSET_SIZE, 0);
row_vec[ limbSeq[2*k] ] = limbSeq[2*k]*peaks_offset + i*3 + 2; //store the index
row_vec[SUBSET_CNT] = 1; //last number in each row is the parts number of that person
row_vec[SUBSET_SCORE] = candA[i*3+2]; //second last number in each row is the total score
subset.push_back(row_vec);
//LOG(INFO) << "nB==0 New subset on part " << k << " subsets: " << subset.size();
} else {
//LOG(INFO) << "nB==0 discarded would have added";
}
}
continue;
}
std::vector< std::vector<double>> temp;
const int num_inter = 10;
for(int i = 1; i <= nA; i++) {
for(int j = 1; j <= nB; j++) {
float s_x = candA[i*3];
float s_y = candA[i*3+1];
float d_x = candB[j*3] - candA[i*3];
float d_y = candB[j*3+1] - candA[i*3+1];
float norm_vec = sqrt( d_x*d_x + d_y*d_y );
if (norm_vec<1e-6) {
// The peaks are coincident. Don't connect them.
continue;
}
float vec_x = d_x/norm_vec;
float vec_y = d_y/norm_vec;
float sum = 0;
int count = 0;
for(int lm=0; lm < num_inter; lm++) {
int my = round(s_y + lm*d_y/num_inter);
int mx = round(s_x + lm*d_x/num_inter);
if (mx>=NET_RESOLUTION_WIDTH) {
//LOG(ERROR) << "mx " << mx << "out of range";
mx = NET_RESOLUTION_WIDTH-1;
}
if (my>=NET_RESOLUTION_HEIGHT) {
//LOG(ERROR) << "my " << my << "out of range";
my = NET_RESOLUTION_HEIGHT-1;
}
CHECK_GE(mx,0);
CHECK_GE(my,0);
int idx = my * NET_RESOLUTION_WIDTH + mx;
float score = (vec_x*map_x[idx] + vec_y*map_y[idx]);
if (score > global.connect_inter_threshold) {
sum = sum + score;
count ++;
}
}
//float score = sum / count; // + std::min((130/dist-1),0.f)
if (count > global.connect_inter_min_above_threshold) {//num_inter*0.8) { //thre/2
// parts score + cpnnection score
std::vector<double> row_vec(4, 0);
row_vec[3] = sum/count + candA[i*3+2] + candB[j*3+2]; //score_all
row_vec[2] = sum/count;
row_vec[0] = i;
row_vec[1] = j;
temp.push_back(row_vec);
}
}
}
//** select the top num connection, assuming that each part occur only once
// sort rows in descending order based on parts + connection score
if (temp.size() > 0)
std::sort(temp.begin(), temp.end(), ColumnCompare());
int num = std::min(nA, nB);
int cnt = 0;
std::vector<int> occurA(nA, 0);
std::vector<int> occurB(nB, 0);
for(int row =0; row < temp.size(); row++) {
if (cnt==num) {
break;
}
else{
int i = int(temp[row][0]);
int j = int(temp[row][1]);
float score = temp[row][2];
if ( occurA[i-1] == 0 && occurB[j-1] == 0 ) { // && score> (1+thre)
std::vector<double> row_vec(3, 0);
row_vec[0] = limbSeq[2*k]*peaks_offset + i*3 + 2;
row_vec[1] = limbSeq[2*k+1]*peaks_offset + j*3 + 2;
row_vec[2] = score;
connection_k.push_back(row_vec);
cnt = cnt+1;
occurA[i-1] = 1;
occurB[j-1] = 1;
}
}
}
//** cluster all the joints candidates into subset based on the part connection
// initialize first body part connection 15&16
if (k==0) {
std::vector<double> row_vec(num_parts+3, 0);
for(int i = 0; i < connection_k.size(); i++) {
double indexB = connection_k[i][1];
double indexA = connection_k[i][0];
row_vec[limbSeq[0]] = indexA;
row_vec[limbSeq[1]] = indexB;
row_vec[SUBSET_CNT] = 2;
// add the score of parts and the connection
row_vec[SUBSET_SCORE] = peaks[int(indexA)] + peaks[int(indexB)] + connection_k[i][2];
//LOG(INFO) << "New subset on part " << k << " subsets: " << subset.size();
subset.push_back(row_vec);
}
}/* else if (k==17 || k==18) { // TODO: Check k numbers?
// %add 15 16 connection
for(int i = 0; i < connection_k.size(); i++) {
double indexA = connection_k[i][0];