-
Notifications
You must be signed in to change notification settings - Fork 261
/
CVTracker.cpp
374 lines (305 loc) · 11.5 KB
/
CVTracker.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
/**
* @file
* @brief Track an object selected by the user
* @author Jonathan Thomas <jonathan@openshot.org>
*
* @ref License
*/
/* LICENSE
*
* Copyright (c) 2008-2019 OpenShot Studios, LLC
* <http://www.openshotstudios.com/>. This file is part of
* OpenShot Library (libopenshot), an open-source project dedicated to
* delivering high quality video editing and animation solutions to the
* world. For more information visit <http://www.openshot.org/>.
*
* OpenShot Library (libopenshot) is free software: you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* OpenShot Library (libopenshot) is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with OpenShot Library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "CVTracker.h"
#include <google/protobuf/util/time_util.h>
using namespace std;
using namespace openshot;
using google::protobuf::util::TimeUtil;
// Constructor
CVTracker::CVTracker(std::string processInfoJson, ProcessingController &processingController)
: processingController(&processingController), json_interval(false){
SetJson(processInfoJson);
start = 1;
end = 1;
}
// Set desirable tracker method
cv::Ptr<cv::Tracker> CVTracker::selectTracker(std::string trackerType){
cv::Ptr<cv::Tracker> t;
if (trackerType == "BOOSTING")
t = cv::TrackerBoosting::create();
if (trackerType == "MIL")
t = cv::TrackerMIL::create();
if (trackerType == "KCF")
t = cv::TrackerKCF::create();
if (trackerType == "TLD")
t = cv::TrackerTLD::create();
if (trackerType == "MEDIANFLOW")
t = cv::TrackerMedianFlow::create();
if (trackerType == "MOSSE")
t = cv::TrackerMOSSE::create();
if (trackerType == "CSRT")
t = cv::TrackerCSRT::create();
return t;
}
// Track object in the hole clip or in a given interval
void CVTracker::trackClip(openshot::Clip& video, size_t _start, size_t _end, bool process_interval){
video.Open();
if(!json_interval){
start = _start; end = _end;
if(!process_interval || end <= 1 || end-start == 0){
// Get total number of frames in video
start = (int)(video.Start() * video.Reader()->info.fps.ToFloat()) + 1;
end = (int)(video.End() * video.Reader()->info.fps.ToFloat()) + 1;
}
}
else{
start = (int)(start + video.Start() * video.Reader()->info.fps.ToFloat()) + 1;
end = (int)(video.End() * video.Reader()->info.fps.ToFloat()) + 1;
}
if(error){
return;
}
processingController->SetError(false, "");
bool trackerInit = false;
size_t frame;
// Loop through video
for (frame = start; frame <= end; frame++)
{
// Stop the feature tracker process
if(processingController->ShouldStop()){
return;
}
size_t frame_number = frame;
// Get current frame
std::shared_ptr<openshot::Frame> f = video.GetFrame(frame_number);
// Grab OpenCV Mat image
cv::Mat cvimage = f->GetImageCV();
if(frame == start){
// Take the normalized inital bounding box and multiply to the current video shape
bbox = cv::Rect2d(bbox.x*cvimage.cols,bbox.y*cvimage.rows,bbox.width*cvimage.cols,
bbox.height*cvimage.rows);
}
// Pass the first frame to initialize the tracker
if(!trackerInit){
// Initialize the tracker
initTracker(cvimage, frame_number);
trackerInit = true;
}
else{
// Update the object tracker according to frame
trackerInit = trackFrame(cvimage, frame_number);
// Draw box on image
FrameData fd = GetTrackedData(frame_number);
}
// Update progress
processingController->SetProgress(uint(100*(frame_number-start)/(end-start)));
}
}
// Initialize the tracker
bool CVTracker::initTracker(cv::Mat &frame, size_t frameId){
// Create new tracker object
tracker = selectTracker(trackerType);
// Correct if bounding box contains negative proportions (width and/or height < 0)
if(bbox.width < 0){
bbox.x = bbox.x - abs(bbox.width);
bbox.width = abs(bbox.width);
}
if(bbox.height < 0){
bbox.y = bbox.y - abs(bbox.height);
bbox.height = abs(bbox.height);
}
// Initialize tracker
tracker->init(frame, bbox);
float fw = frame.size().width;
float fh = frame.size().height;
// Add new frame data
trackedDataById[frameId] = FrameData(frameId, 0, (bbox.x)/fw,
(bbox.y)/fh,
(bbox.x+bbox.width)/fw,
(bbox.y+bbox.height)/fh);
return true;
}
// Update the object tracker according to frame
bool CVTracker::trackFrame(cv::Mat &frame, size_t frameId){
// Update the tracking result
bool ok = tracker->update(frame, bbox);
// Add frame number and box coords if tracker finds the object
// Otherwise add only frame number
if (ok)
{
float fw = frame.size().width;
float fh = frame.size().height;
cv::Rect2d filtered_box = filter_box_jitter(frameId);
// Add new frame data
trackedDataById[frameId] = FrameData(frameId, 0, (filtered_box.x)/fw,
(filtered_box.y)/fh,
(filtered_box.x+filtered_box.width)/fw,
(filtered_box.y+filtered_box.height)/fh);
}
else
{
// Copy the last frame data if the tracker get lost
trackedDataById[frameId] = trackedDataById[frameId-1];
}
return ok;
}
cv::Rect2d CVTracker::filter_box_jitter(size_t frameId){
// get tracked data for the previous frame
float last_box_width = trackedDataById[frameId-1].x2 - trackedDataById[frameId-1].x1;
float last_box_height = trackedDataById[frameId-1].y2 - trackedDataById[frameId-1].y1;
float curr_box_width = bbox.width;
float curr_box_height = bbox.height;
// keep the last width and height if the difference is less than 1%
float threshold = 0.01;
cv::Rect2d filtered_box = bbox;
if(std::abs(1-(curr_box_width/last_box_width)) <= threshold){
filtered_box.width = last_box_width;
}
if(std::abs(1-(curr_box_height/last_box_height)) <= threshold){
filtered_box.height = last_box_height;
}
return filtered_box;
}
bool CVTracker::SaveTrackedData(){
// Create tracker message
pb_tracker::Tracker trackerMessage;
// Iterate over all frames data and save in protobuf message
for(std::map<size_t,FrameData>::iterator it=trackedDataById.begin(); it!=trackedDataById.end(); ++it){
FrameData fData = it->second;
pb_tracker::Frame* pbFrameData;
AddFrameDataToProto(trackerMessage.add_frame(), fData);
}
// Add timestamp
*trackerMessage.mutable_last_updated() = TimeUtil::SecondsToTimestamp(time(NULL));
{
// Write the new message to disk.
std::fstream output(protobuf_data_path, ios::out | ios::trunc | ios::binary);
if (!trackerMessage.SerializeToOstream(&output)) {
cerr << "Failed to write protobuf message." << endl;
return false;
}
}
// Delete all global objects allocated by libprotobuf.
google::protobuf::ShutdownProtobufLibrary();
return true;
}
// Add frame tracked data into protobuf message.
void CVTracker::AddFrameDataToProto(pb_tracker::Frame* pbFrameData, FrameData& fData) {
// Save frame number and rotation
pbFrameData->set_id(fData.frame_id);
pbFrameData->set_rotation(0);
pb_tracker::Frame::Box* box = pbFrameData->mutable_bounding_box();
// Save bounding box data
box->set_x1(fData.x1);
box->set_y1(fData.y1);
box->set_x2(fData.x2);
box->set_y2(fData.y2);
}
// Get tracker info for the desired frame
FrameData CVTracker::GetTrackedData(size_t frameId){
// Check if the tracker info for the requested frame exists
if ( trackedDataById.find(frameId) == trackedDataById.end() ) {
return FrameData();
} else {
return trackedDataById[frameId];
}
}
// Load JSON string into this object
void CVTracker::SetJson(const std::string value) {
// Parse JSON string into JSON objects
try
{
const Json::Value root = openshot::stringToJson(value);
// Set all values that match
SetJsonValue(root);
}
catch (const std::exception& e)
{
// Error parsing JSON (or missing keys)
throw openshot::InvalidJSON("JSON is invalid (missing keys or invalid data types)");
}
}
// Load Json::Value into this object
void CVTracker::SetJsonValue(const Json::Value root) {
// Set data from Json (if key is found)
if (!root["protobuf_data_path"].isNull()){
protobuf_data_path = (root["protobuf_data_path"].asString());
}
if (!root["tracker-type"].isNull()){
trackerType = (root["tracker-type"].asString());
}
if (!root["region"].isNull()){
double x = root["region"]["normalized_x"].asDouble();
double y = root["region"]["normalized_y"].asDouble();
double w = root["region"]["normalized_width"].asDouble();
double h = root["region"]["normalized_height"].asDouble();
cv::Rect2d prev_bbox(x,y,w,h);
bbox = prev_bbox;
}
else{
processingController->SetError(true, "No initial bounding box selected");
error = true;
}
if (!root["region"]["first-frame"].isNull()){
start = root["region"]["first-frame"].asInt64();
json_interval = true;
}
else{
processingController->SetError(true, "No first-frame");
error = true;
}
}
/*
||||||||||||||||||||||||||||||||||||||||||||||||||
ONLY FOR MAKE TEST
||||||||||||||||||||||||||||||||||||||||||||||||||
*/
// Load protobuf data file
bool CVTracker::_LoadTrackedData(){
// Create tracker message
pb_tracker::Tracker trackerMessage;
{
// Read the existing tracker message.
fstream input(protobuf_data_path, ios::in | ios::binary);
if (!trackerMessage.ParseFromIstream(&input)) {
cerr << "Failed to parse protobuf message." << endl;
return false;
}
}
// Make sure the trackedData is empty
trackedDataById.clear();
// Iterate over all frames of the saved message
for (size_t i = 0; i < trackerMessage.frame_size(); i++) {
const pb_tracker::Frame& pbFrameData = trackerMessage.frame(i);
// Load frame and rotation data
size_t id = pbFrameData.id();
float rotation = pbFrameData.rotation();
// Load bounding box data
const pb_tracker::Frame::Box& box = pbFrameData.bounding_box();
float x1 = box.x1();
float y1 = box.y1();
float x2 = box.x2();
float y2 = box.y2();
// Assign data to tracker map
trackedDataById[id] = FrameData(id, rotation, x1, y1, x2, y2);
}
// Delete all global objects allocated by libprotobuf.
google::protobuf::ShutdownProtobufLibrary();
return true;
}