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