blob: 446f1f61e0d0e45ac33ea980d03399c4e4ddb236 [file] [log] [blame]
Milind Upadhyaye3215862022-03-24 19:59:19 -07001#include <algorithm>
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -08002#include <map>
3#include <opencv2/calib3d.hpp>
4#include <opencv2/features2d.hpp>
5#include <opencv2/highgui/highgui.hpp>
6#include <opencv2/imgproc.hpp>
7#include <random>
8
Milind Upadhyay1a293ea2022-03-27 17:41:24 -07009#include "absl/strings/str_format.h"
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080010#include "aos/events/shm_event_loop.h"
11#include "aos/init.h"
12#include "aos/time/time.h"
Jim Ostrowski977850f2022-01-22 21:04:22 -080013#include "frc971/vision/vision_generated.h"
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080014#include "y2022/vision/blob_detector.h"
milind-ucafdd5d2022-03-01 19:58:57 -080015#include "y2022/vision/calibration_data.h"
Henry Speisere45e7a22022-02-04 23:17:01 -080016#include "y2022/vision/target_estimate_generated.h"
Milind Upadhyayf61e1482022-02-11 20:42:55 -080017#include "y2022/vision/target_estimator.h"
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080018
19DEFINE_string(capture, "",
20 "If set, capture a single image and save it to this filename.");
21DEFINE_string(channel, "/camera", "Channel name for the image.");
Austin Schuhc5fa6d92022-02-25 14:36:28 -080022DEFINE_string(config, "aos_config.json", "Path to the config file to use.");
Jim Ostrowski5caf81c2022-01-30 21:02:19 -080023DEFINE_string(png_dir, "", "Path to a set of images to display.");
Milind Upadhyay1a293ea2022-03-27 17:41:24 -070024DEFINE_string(png_pattern, "*", R"(Pattern to match pngs using '*'/'?'.)");
milind-ucafdd5d2022-03-01 19:58:57 -080025DEFINE_string(calibration_node, "",
26 "If reading locally, use the calibration for this node");
27DEFINE_int32(
28 calibration_team_number, 971,
29 "If reading locally, use the calibration for a node with this team number");
Milind Upadhyayf61e1482022-02-11 20:42:55 -080030DEFINE_uint64(skip, 0,
31 "Number of images to skip if doing local reading (png_dir set).");
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080032DEFINE_bool(show_features, true, "Show the blobs.");
Milind Upadhyayf61e1482022-02-11 20:42:55 -080033DEFINE_bool(display_estimation, false,
34 "If true, display the target estimation graphically");
Milind Upadhyaye3215862022-03-24 19:59:19 -070035DEFINE_bool(sort_by_time, true, "If true, sort the images by time");
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080036
37namespace y2022 {
38namespace vision {
39namespace {
40
Jim Ostrowski210765a2022-02-27 12:52:14 -080041using namespace frc971::vision;
42
43std::map<int64_t, BlobDetector::BlobResult> target_est_map;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080044aos::Fetcher<frc971::vision::CameraImage> image_fetcher;
Henry Speisere45e7a22022-02-04 23:17:01 -080045aos::Fetcher<y2022::vision::TargetEstimate> target_estimate_fetcher;
46
Milind Upadhyayf61e1482022-02-11 20:42:55 -080047std::vector<cv::Point> FbsToCvPoints(
48 const flatbuffers::Vector<const Point *> &points_fbs) {
49 std::vector<cv::Point> points;
50 for (const Point *point : points_fbs) {
51 points.emplace_back(point->x(), point->y());
52 }
53 return points;
54}
55
Henry Speisere45e7a22022-02-04 23:17:01 -080056std::vector<std::vector<cv::Point>> FbsToCvBlobs(
James Kuszmauld230d7a2022-03-06 15:00:43 -080057 const flatbuffers::Vector<flatbuffers::Offset<Blob>> *blobs_fbs) {
58 if (blobs_fbs == nullptr) {
59 return {};
60 }
Henry Speisere45e7a22022-02-04 23:17:01 -080061 std::vector<std::vector<cv::Point>> blobs;
James Kuszmauld230d7a2022-03-06 15:00:43 -080062 for (const auto blob : *blobs_fbs) {
Milind Upadhyayf61e1482022-02-11 20:42:55 -080063 blobs.emplace_back(FbsToCvPoints(*blob->points()));
Henry Speisere45e7a22022-02-04 23:17:01 -080064 }
65 return blobs;
66}
67
68std::vector<BlobDetector::BlobStats> FbsToBlobStats(
69 const flatbuffers::Vector<flatbuffers::Offset<BlobStatsFbs>>
70 &blob_stats_fbs) {
71 std::vector<BlobDetector::BlobStats> blob_stats;
72 for (const auto stats_fbs : blob_stats_fbs) {
73 cv::Point centroid{stats_fbs->centroid()->x(), stats_fbs->centroid()->y()};
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080074 cv::Size size{stats_fbs->size()->width(), stats_fbs->size()->height()};
Henry Speisere45e7a22022-02-04 23:17:01 -080075 blob_stats.emplace_back(BlobDetector::BlobStats{
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080076 centroid, size, stats_fbs->aspect_ratio(), stats_fbs->area(),
Henry Speisere45e7a22022-02-04 23:17:01 -080077 static_cast<size_t>(stats_fbs->num_points())});
78 }
79 return blob_stats;
80}
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080081
82bool DisplayLoop() {
Jim Ostrowski210765a2022-02-27 12:52:14 -080083 int64_t target_timestamp = 0;
84 if (target_estimate_fetcher.Fetch()) {
85 const TargetEstimate *target_est = target_estimate_fetcher.get();
86 CHECK(target_est != nullptr)
87 << "Got null when trying to fetch target estimate";
88
89 target_timestamp = target_est->image_monotonic_timestamp_ns();
90 if (target_est->blob_result()->filtered_blobs()->size() > 0) {
91 VLOG(2) << "Got blobs for timestamp " << target_est << "\n";
92 }
93 // Store the TargetEstimate data so we can match timestamp with image
Milind Upadhyayf61e1482022-02-11 20:42:55 -080094 target_est_map[target_timestamp] = BlobDetector::BlobResult{
95 cv::Mat(),
James Kuszmauld230d7a2022-03-06 15:00:43 -080096 FbsToCvBlobs(target_est->blob_result()->filtered_blobs()),
97 FbsToCvBlobs(target_est->blob_result()->unfiltered_blobs()),
Milind Upadhyayf61e1482022-02-11 20:42:55 -080098 FbsToBlobStats(*target_est->blob_result()->blob_stats()),
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080099 FbsToBlobStats(*target_est->blob_result()->filtered_stats()),
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800100 cv::Point{target_est->blob_result()->centroid()->x(),
101 target_est->blob_result()->centroid()->y()}};
Jim Ostrowski210765a2022-02-27 12:52:14 -0800102 // Only keep last 10 matches
103 while (target_est_map.size() > 10u) {
104 target_est_map.erase(target_est_map.begin());
105 }
106 }
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800107 int64_t image_timestamp = 0;
Jim Ostrowski5caf81c2022-01-30 21:02:19 -0800108 if (!image_fetcher.Fetch()) {
Jim Ostrowski210765a2022-02-27 12:52:14 -0800109 VLOG(2) << "Couldn't fetch image";
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800110 return true;
111 }
Jim Ostrowski210765a2022-02-27 12:52:14 -0800112 const CameraImage *image = image_fetcher.get();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800113 CHECK(image != nullptr) << "Couldn't read image";
114 image_timestamp = image->monotonic_timestamp_ns();
115 VLOG(2) << "Got image at timestamp: " << image_timestamp;
116
117 // Create color image:
118 cv::Mat image_color_mat(cv::Size(image->cols(), image->rows()), CV_8UC2,
119 (void *)image->data()->data());
Milind Upadhyayec41e132022-02-05 17:14:05 -0800120 cv::Mat bgr_image(cv::Size(image->cols(), image->rows()), CV_8UC3);
Milind Upadhyay40522942022-02-19 15:30:31 -0800121 cv::cvtColor(image_color_mat, bgr_image, cv::COLOR_YUV2BGR_YUYV);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800122
123 if (!FLAGS_capture.empty()) {
Milind Upadhyayec41e132022-02-05 17:14:05 -0800124 cv::imwrite(FLAGS_capture, bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800125 return false;
126 }
127
Jim Ostrowski210765a2022-02-27 12:52:14 -0800128 auto target_est_it = target_est_map.find(image_timestamp);
129 if (target_est_it != target_est_map.end()) {
130 LOG(INFO) << image->monotonic_timestamp_ns() << ": # unfiltered blobs: "
131 << target_est_it->second.unfiltered_blobs.size()
132 << "; # filtered blobs: "
133 << target_est_it->second.filtered_blobs.size();
Henry Speisere45e7a22022-02-04 23:17:01 -0800134
Jim Ostrowski210765a2022-02-27 12:52:14 -0800135 cv::Mat ret_image =
136 cv::Mat::zeros(cv::Size(image->cols(), image->rows()), CV_8UC3);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800137 BlobDetector::DrawBlobs(target_est_it->second, ret_image);
Jim Ostrowski46a78382022-02-06 14:05:58 -0800138 cv::imshow("blobs", ret_image);
139 }
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800140
Milind Upadhyayec41e132022-02-05 17:14:05 -0800141 cv::imshow("image", bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800142
143 int keystroke = cv::waitKey(1);
144 if ((keystroke & 0xFF) == static_cast<int>('c')) {
145 // Convert again, to get clean image
Milind Upadhyayec41e132022-02-05 17:14:05 -0800146 cv::cvtColor(image_color_mat, bgr_image, cv::COLOR_YUV2BGR_YUYV);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800147 std::stringstream name;
148 name << "capture-" << aos::realtime_clock::now() << ".png";
Milind Upadhyayec41e132022-02-05 17:14:05 -0800149 cv::imwrite(name.str(), bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800150 LOG(INFO) << "Saved image file: " << name.str();
151 } else if ((keystroke & 0xFF) == static_cast<int>('q')) {
152 return false;
153 }
154 return true;
155}
156
157void ViewerMain() {
158 aos::FlatbufferDetachedBuffer<aos::Configuration> config =
159 aos::configuration::ReadConfig(FLAGS_config);
160
161 aos::ShmEventLoop event_loop(&config.message());
162
163 image_fetcher =
164 event_loop.MakeFetcher<frc971::vision::CameraImage>(FLAGS_channel);
165
Jim Ostrowski46a78382022-02-06 14:05:58 -0800166 target_estimate_fetcher =
167 event_loop.MakeFetcher<y2022::vision::TargetEstimate>(FLAGS_channel);
168
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800169 // Run the display loop
170 event_loop.AddPhasedLoop(
171 [&event_loop](int) {
172 if (!DisplayLoop()) {
173 LOG(INFO) << "Calling event_loop Exit";
174 event_loop.Exit();
175 };
176 },
177 ::std::chrono::milliseconds(100));
178
179 event_loop.Run();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800180}
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800181
Milind Upadhyaye3215862022-03-24 19:59:19 -0700182size_t FindImageTimestamp(std::string_view filename) {
183 // Find the first number in the string
184 const auto timestamp_start = std::find_if(
185 filename.begin(), filename.end(), [](char c) { return std::isdigit(c); });
186 CHECK_NE(timestamp_start, filename.end())
187 << "Expected a number in image filename, got " << filename;
188 const auto timestamp_end =
189 std::find_if_not(timestamp_start + 1, filename.end(),
190 [](char c) { return std::isdigit(c); });
191
192 return static_cast<size_t>(
193 std::atoi(filename
194 .substr(timestamp_start - filename.begin(),
195 timestamp_end - timestamp_start)
196 .data()));
197}
198
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800199void ViewerLocal() {
200 std::vector<cv::String> file_list;
Milind Upadhyay1a293ea2022-03-27 17:41:24 -0700201 cv::glob(absl::StrFormat("%s/%s.png", FLAGS_png_dir, FLAGS_png_pattern),
202 file_list, false);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800203
Milind Upadhyaye3215862022-03-24 19:59:19 -0700204 // Sort the images by timestamp
205 if (FLAGS_sort_by_time) {
206 std::sort(file_list.begin(), file_list.end(),
207 [](std::string_view filename_1, std::string_view filename_2) {
208 return (FindImageTimestamp(filename_1) <
209 FindImageTimestamp(filename_2));
210 });
211 }
212
milind-ucafdd5d2022-03-01 19:58:57 -0800213 const aos::FlatbufferSpan<calibration::CalibrationData> calibration_data(
214 CalibrationData());
215
216 const calibration::CameraCalibration *calibration = nullptr;
217 for (const calibration::CameraCalibration *candidate :
218 *calibration_data.message().camera_calibrations()) {
219 if ((candidate->node_name()->string_view() == FLAGS_calibration_node) &&
220 (candidate->team_number() == FLAGS_calibration_team_number)) {
221 calibration = candidate;
222 break;
223 }
224 }
225
226 CHECK(calibration) << "No calibration data found for node \""
227 << FLAGS_calibration_node << "\" with team number "
228 << FLAGS_calibration_team_number;
229
Milind Upadhyay3c1a5c02022-03-27 16:27:19 -0700230 const auto intrinsics_float = cv::Mat(
231 3, 3, CV_32F,
232 const_cast<void *>(
233 static_cast<const void *>(calibration->intrinsics()->data())));
milind-ucafdd5d2022-03-01 19:58:57 -0800234 cv::Mat intrinsics;
235 intrinsics_float.convertTo(intrinsics, CV_64F);
236
Milind Upadhyaya4cce2f2022-03-13 21:50:13 -0700237 const frc971::vision::calibration::TransformationMatrix *transform =
238 calibration->has_turret_extrinsics() ? calibration->turret_extrinsics()
239 : calibration->fixed_extrinsics();
240
241 const auto extrinsics_float = cv::Mat(
242 4, 4, CV_32F,
243 const_cast<void *>(static_cast<const void *>(transform->data()->data())));
milind-ucafdd5d2022-03-01 19:58:57 -0800244 cv::Mat extrinsics;
245 extrinsics_float.convertTo(extrinsics, CV_64F);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800246
Milind Upadhyay3c1a5c02022-03-27 16:27:19 -0700247 const auto dist_coeffs_float = cv::Mat(
248 5, 1, CV_32F,
249 const_cast<void *>(
250 static_cast<const void *>(calibration->dist_coeffs()->data())));
251 cv::Mat dist_coeffs;
252 dist_coeffs_float.convertTo(dist_coeffs, CV_64F);
253
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800254 TargetEstimator estimator(intrinsics, extrinsics);
255
Milind Upadhyayae998722022-03-13 12:45:55 -0700256 for (auto it = file_list.begin() + FLAGS_skip; it < file_list.end(); it++) {
Milind Upadhyay07f6f9e2022-03-18 18:40:34 -0700257 LOG(INFO) << "Reading file " << (it - file_list.begin()) << ": " << *it;
Milind Upadhyay3c1a5c02022-03-27 16:27:19 -0700258 cv::Mat image_mat_distorted = cv::imread(it->c_str());
259 cv::Mat image_mat;
260 cv::undistort(image_mat_distorted, image_mat, intrinsics, dist_coeffs);
261
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800262 BlobDetector::BlobResult blob_result;
263 blob_result.binarized_image =
264 cv::Mat::zeros(cv::Size(image_mat.cols, image_mat.rows), CV_8UC1);
265 BlobDetector::ExtractBlobs(image_mat, &blob_result);
266
267 cv::Mat ret_image =
268 cv::Mat::zeros(cv::Size(image_mat.cols, image_mat.rows), CV_8UC3);
269 BlobDetector::DrawBlobs(blob_result, ret_image);
270
271 LOG(INFO) << ": # blobs: " << blob_result.filtered_blobs.size()
272 << " (# removed: "
273 << blob_result.unfiltered_blobs.size() -
274 blob_result.filtered_blobs.size()
275 << ")";
276
Milind Upadhyaye5003102022-04-02 22:16:39 -0700277 estimator.Solve(blob_result.filtered_stats,
278 FLAGS_display_estimation ? std::make_optional(ret_image)
279 : std::nullopt);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800280 if (blob_result.filtered_blobs.size() > 0) {
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800281 estimator.DrawEstimate(ret_image);
Austin Schuha685b5d2022-04-02 14:53:54 -0700282 LOG(INFO) << "Read file " << (it - file_list.begin()) << ": " << *it;
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800283 }
284
285 cv::imshow("image", image_mat);
286 cv::imshow("mask", blob_result.binarized_image);
287 cv::imshow("blobs", ret_image);
288
Milind Upadhyaye3215862022-03-24 19:59:19 -0700289 constexpr size_t kWaitKeyDelay = 0; // ms
290 int keystroke = cv::waitKey(kWaitKeyDelay) & 0xFF;
291 // Ignore alt key
292 while (keystroke == 233) {
293 keystroke = cv::waitKey(kWaitKeyDelay);
294 }
295 if (keystroke == static_cast<int>('q')) {
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800296 return;
297 }
298 }
299}
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800300} // namespace
301} // namespace vision
302} // namespace y2022
303
304// Quick and lightweight viewer for images
305int main(int argc, char **argv) {
306 aos::InitGoogle(&argc, &argv);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800307 if (FLAGS_png_dir != "")
308 y2022::vision::ViewerLocal();
309 else
310 y2022::vision::ViewerMain();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800311}