Home | History | Annotate | Download | only in object_tracking
      1 /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
      2 
      3 Licensed under the Apache License, Version 2.0 (the "License");
      4 you may not use this file except in compliance with the License.
      5 You may obtain a copy of the License at
      6 
      7     http://www.apache.org/licenses/LICENSE-2.0
      8 
      9 Unless required by applicable law or agreed to in writing, software
     10 distributed under the License is distributed on an "AS IS" BASIS,
     11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12 See the License for the specific language governing permissions and
     13 limitations under the License.
     14 ==============================================================================*/
     15 
     16 #include "tensorflow/examples/android/jni/object_tracking/tracked_object.h"
     17 
     18 namespace tf_tracking {
     19 
     20 static const float kInitialDistance = 20.0f;
     21 
     22 static void InitNormalized(const Image<uint8_t>& src_image,
     23                            const BoundingBox& position,
     24                            Image<float>* const dst_image) {
     25   BoundingBox scaled_box(position);
     26   CopyArea(src_image, scaled_box, dst_image);
     27   NormalizeImage(dst_image);
     28 }
     29 
     30 TrackedObject::TrackedObject(const std::string& id, const Image<uint8_t>& image,
     31                              const BoundingBox& bounding_box,
     32                              ObjectModelBase* const model)
     33     : id_(id),
     34       last_known_position_(bounding_box),
     35       last_detection_position_(bounding_box),
     36       position_last_computed_time_(-1),
     37       object_model_(model),
     38       last_detection_thumbnail_(kNormalizedThumbnailSize,
     39                                 kNormalizedThumbnailSize),
     40       last_frame_thumbnail_(kNormalizedThumbnailSize, kNormalizedThumbnailSize),
     41       tracked_correlation_(0.0f),
     42       tracked_match_score_(0.0),
     43       num_consecutive_frames_below_threshold_(0),
     44       allowable_detection_distance_(Square(kInitialDistance)) {
     45   InitNormalized(image, bounding_box, &last_detection_thumbnail_);
     46 }
     47 
     48 TrackedObject::~TrackedObject() {}
     49 
     50 void TrackedObject::UpdatePosition(const BoundingBox& new_position,
     51                                    const int64_t timestamp,
     52                                    const ImageData& image_data,
     53                                    const bool authoratative) {
     54   last_known_position_ = new_position;
     55   position_last_computed_time_ = timestamp;
     56 
     57   InitNormalized(*image_data.GetImage(), new_position, &last_frame_thumbnail_);
     58 
     59   const float last_localization_correlation = ComputeCrossCorrelation(
     60       last_detection_thumbnail_.data(),
     61       last_frame_thumbnail_.data(),
     62       last_frame_thumbnail_.data_size_);
     63   LOGV("Tracked correlation to last localization:   %.6f",
     64        last_localization_correlation);
     65 
     66   // Correlation to object model, if it exists.
     67   if (object_model_ != NULL) {
     68     tracked_correlation_ =
     69         object_model_->GetMaxCorrelation(last_frame_thumbnail_);
     70     LOGV("Tracked correlation to model:               %.6f",
     71          tracked_correlation_);
     72 
     73     tracked_match_score_ =
     74         object_model_->GetMatchScore(new_position, image_data);
     75     LOGV("Tracked match score with model:             %.6f",
     76          tracked_match_score_.value);
     77   } else {
     78     // If there's no model to check against, set the tracked correlation to
     79     // simply be the correlation to the last set position.
     80     tracked_correlation_ = last_localization_correlation;
     81     tracked_match_score_ = MatchScore(0.0f);
     82   }
     83 
     84   // Determine if it's still being tracked.
     85   if (tracked_correlation_ >= kMinimumCorrelationForTracking &&
     86       tracked_match_score_ >= kMinimumMatchScore) {
     87     num_consecutive_frames_below_threshold_ = 0;
     88 
     89     if (object_model_ != NULL) {
     90       object_model_->TrackStep(last_known_position_, *image_data.GetImage(),
     91                                *image_data.GetIntegralImage(), authoratative);
     92     }
     93   } else if (tracked_match_score_ < kMatchScoreForImmediateTermination) {
     94     if (num_consecutive_frames_below_threshold_ < 1000) {
     95       LOGD("Tracked match score is way too low (%.6f), aborting track.",
     96            tracked_match_score_.value);
     97     }
     98 
     99     // Add an absurd amount of missed frames so that all heuristics will
    100     // consider it a lost track.
    101     num_consecutive_frames_below_threshold_ += 1000;
    102 
    103     if (object_model_ != NULL) {
    104       object_model_->TrackLost();
    105     }
    106   } else {
    107     ++num_consecutive_frames_below_threshold_;
    108     allowable_detection_distance_ *= 1.1f;
    109   }
    110 }
    111 
    112 void TrackedObject::OnDetection(ObjectModelBase* const model,
    113                                 const BoundingBox& detection_position,
    114                                 const MatchScore match_score,
    115                                 const int64_t timestamp,
    116                                 const ImageData& image_data) {
    117   const float overlap = detection_position.PascalScore(last_known_position_);
    118   if (overlap > kPositionOverlapThreshold) {
    119     // If the position agreement with the current tracked position is good
    120     // enough, lock all the current unlocked examples.
    121     object_model_->TrackConfirmed();
    122     num_consecutive_frames_below_threshold_ = 0;
    123   }
    124 
    125   // Before relocalizing, make sure the new proposed position is better than
    126   // the existing position by a small amount to prevent thrashing.
    127   if (match_score <= tracked_match_score_ + kMatchScoreBuffer) {
    128     LOGI("Not relocalizing since new match is worse: %.6f < %.6f + %.6f",
    129          match_score.value, tracked_match_score_.value,
    130          kMatchScoreBuffer.value);
    131     return;
    132   }
    133 
    134   LOGI("Relocalizing! From (%.1f, %.1f)[%.1fx%.1f] to "
    135        "(%.1f, %.1f)[%.1fx%.1f]:   %.6f > %.6f",
    136        last_known_position_.left_, last_known_position_.top_,
    137        last_known_position_.GetWidth(), last_known_position_.GetHeight(),
    138        detection_position.left_, detection_position.top_,
    139        detection_position.GetWidth(), detection_position.GetHeight(),
    140        match_score.value, tracked_match_score_.value);
    141 
    142   if (overlap < kPositionOverlapThreshold) {
    143     // The path might be good, it might be bad, but it's no longer a path
    144     // since we're moving the box to a new position, so just nuke it from
    145     // orbit to be safe.
    146     object_model_->TrackLost();
    147   }
    148 
    149   object_model_ = model;
    150 
    151   // Reset the last detected appearance.
    152   InitNormalized(
    153       *image_data.GetImage(), detection_position, &last_detection_thumbnail_);
    154 
    155   num_consecutive_frames_below_threshold_ = 0;
    156   last_detection_position_ = detection_position;
    157 
    158   UpdatePosition(detection_position, timestamp, image_data, false);
    159   allowable_detection_distance_ = Square(kInitialDistance);
    160 }
    161 
    162 }  // namespace tf_tracking
    163