blob: 58db7228970c69e7263015cd9791665bc2f8e0cb [file] [log] [blame]
Milind Upadhyaye3215862022-03-24 19:59:19 -07001#include <algorithm>
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -08002#include <map>
Philipp Schrader790cb542023-07-05 21:06:52 -07003#include <random>
4
5#include "absl/strings/str_format.h"
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -08006#include <opencv2/calib3d.hpp>
7#include <opencv2/features2d.hpp>
8#include <opencv2/highgui/highgui.hpp>
9#include <opencv2/imgproc.hpp>
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080010
11#include "aos/events/shm_event_loop.h"
12#include "aos/init.h"
13#include "aos/time/time.h"
Jim Ostrowski977850f2022-01-22 21:04:22 -080014#include "frc971/vision/vision_generated.h"
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080015#include "y2022/vision/blob_detector.h"
milind-ucafdd5d2022-03-01 19:58:57 -080016#include "y2022/vision/calibration_data.h"
Milind Upadhyaya31f0272022-04-03 13:55:22 -070017#include "y2022/vision/camera_reader.h"
Henry Speisere45e7a22022-02-04 23:17:01 -080018#include "y2022/vision/target_estimate_generated.h"
Milind Upadhyayf61e1482022-02-11 20:42:55 -080019#include "y2022/vision/target_estimator.h"
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080020
21DEFINE_string(capture, "",
22 "If set, capture a single image and save it to this filename.");
23DEFINE_string(channel, "/camera", "Channel name for the image.");
Austin Schuhc5fa6d92022-02-25 14:36:28 -080024DEFINE_string(config, "aos_config.json", "Path to the config file to use.");
Jim Ostrowski5caf81c2022-01-30 21:02:19 -080025DEFINE_string(png_dir, "", "Path to a set of images to display.");
Milind Upadhyay1a293ea2022-03-27 17:41:24 -070026DEFINE_string(png_pattern, "*", R"(Pattern to match pngs using '*'/'?'.)");
milind-ucafdd5d2022-03-01 19:58:57 -080027DEFINE_string(calibration_node, "",
28 "If reading locally, use the calibration for this node");
29DEFINE_int32(
30 calibration_team_number, 971,
31 "If reading locally, use the calibration for a node with this team number");
Milind Upadhyayf61e1482022-02-11 20:42:55 -080032DEFINE_uint64(skip, 0,
33 "Number of images to skip if doing local reading (png_dir set).");
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080034DEFINE_bool(show_features, true, "Show the blobs.");
Milind Upadhyayf61e1482022-02-11 20:42:55 -080035DEFINE_bool(display_estimation, false,
36 "If true, display the target estimation graphically");
Milind Upadhyaye3215862022-03-24 19:59:19 -070037DEFINE_bool(sort_by_time, true, "If true, sort the images by time");
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080038
39namespace y2022 {
40namespace vision {
41namespace {
42
Jim Ostrowski210765a2022-02-27 12:52:14 -080043using namespace frc971::vision;
44
45std::map<int64_t, BlobDetector::BlobResult> target_est_map;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080046aos::Fetcher<frc971::vision::CameraImage> image_fetcher;
Henry Speisere45e7a22022-02-04 23:17:01 -080047aos::Fetcher<y2022::vision::TargetEstimate> target_estimate_fetcher;
48
Milind Upadhyayf61e1482022-02-11 20:42:55 -080049std::vector<cv::Point> FbsToCvPoints(
50 const flatbuffers::Vector<const Point *> &points_fbs) {
51 std::vector<cv::Point> points;
52 for (const Point *point : points_fbs) {
53 points.emplace_back(point->x(), point->y());
54 }
55 return points;
56}
57
Henry Speisere45e7a22022-02-04 23:17:01 -080058std::vector<std::vector<cv::Point>> FbsToCvBlobs(
James Kuszmauld230d7a2022-03-06 15:00:43 -080059 const flatbuffers::Vector<flatbuffers::Offset<Blob>> *blobs_fbs) {
60 if (blobs_fbs == nullptr) {
61 return {};
62 }
Henry Speisere45e7a22022-02-04 23:17:01 -080063 std::vector<std::vector<cv::Point>> blobs;
James Kuszmauld230d7a2022-03-06 15:00:43 -080064 for (const auto blob : *blobs_fbs) {
Milind Upadhyayf61e1482022-02-11 20:42:55 -080065 blobs.emplace_back(FbsToCvPoints(*blob->points()));
Henry Speisere45e7a22022-02-04 23:17:01 -080066 }
67 return blobs;
68}
69
70std::vector<BlobDetector::BlobStats> FbsToBlobStats(
71 const flatbuffers::Vector<flatbuffers::Offset<BlobStatsFbs>>
72 &blob_stats_fbs) {
73 std::vector<BlobDetector::BlobStats> blob_stats;
74 for (const auto stats_fbs : blob_stats_fbs) {
75 cv::Point centroid{stats_fbs->centroid()->x(), stats_fbs->centroid()->y()};
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080076 cv::Size size{stats_fbs->size()->width(), stats_fbs->size()->height()};
Henry Speisere45e7a22022-02-04 23:17:01 -080077 blob_stats.emplace_back(BlobDetector::BlobStats{
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080078 centroid, size, stats_fbs->aspect_ratio(), stats_fbs->area(),
Henry Speisere45e7a22022-02-04 23:17:01 -080079 static_cast<size_t>(stats_fbs->num_points())});
80 }
81 return blob_stats;
82}
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080083
84bool DisplayLoop() {
Jim Ostrowski210765a2022-02-27 12:52:14 -080085 int64_t target_timestamp = 0;
86 if (target_estimate_fetcher.Fetch()) {
87 const TargetEstimate *target_est = target_estimate_fetcher.get();
88 CHECK(target_est != nullptr)
89 << "Got null when trying to fetch target estimate";
90
91 target_timestamp = target_est->image_monotonic_timestamp_ns();
92 if (target_est->blob_result()->filtered_blobs()->size() > 0) {
93 VLOG(2) << "Got blobs for timestamp " << target_est << "\n";
94 }
95 // Store the TargetEstimate data so we can match timestamp with image
Milind Upadhyayf61e1482022-02-11 20:42:55 -080096 target_est_map[target_timestamp] = BlobDetector::BlobResult{
97 cv::Mat(),
James Kuszmauld230d7a2022-03-06 15:00:43 -080098 FbsToCvBlobs(target_est->blob_result()->filtered_blobs()),
99 FbsToCvBlobs(target_est->blob_result()->unfiltered_blobs()),
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800100 FbsToBlobStats(*target_est->blob_result()->blob_stats()),
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800101 FbsToBlobStats(*target_est->blob_result()->filtered_stats()),
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800102 cv::Point{target_est->blob_result()->centroid()->x(),
103 target_est->blob_result()->centroid()->y()}};
Jim Ostrowski210765a2022-02-27 12:52:14 -0800104 // Only keep last 10 matches
105 while (target_est_map.size() > 10u) {
106 target_est_map.erase(target_est_map.begin());
107 }
108 }
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800109 int64_t image_timestamp = 0;
Jim Ostrowski5caf81c2022-01-30 21:02:19 -0800110 if (!image_fetcher.Fetch()) {
Jim Ostrowski210765a2022-02-27 12:52:14 -0800111 VLOG(2) << "Couldn't fetch image";
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800112 return true;
113 }
Jim Ostrowski210765a2022-02-27 12:52:14 -0800114 const CameraImage *image = image_fetcher.get();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800115 CHECK(image != nullptr) << "Couldn't read image";
116 image_timestamp = image->monotonic_timestamp_ns();
117 VLOG(2) << "Got image at timestamp: " << image_timestamp;
118
119 // Create color image:
120 cv::Mat image_color_mat(cv::Size(image->cols(), image->rows()), CV_8UC2,
121 (void *)image->data()->data());
Milind Upadhyayec41e132022-02-05 17:14:05 -0800122 cv::Mat bgr_image(cv::Size(image->cols(), image->rows()), CV_8UC3);
Milind Upadhyay40522942022-02-19 15:30:31 -0800123 cv::cvtColor(image_color_mat, bgr_image, cv::COLOR_YUV2BGR_YUYV);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800124
125 if (!FLAGS_capture.empty()) {
Milind Upadhyayec41e132022-02-05 17:14:05 -0800126 cv::imwrite(FLAGS_capture, bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800127 return false;
128 }
129
Jim Ostrowski210765a2022-02-27 12:52:14 -0800130 auto target_est_it = target_est_map.find(image_timestamp);
131 if (target_est_it != target_est_map.end()) {
132 LOG(INFO) << image->monotonic_timestamp_ns() << ": # unfiltered blobs: "
133 << target_est_it->second.unfiltered_blobs.size()
134 << "; # filtered blobs: "
135 << target_est_it->second.filtered_blobs.size();
Henry Speisere45e7a22022-02-04 23:17:01 -0800136
Jim Ostrowski210765a2022-02-27 12:52:14 -0800137 cv::Mat ret_image =
138 cv::Mat::zeros(cv::Size(image->cols(), image->rows()), CV_8UC3);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800139 BlobDetector::DrawBlobs(target_est_it->second, ret_image);
Jim Ostrowski46a78382022-02-06 14:05:58 -0800140 cv::imshow("blobs", ret_image);
141 }
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800142
Milind Upadhyayec41e132022-02-05 17:14:05 -0800143 cv::imshow("image", bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800144
145 int keystroke = cv::waitKey(1);
146 if ((keystroke & 0xFF) == static_cast<int>('c')) {
147 // Convert again, to get clean image
Milind Upadhyayec41e132022-02-05 17:14:05 -0800148 cv::cvtColor(image_color_mat, bgr_image, cv::COLOR_YUV2BGR_YUYV);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800149 std::stringstream name;
150 name << "capture-" << aos::realtime_clock::now() << ".png";
Milind Upadhyayec41e132022-02-05 17:14:05 -0800151 cv::imwrite(name.str(), bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800152 LOG(INFO) << "Saved image file: " << name.str();
153 } else if ((keystroke & 0xFF) == static_cast<int>('q')) {
154 return false;
155 }
156 return true;
157}
158
159void ViewerMain() {
160 aos::FlatbufferDetachedBuffer<aos::Configuration> config =
161 aos::configuration::ReadConfig(FLAGS_config);
162
163 aos::ShmEventLoop event_loop(&config.message());
164
165 image_fetcher =
166 event_loop.MakeFetcher<frc971::vision::CameraImage>(FLAGS_channel);
167
Jim Ostrowski46a78382022-02-06 14:05:58 -0800168 target_estimate_fetcher =
169 event_loop.MakeFetcher<y2022::vision::TargetEstimate>(FLAGS_channel);
170
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800171 // Run the display loop
172 event_loop.AddPhasedLoop(
173 [&event_loop](int) {
174 if (!DisplayLoop()) {
175 LOG(INFO) << "Calling event_loop Exit";
176 event_loop.Exit();
177 };
178 },
179 ::std::chrono::milliseconds(100));
180
181 event_loop.Run();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800182}
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800183
Milind Upadhyaye3215862022-03-24 19:59:19 -0700184size_t FindImageTimestamp(std::string_view filename) {
185 // Find the first number in the string
186 const auto timestamp_start = std::find_if(
187 filename.begin(), filename.end(), [](char c) { return std::isdigit(c); });
188 CHECK_NE(timestamp_start, filename.end())
189 << "Expected a number in image filename, got " << filename;
190 const auto timestamp_end =
191 std::find_if_not(timestamp_start + 1, filename.end(),
192 [](char c) { return std::isdigit(c); });
193
194 return static_cast<size_t>(
195 std::atoi(filename
196 .substr(timestamp_start - filename.begin(),
197 timestamp_end - timestamp_start)
198 .data()));
199}
200
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800201void ViewerLocal() {
202 std::vector<cv::String> file_list;
Milind Upadhyay1a293ea2022-03-27 17:41:24 -0700203 cv::glob(absl::StrFormat("%s/%s.png", FLAGS_png_dir, FLAGS_png_pattern),
204 file_list, false);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800205
Milind Upadhyaye3215862022-03-24 19:59:19 -0700206 // Sort the images by timestamp
207 if (FLAGS_sort_by_time) {
208 std::sort(file_list.begin(), file_list.end(),
209 [](std::string_view filename_1, std::string_view filename_2) {
210 return (FindImageTimestamp(filename_1) <
211 FindImageTimestamp(filename_2));
212 });
213 }
214
milind-ucafdd5d2022-03-01 19:58:57 -0800215 const aos::FlatbufferSpan<calibration::CalibrationData> calibration_data(
216 CalibrationData());
217
Milind Upadhyaya31f0272022-04-03 13:55:22 -0700218 const calibration::CameraCalibration *calibration =
219 CameraReader::FindCameraCalibration(&calibration_data.message(),
220 FLAGS_calibration_node,
221 FLAGS_calibration_team_number);
222 const auto intrinsics = CameraReader::CameraIntrinsics(calibration);
223 const auto extrinsics = CameraReader::CameraExtrinsics(calibration);
224 const auto dist_coeffs = CameraReader::CameraDistCoeffs(calibration);
milind-ucafdd5d2022-03-01 19:58:57 -0800225
Milind Upadhyaya31f0272022-04-03 13:55:22 -0700226 // Compute undistortion map once for efficiency
227 const auto undistort_maps =
228 CameraReader::ComputeUndistortMaps(intrinsics, dist_coeffs);
Milind Upadhyay3c1a5c02022-03-27 16:27:19 -0700229
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800230 TargetEstimator estimator(intrinsics, extrinsics);
231
Milind Upadhyayae998722022-03-13 12:45:55 -0700232 for (auto it = file_list.begin() + FLAGS_skip; it < file_list.end(); it++) {
Milind Upadhyay07f6f9e2022-03-18 18:40:34 -0700233 LOG(INFO) << "Reading file " << (it - file_list.begin()) << ": " << *it;
Milind Upadhyaya31f0272022-04-03 13:55:22 -0700234 cv::Mat image_mat =
235 CameraReader::UndistortImage(cv::imread(it->c_str()), undistort_maps);
Milind Upadhyay3c1a5c02022-03-27 16:27:19 -0700236
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800237 BlobDetector::BlobResult blob_result;
238 blob_result.binarized_image =
239 cv::Mat::zeros(cv::Size(image_mat.cols, image_mat.rows), CV_8UC1);
240 BlobDetector::ExtractBlobs(image_mat, &blob_result);
241
242 cv::Mat ret_image =
243 cv::Mat::zeros(cv::Size(image_mat.cols, image_mat.rows), CV_8UC3);
244 BlobDetector::DrawBlobs(blob_result, ret_image);
245
246 LOG(INFO) << ": # blobs: " << blob_result.filtered_blobs.size()
247 << " (# removed: "
248 << blob_result.unfiltered_blobs.size() -
249 blob_result.filtered_blobs.size()
250 << ")";
251
Milind Upadhyaye5003102022-04-02 22:16:39 -0700252 estimator.Solve(blob_result.filtered_stats,
253 FLAGS_display_estimation ? std::make_optional(ret_image)
254 : std::nullopt);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800255 if (blob_result.filtered_blobs.size() > 0) {
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800256 estimator.DrawEstimate(ret_image);
Austin Schuha685b5d2022-04-02 14:53:54 -0700257 LOG(INFO) << "Read file " << (it - file_list.begin()) << ": " << *it;
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800258 }
259
260 cv::imshow("image", image_mat);
261 cv::imshow("mask", blob_result.binarized_image);
262 cv::imshow("blobs", ret_image);
263
Milind Upadhyaye3215862022-03-24 19:59:19 -0700264 constexpr size_t kWaitKeyDelay = 0; // ms
265 int keystroke = cv::waitKey(kWaitKeyDelay) & 0xFF;
266 // Ignore alt key
267 while (keystroke == 233) {
268 keystroke = cv::waitKey(kWaitKeyDelay);
269 }
270 if (keystroke == static_cast<int>('q')) {
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800271 return;
272 }
273 }
274}
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800275} // namespace
276} // namespace vision
277} // namespace y2022
278
279// Quick and lightweight viewer for images
280int main(int argc, char **argv) {
281 aos::InitGoogle(&argc, &argv);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800282 if (FLAGS_png_dir != "")
283 y2022::vision::ViewerLocal();
284 else
285 y2022::vision::ViewerMain();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800286}