Brian Silverman | 4770c7d | 2020-02-17 20:34:42 -0800 | [diff] [blame] | 1 | #include <opencv2/calib3d.hpp> |
Brian Silverman | 967e5df | 2020-02-09 16:43:34 -0800 | [diff] [blame] | 2 | #include <opencv2/features2d.hpp> |
| 3 | #include <opencv2/imgproc.hpp> |
| 4 | |
Brian Silverman | 9dd793b | 2020-01-31 23:52:21 -0800 | [diff] [blame] | 5 | #include "aos/events/shm_event_loop.h" |
Brian Silverman | 4770c7d | 2020-02-17 20:34:42 -0800 | [diff] [blame] | 6 | #include "aos/flatbuffer_merge.h" |
Brian Silverman | 9dd793b | 2020-01-31 23:52:21 -0800 | [diff] [blame] | 7 | #include "aos/init.h" |
Brian Silverman | 4770c7d | 2020-02-17 20:34:42 -0800 | [diff] [blame] | 8 | #include "aos/network/team_number.h" |
Brian Silverman | 9dd793b | 2020-01-31 23:52:21 -0800 | [diff] [blame] | 9 | |
Brian Silverman | 967e5df | 2020-02-09 16:43:34 -0800 | [diff] [blame] | 10 | #include "y2020/vision/sift/sift971.h" |
| 11 | #include "y2020/vision/sift/sift_generated.h" |
| 12 | #include "y2020/vision/sift/sift_training_generated.h" |
Jim Ostrowski | ad5d8a7 | 2020-02-28 00:15:26 -0800 | [diff] [blame] | 13 | #include "y2020/vision/tools/python_code/sift_training_data.h" |
Brian Silverman | 9dd793b | 2020-01-31 23:52:21 -0800 | [diff] [blame] | 14 | #include "y2020/vision/v4l2_reader.h" |
Brian Silverman | 967e5df | 2020-02-09 16:43:34 -0800 | [diff] [blame] | 15 | #include "y2020/vision/vision_generated.h" |
Brian Silverman | 9dd793b | 2020-01-31 23:52:21 -0800 | [diff] [blame] | 16 | |
| 17 | namespace frc971 { |
| 18 | namespace vision { |
| 19 | namespace { |
| 20 | |
Brian Silverman | 967e5df | 2020-02-09 16:43:34 -0800 | [diff] [blame] | 21 | class CameraReader { |
| 22 | public: |
| 23 | CameraReader(aos::EventLoop *event_loop, |
| 24 | const sift::TrainingData *training_data, V4L2Reader *reader, |
| 25 | cv::FlannBasedMatcher *matcher) |
| 26 | : event_loop_(event_loop), |
| 27 | training_data_(training_data), |
Brian Silverman | 4770c7d | 2020-02-17 20:34:42 -0800 | [diff] [blame] | 28 | camera_calibration_(FindCameraCalibration()), |
Brian Silverman | 967e5df | 2020-02-09 16:43:34 -0800 | [diff] [blame] | 29 | reader_(reader), |
| 30 | matcher_(matcher), |
| 31 | image_sender_(event_loop->MakeSender<CameraImage>("/camera")), |
| 32 | result_sender_( |
| 33 | event_loop->MakeSender<sift::ImageMatchResult>("/camera")), |
Jim Ostrowski | ad5d8a7 | 2020-02-28 00:15:26 -0800 | [diff] [blame] | 34 | detailed_result_sender_( |
| 35 | event_loop->MakeSender<sift::ImageMatchResult>("/camera/detailed")), |
Brian Silverman | 967e5df | 2020-02-09 16:43:34 -0800 | [diff] [blame] | 36 | read_image_timer_(event_loop->AddTimer([this]() { |
| 37 | ReadImage(); |
| 38 | read_image_timer_->Setup(event_loop_->monotonic_now()); |
| 39 | })) { |
| 40 | CopyTrainingFeatures(); |
| 41 | // Technically we don't need to do this, but doing it now avoids the first |
| 42 | // match attempt being slow. |
| 43 | matcher_->train(); |
| 44 | |
| 45 | event_loop->OnRun( |
| 46 | [this]() { read_image_timer_->Setup(event_loop_->monotonic_now()); }); |
| 47 | } |
| 48 | |
| 49 | private: |
Brian Silverman | 4770c7d | 2020-02-17 20:34:42 -0800 | [diff] [blame] | 50 | const sift::CameraCalibration *FindCameraCalibration() const; |
| 51 | |
Brian Silverman | 967e5df | 2020-02-09 16:43:34 -0800 | [diff] [blame] | 52 | // Copies the information from training_data_ into matcher_. |
| 53 | void CopyTrainingFeatures(); |
| 54 | // Processes an image (including sending the results). |
| 55 | void ProcessImage(const CameraImage &image); |
| 56 | // Reads an image, and then performs all of our processing on it. |
| 57 | void ReadImage(); |
| 58 | |
| 59 | flatbuffers::Offset< |
| 60 | flatbuffers::Vector<flatbuffers::Offset<sift::ImageMatch>>> |
| 61 | PackImageMatches(flatbuffers::FlatBufferBuilder *fbb, |
| 62 | const std::vector<std::vector<cv::DMatch>> &matches); |
| 63 | flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<sift::Feature>>> |
| 64 | PackFeatures(flatbuffers::FlatBufferBuilder *fbb, |
| 65 | const std::vector<cv::KeyPoint> &keypoints, |
| 66 | const cv::Mat &descriptors); |
| 67 | |
Jim Ostrowski | ad5d8a7 | 2020-02-28 00:15:26 -0800 | [diff] [blame] | 68 | void SendImageMatchResult(const CameraImage &image, |
| 69 | const std::vector<cv::KeyPoint> &keypoints, |
| 70 | const cv::Mat &descriptors, |
| 71 | const std::vector<std::vector<cv::DMatch>> &matches, |
| 72 | const std::vector<cv::Mat> &camera_target_list, |
Jim Ostrowski | e426426 | 2020-02-29 00:27:24 -0800 | [diff] [blame] | 73 | const std::vector<cv::Mat> &field_camera_list, |
Jim Ostrowski | ad5d8a7 | 2020-02-28 00:15:26 -0800 | [diff] [blame] | 74 | aos::Sender<sift::ImageMatchResult> *result_sender, |
| 75 | bool send_details); |
| 76 | |
Jim Ostrowski | 1075cac | 2020-02-29 15:18:13 -0800 | [diff] [blame] | 77 | // Returns the 2D (image) location for the specified training feature. |
| 78 | cv::Point2f Training2dPoint(int training_image_index, |
| 79 | int feature_index) const { |
| 80 | const float x = training_data_->images() |
| 81 | ->Get(training_image_index) |
| 82 | ->features() |
| 83 | ->Get(feature_index) |
| 84 | ->x(); |
| 85 | const float y = training_data_->images() |
| 86 | ->Get(training_image_index) |
| 87 | ->features() |
| 88 | ->Get(feature_index) |
| 89 | ->y(); |
| 90 | return cv::Point2f(x, y); |
| 91 | } |
| 92 | |
Brian Silverman | 4d4a70d | 2020-02-17 13:03:19 -0800 | [diff] [blame] | 93 | // Returns the 3D location for the specified training feature. |
Brian Silverman | 4770c7d | 2020-02-17 20:34:42 -0800 | [diff] [blame] | 94 | cv::Point3f Training3dPoint(int training_image_index, |
| 95 | int feature_index) const { |
Brian Silverman | 4d4a70d | 2020-02-17 13:03:19 -0800 | [diff] [blame] | 96 | const sift::KeypointFieldLocation *const location = |
| 97 | training_data_->images() |
| 98 | ->Get(training_image_index) |
| 99 | ->features() |
| 100 | ->Get(feature_index) |
| 101 | ->field_location(); |
| 102 | return cv::Point3f(location->x(), location->y(), location->z()); |
| 103 | } |
| 104 | |
Brian Silverman | 4770c7d | 2020-02-17 20:34:42 -0800 | [diff] [blame] | 105 | const sift::TransformationMatrix *FieldToTarget(int training_image_index) { |
| 106 | return training_data_->images() |
| 107 | ->Get(training_image_index) |
| 108 | ->field_to_target(); |
| 109 | } |
| 110 | |
Brian Silverman | 4d4a70d | 2020-02-17 13:03:19 -0800 | [diff] [blame] | 111 | int number_training_images() const { |
| 112 | return training_data_->images()->size(); |
| 113 | } |
| 114 | |
Brian Silverman | 4770c7d | 2020-02-17 20:34:42 -0800 | [diff] [blame] | 115 | cv::Mat CameraIntrinsics() const { |
| 116 | const cv::Mat result(3, 3, CV_32F, |
| 117 | const_cast<void *>(static_cast<const void *>( |
| 118 | camera_calibration_->intrinsics()->data()))); |
| 119 | CHECK_EQ(result.total(), camera_calibration_->intrinsics()->size()); |
| 120 | return result; |
| 121 | } |
| 122 | |
Jim Ostrowski | ad5d8a7 | 2020-02-28 00:15:26 -0800 | [diff] [blame] | 123 | cv::Mat CameraDistCoeffs() const { |
| 124 | const cv::Mat result(5, 1, CV_32F, |
| 125 | const_cast<void *>(static_cast<const void *>( |
| 126 | camera_calibration_->dist_coeffs()->data()))); |
| 127 | CHECK_EQ(result.total(), camera_calibration_->dist_coeffs()->size()); |
| 128 | return result; |
| 129 | } |
| 130 | |
Brian Silverman | 967e5df | 2020-02-09 16:43:34 -0800 | [diff] [blame] | 131 | aos::EventLoop *const event_loop_; |
| 132 | const sift::TrainingData *const training_data_; |
Brian Silverman | 4770c7d | 2020-02-17 20:34:42 -0800 | [diff] [blame] | 133 | const sift::CameraCalibration *const camera_calibration_; |
Brian Silverman | 967e5df | 2020-02-09 16:43:34 -0800 | [diff] [blame] | 134 | V4L2Reader *const reader_; |
| 135 | cv::FlannBasedMatcher *const matcher_; |
| 136 | aos::Sender<CameraImage> image_sender_; |
| 137 | aos::Sender<sift::ImageMatchResult> result_sender_; |
Jim Ostrowski | ad5d8a7 | 2020-02-28 00:15:26 -0800 | [diff] [blame] | 138 | aos::Sender<sift::ImageMatchResult> detailed_result_sender_; |
Brian Silverman | 967e5df | 2020-02-09 16:43:34 -0800 | [diff] [blame] | 139 | // We schedule this immediately to read an image. Having it on a timer means |
| 140 | // other things can run on the event loop in between. |
| 141 | aos::TimerHandler *const read_image_timer_; |
| 142 | |
| 143 | const std::unique_ptr<frc971::vision::SIFT971_Impl> sift_{ |
| 144 | new frc971::vision::SIFT971_Impl()}; |
| 145 | }; |
| 146 | |
Brian Silverman | 4770c7d | 2020-02-17 20:34:42 -0800 | [diff] [blame] | 147 | const sift::CameraCalibration *CameraReader::FindCameraCalibration() const { |
| 148 | const std::string_view node_name = event_loop_->node()->name()->string_view(); |
| 149 | const int team_number = aos::network::GetTeamNumber(); |
| 150 | for (const sift::CameraCalibration *candidate : |
| 151 | *training_data_->camera_calibrations()) { |
| 152 | if (candidate->node_name()->string_view() != node_name) { |
| 153 | continue; |
| 154 | } |
| 155 | if (candidate->team_number() != team_number) { |
| 156 | continue; |
| 157 | } |
| 158 | return candidate; |
| 159 | } |
| 160 | LOG(FATAL) << ": Failed to find camera calibration for " << node_name |
| 161 | << " on " << team_number; |
| 162 | } |
| 163 | |
Brian Silverman | 967e5df | 2020-02-09 16:43:34 -0800 | [diff] [blame] | 164 | void CameraReader::CopyTrainingFeatures() { |
| 165 | for (const sift::TrainingImage *training_image : *training_data_->images()) { |
| 166 | cv::Mat features(training_image->features()->size(), 128, CV_32F); |
Jim Ostrowski | 38bb70b | 2020-02-21 20:46:10 -0800 | [diff] [blame] | 167 | for (size_t i = 0; i < training_image->features()->size(); ++i) { |
Brian Silverman | 967e5df | 2020-02-09 16:43:34 -0800 | [diff] [blame] | 168 | const sift::Feature *feature_table = training_image->features()->Get(i); |
Brian Silverman | 4770c7d | 2020-02-17 20:34:42 -0800 | [diff] [blame] | 169 | |
| 170 | // We don't need this information right now, but make sure it's here to |
| 171 | // avoid crashes that only occur when specific features are matched. |
| 172 | CHECK(feature_table->has_field_location()); |
| 173 | |
Brian Silverman | 967e5df | 2020-02-09 16:43:34 -0800 | [diff] [blame] | 174 | const flatbuffers::Vector<float> *const descriptor = |
| 175 | feature_table->descriptor(); |
| 176 | CHECK_EQ(descriptor->size(), 128u) << ": Unsupported feature size"; |
| 177 | cv::Mat(1, descriptor->size(), CV_32F, |
| 178 | const_cast<void *>(static_cast<const void *>(descriptor->data()))) |
| 179 | .copyTo(features(cv::Range(i, i + 1), cv::Range(0, 128))); |
| 180 | } |
| 181 | matcher_->add(features); |
| 182 | } |
| 183 | } |
| 184 | |
Jim Ostrowski | ad5d8a7 | 2020-02-28 00:15:26 -0800 | [diff] [blame] | 185 | void CameraReader::SendImageMatchResult( |
| 186 | const CameraImage &image, const std::vector<cv::KeyPoint> &keypoints, |
| 187 | const cv::Mat &descriptors, |
| 188 | const std::vector<std::vector<cv::DMatch>> &matches, |
| 189 | const std::vector<cv::Mat> &camera_target_list, |
Jim Ostrowski | e426426 | 2020-02-29 00:27:24 -0800 | [diff] [blame] | 190 | const std::vector<cv::Mat> &field_camera_list, |
Jim Ostrowski | ad5d8a7 | 2020-02-28 00:15:26 -0800 | [diff] [blame] | 191 | aos::Sender<sift::ImageMatchResult> *result_sender, bool send_details) { |
| 192 | auto builder = result_sender->MakeBuilder(); |
Brian Silverman | 4770c7d | 2020-02-17 20:34:42 -0800 | [diff] [blame] | 193 | const auto camera_calibration_offset = |
| 194 | aos::CopyFlatBuffer(camera_calibration_, builder.fbb()); |
| 195 | |
Jim Ostrowski | ad5d8a7 | 2020-02-28 00:15:26 -0800 | [diff] [blame] | 196 | flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<sift::Feature>>> |
| 197 | features_offset; |
Austin Schuh | 6f3640a | 2020-02-28 22:13:36 -0800 | [diff] [blame] | 198 | flatbuffers::Offset< |
| 199 | flatbuffers::Vector<flatbuffers::Offset<sift::ImageMatch>>> |
| 200 | image_matches_offset; |
Jim Ostrowski | ad5d8a7 | 2020-02-28 00:15:26 -0800 | [diff] [blame] | 201 | if (send_details) { |
| 202 | features_offset = PackFeatures(builder.fbb(), keypoints, descriptors); |
Austin Schuh | 6f3640a | 2020-02-28 22:13:36 -0800 | [diff] [blame] | 203 | image_matches_offset = PackImageMatches(builder.fbb(), matches); |
Jim Ostrowski | ad5d8a7 | 2020-02-28 00:15:26 -0800 | [diff] [blame] | 204 | } |
| 205 | |
Jim Ostrowski | ad5d8a7 | 2020-02-28 00:15:26 -0800 | [diff] [blame] | 206 | std::vector<flatbuffers::Offset<sift::CameraPose>> camera_poses; |
| 207 | |
Jim Ostrowski | e426426 | 2020-02-29 00:27:24 -0800 | [diff] [blame] | 208 | CHECK_EQ(camera_target_list.size(), field_camera_list.size()); |
Jim Ostrowski | ad5d8a7 | 2020-02-28 00:15:26 -0800 | [diff] [blame] | 209 | for (size_t i = 0; i < camera_target_list.size(); ++i) { |
| 210 | cv::Mat camera_target = camera_target_list[i]; |
| 211 | CHECK(camera_target.isContinuous()); |
| 212 | const auto data_offset = builder.fbb()->CreateVector<float>( |
| 213 | reinterpret_cast<float *>(camera_target.data), camera_target.total()); |
Austin Schuh | 6f3640a | 2020-02-28 22:13:36 -0800 | [diff] [blame] | 214 | const flatbuffers::Offset<sift::TransformationMatrix> transform_offset = |
Jim Ostrowski | ad5d8a7 | 2020-02-28 00:15:26 -0800 | [diff] [blame] | 215 | sift::CreateTransformationMatrix(*builder.fbb(), data_offset); |
Jim Ostrowski | e426426 | 2020-02-29 00:27:24 -0800 | [diff] [blame] | 216 | |
| 217 | cv::Mat field_camera = field_camera_list[i]; |
| 218 | CHECK(field_camera.isContinuous()); |
| 219 | const auto fc_data_offset = builder.fbb()->CreateVector<float>( |
| 220 | reinterpret_cast<float *>(field_camera.data), field_camera.total()); |
| 221 | const flatbuffers::Offset<sift::TransformationMatrix> fc_transform_offset = |
| 222 | sift::CreateTransformationMatrix(*builder.fbb(), fc_data_offset); |
| 223 | |
Austin Schuh | 6f3640a | 2020-02-28 22:13:36 -0800 | [diff] [blame] | 224 | const flatbuffers::Offset<sift::TransformationMatrix> |
| 225 | field_to_target_offset = |
| 226 | aos::CopyFlatBuffer(FieldToTarget(i), builder.fbb()); |
Jim Ostrowski | ad5d8a7 | 2020-02-28 00:15:26 -0800 | [diff] [blame] | 227 | |
| 228 | sift::CameraPose::Builder pose_builder(*builder.fbb()); |
| 229 | pose_builder.add_camera_to_target(transform_offset); |
Jim Ostrowski | e426426 | 2020-02-29 00:27:24 -0800 | [diff] [blame] | 230 | pose_builder.add_field_to_camera(fc_transform_offset); |
Austin Schuh | 6f3640a | 2020-02-28 22:13:36 -0800 | [diff] [blame] | 231 | pose_builder.add_field_to_target(field_to_target_offset); |
Jim Ostrowski | ad5d8a7 | 2020-02-28 00:15:26 -0800 | [diff] [blame] | 232 | camera_poses.emplace_back(pose_builder.Finish()); |
| 233 | } |
| 234 | const auto camera_poses_offset = builder.fbb()->CreateVector(camera_poses); |
| 235 | |
| 236 | sift::ImageMatchResult::Builder result_builder(*builder.fbb()); |
Jim Ostrowski | ad5d8a7 | 2020-02-28 00:15:26 -0800 | [diff] [blame] | 237 | result_builder.add_camera_poses(camera_poses_offset); |
| 238 | if (send_details) { |
Austin Schuh | 6f3640a | 2020-02-28 22:13:36 -0800 | [diff] [blame] | 239 | result_builder.add_image_matches(image_matches_offset); |
Jim Ostrowski | ad5d8a7 | 2020-02-28 00:15:26 -0800 | [diff] [blame] | 240 | result_builder.add_features(features_offset); |
| 241 | } |
| 242 | result_builder.add_image_monotonic_timestamp_ns( |
| 243 | image.monotonic_timestamp_ns()); |
| 244 | result_builder.add_camera_calibration(camera_calibration_offset); |
| 245 | |
| 246 | // TODO<Jim>: Need to add target point computed from matches and |
| 247 | // mapped by homography |
| 248 | builder.Send(result_builder.Finish()); |
| 249 | } |
| 250 | |
| 251 | void CameraReader::ProcessImage(const CameraImage &image) { |
Brian Silverman | 967e5df | 2020-02-09 16:43:34 -0800 | [diff] [blame] | 252 | // First, we need to extract the brightness information. This can't really be |
| 253 | // fused into the beginning of the SIFT algorithm because the algorithm needs |
| 254 | // to look at the base image directly. It also only takes 2ms on our images. |
| 255 | // This is converting from YUYV to a grayscale image. |
Jim Ostrowski | 38bb70b | 2020-02-21 20:46:10 -0800 | [diff] [blame] | 256 | cv::Mat image_mat(image.rows(), image.cols(), CV_8U); |
Brian Silverman | 967e5df | 2020-02-09 16:43:34 -0800 | [diff] [blame] | 257 | CHECK(image_mat.isContinuous()); |
| 258 | const int number_pixels = image.rows() * image.cols(); |
| 259 | for (int i = 0; i < number_pixels; ++i) { |
| 260 | reinterpret_cast<uint8_t *>(image_mat.data)[i] = |
| 261 | image.data()->data()[i * 2]; |
| 262 | } |
| 263 | |
| 264 | // Next, grab the features from the image. |
| 265 | std::vector<cv::KeyPoint> keypoints; |
| 266 | cv::Mat descriptors; |
| 267 | sift_->detectAndCompute(image_mat, cv::noArray(), keypoints, descriptors); |
| 268 | |
| 269 | // Then, match those features against our training data. |
| 270 | std::vector<std::vector<cv::DMatch>> matches; |
| 271 | matcher_->knnMatch(/* queryDescriptors */ descriptors, matches, /* k */ 2); |
Brian Silverman | 4770c7d | 2020-02-17 20:34:42 -0800 | [diff] [blame] | 272 | |
| 273 | struct PerImageMatches { |
| 274 | std::vector<const std::vector<cv::DMatch> *> matches; |
| 275 | std::vector<cv::Point3f> training_points_3d; |
| 276 | std::vector<cv::Point2f> query_points; |
Jim Ostrowski | 1075cac | 2020-02-29 15:18:13 -0800 | [diff] [blame] | 277 | std::vector<cv::Point2f> training_points; |
| 278 | cv::Mat homography; |
Brian Silverman | 4770c7d | 2020-02-17 20:34:42 -0800 | [diff] [blame] | 279 | }; |
| 280 | std::vector<PerImageMatches> per_image_matches(number_training_images()); |
| 281 | |
| 282 | // Pull out the good matches which we want for each image. |
| 283 | // Discard the bad matches per Lowe's ratio test. |
| 284 | // (Lowe originally proposed 0.7 ratio, but 0.75 was later proposed as a |
| 285 | // better option. We'll go with the more conservative (fewer, better matches) |
| 286 | // for now). |
| 287 | for (const std::vector<cv::DMatch> &match : matches) { |
| 288 | CHECK_EQ(2u, match.size()); |
| 289 | CHECK_LE(match[0].distance, match[1].distance); |
| 290 | CHECK_LT(match[0].imgIdx, number_training_images()); |
| 291 | CHECK_LT(match[1].imgIdx, number_training_images()); |
| 292 | CHECK_EQ(match[0].queryIdx, match[1].queryIdx); |
| 293 | if (!(match[0].distance < 0.7 * match[1].distance)) { |
| 294 | continue; |
| 295 | } |
| 296 | |
| 297 | const int training_image = match[0].imgIdx; |
| 298 | CHECK_LT(training_image, static_cast<int>(per_image_matches.size())); |
| 299 | PerImageMatches *const per_image = &per_image_matches[training_image]; |
| 300 | per_image->matches.push_back(&match); |
Jim Ostrowski | 1075cac | 2020-02-29 15:18:13 -0800 | [diff] [blame] | 301 | per_image->training_points.push_back( |
| 302 | Training2dPoint(training_image, match[0].trainIdx)); |
Brian Silverman | 4770c7d | 2020-02-17 20:34:42 -0800 | [diff] [blame] | 303 | per_image->training_points_3d.push_back( |
| 304 | Training3dPoint(training_image, match[0].trainIdx)); |
| 305 | |
| 306 | const cv::KeyPoint &keypoint = keypoints[match[0].queryIdx]; |
| 307 | per_image->query_points.push_back(keypoint.pt); |
| 308 | } |
| 309 | |
| 310 | // The minimum number of matches in a training image for us to use it. |
| 311 | static constexpr int kMinimumMatchCount = 10; |
Jim Ostrowski | ad5d8a7 | 2020-02-28 00:15:26 -0800 | [diff] [blame] | 312 | std::vector<cv::Mat> camera_target_list; |
Jim Ostrowski | e426426 | 2020-02-29 00:27:24 -0800 | [diff] [blame] | 313 | std::vector<cv::Mat> field_camera_list; |
Brian Silverman | 4770c7d | 2020-02-17 20:34:42 -0800 | [diff] [blame] | 314 | |
Jim Ostrowski | 1075cac | 2020-02-29 15:18:13 -0800 | [diff] [blame] | 315 | std::vector<PerImageMatches> per_image_good_matches; |
| 316 | std::vector<std::vector<cv::DMatch>> all_good_matches; |
| 317 | // Iterate through matches for each training image |
Brian Silverman | 4770c7d | 2020-02-17 20:34:42 -0800 | [diff] [blame] | 318 | for (size_t i = 0; i < per_image_matches.size(); ++i) { |
| 319 | const PerImageMatches &per_image = per_image_matches[i]; |
Jim Ostrowski | 1075cac | 2020-02-29 15:18:13 -0800 | [diff] [blame] | 320 | |
| 321 | VLOG(2) << "Number of matches to start: " << per_image_matches.size() |
| 322 | << "\n"; |
| 323 | // If we don't have enough matches to start, skip this set of matches |
Brian Silverman | 4770c7d | 2020-02-17 20:34:42 -0800 | [diff] [blame] | 324 | if (per_image.matches.size() < kMinimumMatchCount) { |
| 325 | continue; |
| 326 | } |
| 327 | |
Jim Ostrowski | 1075cac | 2020-02-29 15:18:13 -0800 | [diff] [blame] | 328 | // Use homography to determine which matches make sense physically |
| 329 | cv::Mat mask; |
| 330 | cv::Mat homography = |
| 331 | cv::findHomography(per_image.training_points, per_image.query_points, |
| 332 | CV_RANSAC, 3.0, mask); |
| 333 | |
| 334 | // If mask doesn't have enough leftover matches, skip these matches |
| 335 | if (cv::countNonZero(mask) < kMinimumMatchCount) { |
| 336 | continue; |
| 337 | } |
| 338 | |
| 339 | VLOG(2) << "Number of matches after homography: " << cv::countNonZero(mask) |
| 340 | << "\n"; |
| 341 | // Fill our match info for each good match |
| 342 | // TODO<Jim>: Could probably optimize some of the copies here |
| 343 | PerImageMatches per_image_good_match; |
| 344 | CHECK_EQ(per_image.training_points.size(), |
| 345 | (unsigned long)mask.size().height); |
| 346 | for (size_t j = 0; j < per_image.matches.size(); j++) { |
| 347 | // Skip if we masked out by homography |
| 348 | if (mask.at<uchar>(0, j) != 1) { |
| 349 | continue; |
| 350 | } |
| 351 | |
| 352 | // Add this to our collection of all matches that passed our criteria |
| 353 | all_good_matches.push_back( |
| 354 | static_cast<std::vector<cv::DMatch>>(*per_image.matches[j])); |
| 355 | |
| 356 | // Fill out the data for matches per image that made it past |
| 357 | // homography check |
| 358 | per_image_good_match.matches.push_back(per_image.matches[j]); |
| 359 | per_image_good_match.training_points.push_back( |
| 360 | per_image.training_points[j]); |
| 361 | per_image_good_match.training_points_3d.push_back( |
| 362 | per_image.training_points_3d[j]); |
| 363 | per_image_good_match.query_points.push_back(per_image.query_points[j]); |
| 364 | per_image_good_match.homography = homography; |
| 365 | } |
| 366 | per_image_good_matches.push_back(per_image_good_match); |
| 367 | |
| 368 | // TODO: Use homography to compute target point on query image |
| 369 | |
| 370 | // Pose transformations (rotations and translations) for various |
| 371 | // coordinate frames. R_X_Y_vec is the Rodrigues (angle-axis) |
| 372 | // representation the 3x3 rotation R_X_Y from frame X to frame Y |
| 373 | |
Jim Ostrowski | e426426 | 2020-02-29 00:27:24 -0800 | [diff] [blame] | 374 | // Tranform from camera to target frame |
Jim Ostrowski | 295f2a1 | 2020-02-26 22:22:44 -0800 | [diff] [blame] | 375 | cv::Mat R_camera_target_vec, R_camera_target, T_camera_target; |
Jim Ostrowski | e426426 | 2020-02-29 00:27:24 -0800 | [diff] [blame] | 376 | // Tranform from camera to field origin (global) reference frame |
| 377 | cv::Mat R_camera_field_vec, R_camera_field, T_camera_field; |
| 378 | // Inverse of camera to field-- defines location of camera in |
| 379 | // global (field) reference frame |
| 380 | cv::Mat R_field_camera_vec, R_field_camera, T_field_camera; |
| 381 | |
Jim Ostrowski | 295f2a1 | 2020-02-26 22:22:44 -0800 | [diff] [blame] | 382 | // Compute the pose of the camera (global origin relative to camera) |
Jim Ostrowski | 1075cac | 2020-02-29 15:18:13 -0800 | [diff] [blame] | 383 | cv::solvePnPRansac(per_image_good_match.training_points_3d, |
| 384 | per_image_good_match.query_points, CameraIntrinsics(), |
| 385 | CameraDistCoeffs(), R_camera_field_vec, T_camera_field); |
| 386 | CHECK_EQ(cv::Size(1, 3), T_camera_field.size()); |
| 387 | |
| 388 | // Convert to float32's (from float64) to be compatible with the rest |
| 389 | R_camera_field_vec.convertTo(R_camera_field_vec, CV_32F); |
| 390 | T_camera_field.convertTo(T_camera_field, CV_32F); |
Brian Silverman | 4770c7d | 2020-02-17 20:34:42 -0800 | [diff] [blame] | 391 | |
Jim Ostrowski | e426426 | 2020-02-29 00:27:24 -0800 | [diff] [blame] | 392 | // Get matrix version of R_camera_field |
| 393 | cv::Rodrigues(R_camera_field_vec, R_camera_field); |
Jim Ostrowski | 1075cac | 2020-02-29 15:18:13 -0800 | [diff] [blame] | 394 | CHECK_EQ(cv::Size(3, 3), R_camera_field.size()); |
Jim Ostrowski | e426426 | 2020-02-29 00:27:24 -0800 | [diff] [blame] | 395 | |
| 396 | // Compute H_field_camera = H_camera_field^-1 |
| 397 | R_field_camera = R_camera_field.t(); |
Jim Ostrowski | 1075cac | 2020-02-29 15:18:13 -0800 | [diff] [blame] | 398 | T_field_camera = -R_field_camera * (T_camera_field); |
Jim Ostrowski | e426426 | 2020-02-29 00:27:24 -0800 | [diff] [blame] | 399 | |
| 400 | // Extract the field_target transformation |
| 401 | const cv::Mat H_field_target(4, 4, CV_32F, |
| 402 | const_cast<void *>(static_cast<const void *>( |
Jim Ostrowski | 1075cac | 2020-02-29 15:18:13 -0800 | [diff] [blame] | 403 | FieldToTarget(i)->data()->data()))); |
| 404 | |
Jim Ostrowski | e426426 | 2020-02-29 00:27:24 -0800 | [diff] [blame] | 405 | const cv::Mat R_field_target = |
| 406 | H_field_target(cv::Range(0, 3), cv::Range(0, 3)); |
| 407 | const cv::Mat T_field_target = |
Jim Ostrowski | 1075cac | 2020-02-29 15:18:13 -0800 | [diff] [blame] | 408 | H_field_target(cv::Range(0, 3), cv::Range(3, 4)); |
Jim Ostrowski | e426426 | 2020-02-29 00:27:24 -0800 | [diff] [blame] | 409 | |
| 410 | // Use it to get the relative pose from camera to target |
Jim Ostrowski | 1075cac | 2020-02-29 15:18:13 -0800 | [diff] [blame] | 411 | R_camera_target = R_camera_field * (R_field_target); |
| 412 | T_camera_target = R_camera_field * (T_field_target) + T_camera_field; |
Jim Ostrowski | e426426 | 2020-02-29 00:27:24 -0800 | [diff] [blame] | 413 | |
| 414 | // Set H_camera_target |
Brian Silverman | 4770c7d | 2020-02-17 20:34:42 -0800 | [diff] [blame] | 415 | { |
Jim Ostrowski | 38bb70b | 2020-02-21 20:46:10 -0800 | [diff] [blame] | 416 | CHECK_EQ(cv::Size(3, 3), R_camera_target.size()); |
Jim Ostrowski | 1075cac | 2020-02-29 15:18:13 -0800 | [diff] [blame] | 417 | CHECK_EQ(cv::Size(1, 3), T_camera_target.size()); |
| 418 | cv::Mat H_camera_target = cv::Mat::zeros(4, 4, CV_32F); |
| 419 | R_camera_target.copyTo(H_camera_target(cv::Range(0, 3), cv::Range(0, 3))); |
| 420 | T_camera_target.copyTo(H_camera_target(cv::Range(0, 3), cv::Range(3, 4))); |
| 421 | H_camera_target.at<float>(3, 3) = 1; |
| 422 | CHECK(H_camera_target.isContinuous()); |
| 423 | camera_target_list.push_back(H_camera_target.clone()); |
Jim Ostrowski | e426426 | 2020-02-29 00:27:24 -0800 | [diff] [blame] | 424 | } |
| 425 | |
| 426 | // Set H_field_camera |
| 427 | { |
| 428 | CHECK_EQ(cv::Size(3, 3), R_field_camera.size()); |
Jim Ostrowski | 1075cac | 2020-02-29 15:18:13 -0800 | [diff] [blame] | 429 | CHECK_EQ(cv::Size(1, 3), T_field_camera.size()); |
| 430 | cv::Mat H_field_camera = cv::Mat::zeros(4, 4, CV_32F); |
| 431 | R_field_camera.copyTo(H_field_camera(cv::Range(0, 3), cv::Range(0, 3))); |
| 432 | T_field_camera.copyTo(H_field_camera(cv::Range(0, 3), cv::Range(3, 4))); |
| 433 | H_field_camera.at<float>(3, 3) = 1; |
| 434 | CHECK(H_field_camera.isContinuous()); |
| 435 | field_camera_list.push_back(H_field_camera.clone()); |
Brian Silverman | 4770c7d | 2020-02-17 20:34:42 -0800 | [diff] [blame] | 436 | } |
Brian Silverman | 4770c7d | 2020-02-17 20:34:42 -0800 | [diff] [blame] | 437 | } |
Jim Ostrowski | ad5d8a7 | 2020-02-28 00:15:26 -0800 | [diff] [blame] | 438 | // Now, send our two messages-- one large, with details for remote |
| 439 | // debugging(features), and one smaller |
Jim Ostrowski | 1075cac | 2020-02-29 15:18:13 -0800 | [diff] [blame] | 440 | SendImageMatchResult(image, keypoints, descriptors, all_good_matches, |
Jim Ostrowski | e426426 | 2020-02-29 00:27:24 -0800 | [diff] [blame] | 441 | camera_target_list, field_camera_list, |
| 442 | &detailed_result_sender_, true); |
Jim Ostrowski | 1075cac | 2020-02-29 15:18:13 -0800 | [diff] [blame] | 443 | SendImageMatchResult(image, keypoints, descriptors, all_good_matches, |
Jim Ostrowski | e426426 | 2020-02-29 00:27:24 -0800 | [diff] [blame] | 444 | camera_target_list, field_camera_list, &result_sender_, |
| 445 | false); |
Brian Silverman | 967e5df | 2020-02-09 16:43:34 -0800 | [diff] [blame] | 446 | } |
| 447 | |
| 448 | void CameraReader::ReadImage() { |
| 449 | if (!reader_->ReadLatestImage()) { |
| 450 | LOG(INFO) << "No image, sleeping"; |
| 451 | std::this_thread::sleep_for(std::chrono::milliseconds(10)); |
| 452 | return; |
| 453 | } |
| 454 | |
| 455 | ProcessImage(reader_->LatestImage()); |
| 456 | |
| 457 | reader_->SendLatestImage(); |
| 458 | } |
| 459 | |
| 460 | flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<sift::ImageMatch>>> |
| 461 | CameraReader::PackImageMatches( |
| 462 | flatbuffers::FlatBufferBuilder *fbb, |
| 463 | const std::vector<std::vector<cv::DMatch>> &matches) { |
| 464 | // First, we need to pull out all the matches for each image. Might as well |
| 465 | // build up the Match tables at the same time. |
Brian Silverman | 4d4a70d | 2020-02-17 13:03:19 -0800 | [diff] [blame] | 466 | std::vector<std::vector<sift::Match>> per_image_matches( |
| 467 | number_training_images()); |
Brian Silverman | 967e5df | 2020-02-09 16:43:34 -0800 | [diff] [blame] | 468 | for (const std::vector<cv::DMatch> &image_matches : matches) { |
| 469 | for (const cv::DMatch &image_match : image_matches) { |
Brian Silverman | 4d4a70d | 2020-02-17 13:03:19 -0800 | [diff] [blame] | 470 | CHECK_LT(image_match.imgIdx, number_training_images()); |
| 471 | per_image_matches[image_match.imgIdx].emplace_back(); |
| 472 | sift::Match *const match = &per_image_matches[image_match.imgIdx].back(); |
| 473 | match->mutate_query_feature(image_match.queryIdx); |
| 474 | match->mutate_train_feature(image_match.trainIdx); |
| 475 | match->mutate_distance(image_match.distance); |
Brian Silverman | 967e5df | 2020-02-09 16:43:34 -0800 | [diff] [blame] | 476 | } |
| 477 | } |
| 478 | |
| 479 | // Then, we need to build up each ImageMatch table. |
| 480 | std::vector<flatbuffers::Offset<sift::ImageMatch>> image_match_tables; |
| 481 | for (size_t i = 0; i < per_image_matches.size(); ++i) { |
Brian Silverman | 4d4a70d | 2020-02-17 13:03:19 -0800 | [diff] [blame] | 482 | const std::vector<sift::Match> &this_image_matches = per_image_matches[i]; |
Brian Silverman | 967e5df | 2020-02-09 16:43:34 -0800 | [diff] [blame] | 483 | if (this_image_matches.empty()) { |
| 484 | continue; |
| 485 | } |
Brian Silverman | 4d4a70d | 2020-02-17 13:03:19 -0800 | [diff] [blame] | 486 | const auto vector_offset = fbb->CreateVectorOfStructs(this_image_matches); |
Brian Silverman | 967e5df | 2020-02-09 16:43:34 -0800 | [diff] [blame] | 487 | sift::ImageMatch::Builder image_builder(*fbb); |
| 488 | image_builder.add_train_image(i); |
| 489 | image_builder.add_matches(vector_offset); |
| 490 | image_match_tables.emplace_back(image_builder.Finish()); |
| 491 | } |
| 492 | |
| 493 | return fbb->CreateVector(image_match_tables); |
| 494 | } |
| 495 | |
| 496 | flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<sift::Feature>>> |
| 497 | CameraReader::PackFeatures(flatbuffers::FlatBufferBuilder *fbb, |
| 498 | const std::vector<cv::KeyPoint> &keypoints, |
| 499 | const cv::Mat &descriptors) { |
| 500 | const int number_features = keypoints.size(); |
| 501 | CHECK_EQ(descriptors.rows, number_features); |
| 502 | std::vector<flatbuffers::Offset<sift::Feature>> features_vector( |
| 503 | number_features); |
| 504 | for (int i = 0; i < number_features; ++i) { |
| 505 | const auto submat = descriptors(cv::Range(i, i + 1), cv::Range(0, 128)); |
| 506 | CHECK(submat.isContinuous()); |
| 507 | const auto descriptor_offset = |
| 508 | fbb->CreateVector(reinterpret_cast<float *>(submat.data), 128); |
| 509 | sift::Feature::Builder feature_builder(*fbb); |
| 510 | feature_builder.add_descriptor(descriptor_offset); |
| 511 | feature_builder.add_x(keypoints[i].pt.x); |
| 512 | feature_builder.add_y(keypoints[i].pt.y); |
| 513 | feature_builder.add_size(keypoints[i].size); |
| 514 | feature_builder.add_angle(keypoints[i].angle); |
| 515 | feature_builder.add_response(keypoints[i].response); |
| 516 | feature_builder.add_octave(keypoints[i].octave); |
| 517 | CHECK_EQ(-1, keypoints[i].class_id) |
| 518 | << ": Not sure what to do with a class id"; |
| 519 | features_vector[i] = feature_builder.Finish(); |
| 520 | } |
| 521 | return fbb->CreateVector(features_vector); |
| 522 | } |
| 523 | |
Brian Silverman | 9dd793b | 2020-01-31 23:52:21 -0800 | [diff] [blame] | 524 | void CameraReaderMain() { |
| 525 | aos::FlatbufferDetachedBuffer<aos::Configuration> config = |
| 526 | aos::configuration::ReadConfig("config.json"); |
| 527 | |
Austin Schuh | 75589cb | 2020-02-26 22:21:37 -0800 | [diff] [blame] | 528 | const auto training_data_bfbs = SiftTrainingData(); |
Brian Silverman | 967e5df | 2020-02-09 16:43:34 -0800 | [diff] [blame] | 529 | const sift::TrainingData *const training_data = |
| 530 | flatbuffers::GetRoot<sift::TrainingData>(training_data_bfbs.data()); |
| 531 | { |
| 532 | flatbuffers::Verifier verifier( |
| 533 | reinterpret_cast<const uint8_t *>(training_data_bfbs.data()), |
| 534 | training_data_bfbs.size()); |
| 535 | CHECK(training_data->Verify(verifier)); |
| 536 | } |
| 537 | |
| 538 | const auto index_params = cv::makePtr<cv::flann::IndexParams>(); |
| 539 | index_params->setAlgorithm(cvflann::FLANN_INDEX_KDTREE); |
| 540 | index_params->setInt("trees", 5); |
| 541 | const auto search_params = |
| 542 | cv::makePtr<cv::flann::SearchParams>(/* checks */ 50); |
| 543 | cv::FlannBasedMatcher matcher(index_params, search_params); |
| 544 | |
Brian Silverman | 9dd793b | 2020-01-31 23:52:21 -0800 | [diff] [blame] | 545 | aos::ShmEventLoop event_loop(&config.message()); |
Brian Silverman | 62956e7 | 2020-02-26 21:04:05 -0800 | [diff] [blame] | 546 | |
| 547 | // First, log the data for future reference. |
| 548 | { |
| 549 | aos::Sender<sift::TrainingData> training_data_sender = |
| 550 | event_loop.MakeSender<sift::TrainingData>("/camera"); |
| 551 | training_data_sender.Send( |
| 552 | aos::FlatbufferString<sift::TrainingData>(training_data_bfbs)); |
| 553 | } |
| 554 | |
Brian Silverman | 9dd793b | 2020-01-31 23:52:21 -0800 | [diff] [blame] | 555 | V4L2Reader v4l2_reader(&event_loop, "/dev/video0"); |
Jim Ostrowski | 38bb70b | 2020-02-21 20:46:10 -0800 | [diff] [blame] | 556 | CameraReader camera_reader(&event_loop, training_data, &v4l2_reader, |
| 557 | &matcher); |
Brian Silverman | 9dd793b | 2020-01-31 23:52:21 -0800 | [diff] [blame] | 558 | |
Brian Silverman | 967e5df | 2020-02-09 16:43:34 -0800 | [diff] [blame] | 559 | event_loop.Run(); |
Brian Silverman | 9dd793b | 2020-01-31 23:52:21 -0800 | [diff] [blame] | 560 | } |
| 561 | |
| 562 | } // namespace |
| 563 | } // namespace vision |
| 564 | } // namespace frc971 |
| 565 | |
Brian Silverman | 9dd793b | 2020-01-31 23:52:21 -0800 | [diff] [blame] | 566 | int main(int argc, char **argv) { |
| 567 | aos::InitGoogle(&argc, &argv); |
| 568 | frc971::vision::CameraReaderMain(); |
| 569 | } |