blob: 7638a4c0548bac37cb29c58d976dd284d2f6971e [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
Austin Schuh99f7c6a2024-06-25 22:07:44 -07005#include "absl/flags/flag.h"
Philipp Schrader790cb542023-07-05 21:06:52 -07006#include "absl/strings/str_format.h"
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -08007#include <opencv2/calib3d.hpp>
8#include <opencv2/features2d.hpp>
9#include <opencv2/highgui/highgui.hpp>
10#include <opencv2/imgproc.hpp>
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080011
12#include "aos/events/shm_event_loop.h"
13#include "aos/init.h"
14#include "aos/time/time.h"
Jim Ostrowski977850f2022-01-22 21:04:22 -080015#include "frc971/vision/vision_generated.h"
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080016#include "y2022/vision/blob_detector.h"
milind-ucafdd5d2022-03-01 19:58:57 -080017#include "y2022/vision/calibration_data.h"
Milind Upadhyaya31f0272022-04-03 13:55:22 -070018#include "y2022/vision/camera_reader.h"
Henry Speisere45e7a22022-02-04 23:17:01 -080019#include "y2022/vision/target_estimate_generated.h"
Milind Upadhyayf61e1482022-02-11 20:42:55 -080020#include "y2022/vision/target_estimator.h"
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080021
Austin Schuh99f7c6a2024-06-25 22:07:44 -070022ABSL_FLAG(std::string, capture, "",
23 "If set, capture a single image and save it to this filename.");
24ABSL_FLAG(std::string, channel, "/camera", "Channel name for the image.");
25ABSL_FLAG(std::string, config, "aos_config.json",
26 "Path to the config file to use.");
27ABSL_FLAG(std::string, png_dir, "", "Path to a set of images to display.");
28ABSL_FLAG(std::string, png_pattern, "*",
29 R"(Pattern to match pngs using '*'/'?'.)");
30ABSL_FLAG(std::string, calibration_node, "",
31 "If reading locally, use the calibration for this node");
32ABSL_FLAG(
33 int32_t, calibration_team_number, 971,
milind-ucafdd5d2022-03-01 19:58:57 -080034 "If reading locally, use the calibration for a node with this team number");
Austin Schuh99f7c6a2024-06-25 22:07:44 -070035ABSL_FLAG(uint64_t, skip, 0,
36 "Number of images to skip if doing local reading (png_dir set).");
37ABSL_FLAG(bool, show_features, true, "Show the blobs.");
38ABSL_FLAG(bool, display_estimation, false,
39 "If true, display the target estimation graphically");
40ABSL_FLAG(bool, sort_by_time, true, "If true, sort the images by time");
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080041
Stephan Pleinesf63bde82024-01-13 15:59:33 -080042namespace y2022::vision {
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080043namespace {
44
Jim Ostrowski210765a2022-02-27 12:52:14 -080045using namespace frc971::vision;
46
47std::map<int64_t, BlobDetector::BlobResult> target_est_map;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080048aos::Fetcher<frc971::vision::CameraImage> image_fetcher;
Henry Speisere45e7a22022-02-04 23:17:01 -080049aos::Fetcher<y2022::vision::TargetEstimate> target_estimate_fetcher;
50
Milind Upadhyayf61e1482022-02-11 20:42:55 -080051std::vector<cv::Point> FbsToCvPoints(
52 const flatbuffers::Vector<const Point *> &points_fbs) {
53 std::vector<cv::Point> points;
54 for (const Point *point : points_fbs) {
55 points.emplace_back(point->x(), point->y());
56 }
57 return points;
58}
59
Henry Speisere45e7a22022-02-04 23:17:01 -080060std::vector<std::vector<cv::Point>> FbsToCvBlobs(
James Kuszmauld230d7a2022-03-06 15:00:43 -080061 const flatbuffers::Vector<flatbuffers::Offset<Blob>> *blobs_fbs) {
62 if (blobs_fbs == nullptr) {
63 return {};
64 }
Henry Speisere45e7a22022-02-04 23:17:01 -080065 std::vector<std::vector<cv::Point>> blobs;
James Kuszmauld230d7a2022-03-06 15:00:43 -080066 for (const auto blob : *blobs_fbs) {
Milind Upadhyayf61e1482022-02-11 20:42:55 -080067 blobs.emplace_back(FbsToCvPoints(*blob->points()));
Henry Speisere45e7a22022-02-04 23:17:01 -080068 }
69 return blobs;
70}
71
72std::vector<BlobDetector::BlobStats> FbsToBlobStats(
73 const flatbuffers::Vector<flatbuffers::Offset<BlobStatsFbs>>
74 &blob_stats_fbs) {
75 std::vector<BlobDetector::BlobStats> blob_stats;
76 for (const auto stats_fbs : blob_stats_fbs) {
77 cv::Point centroid{stats_fbs->centroid()->x(), stats_fbs->centroid()->y()};
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080078 cv::Size size{stats_fbs->size()->width(), stats_fbs->size()->height()};
Henry Speisere45e7a22022-02-04 23:17:01 -080079 blob_stats.emplace_back(BlobDetector::BlobStats{
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080080 centroid, size, stats_fbs->aspect_ratio(), stats_fbs->area(),
Henry Speisere45e7a22022-02-04 23:17:01 -080081 static_cast<size_t>(stats_fbs->num_points())});
82 }
83 return blob_stats;
84}
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080085
86bool DisplayLoop() {
Jim Ostrowski210765a2022-02-27 12:52:14 -080087 int64_t target_timestamp = 0;
88 if (target_estimate_fetcher.Fetch()) {
89 const TargetEstimate *target_est = target_estimate_fetcher.get();
90 CHECK(target_est != nullptr)
91 << "Got null when trying to fetch target estimate";
92
93 target_timestamp = target_est->image_monotonic_timestamp_ns();
94 if (target_est->blob_result()->filtered_blobs()->size() > 0) {
95 VLOG(2) << "Got blobs for timestamp " << target_est << "\n";
96 }
97 // Store the TargetEstimate data so we can match timestamp with image
Milind Upadhyayf61e1482022-02-11 20:42:55 -080098 target_est_map[target_timestamp] = BlobDetector::BlobResult{
99 cv::Mat(),
James Kuszmauld230d7a2022-03-06 15:00:43 -0800100 FbsToCvBlobs(target_est->blob_result()->filtered_blobs()),
101 FbsToCvBlobs(target_est->blob_result()->unfiltered_blobs()),
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800102 FbsToBlobStats(*target_est->blob_result()->blob_stats()),
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800103 FbsToBlobStats(*target_est->blob_result()->filtered_stats()),
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800104 cv::Point{target_est->blob_result()->centroid()->x(),
105 target_est->blob_result()->centroid()->y()}};
Jim Ostrowski210765a2022-02-27 12:52:14 -0800106 // Only keep last 10 matches
107 while (target_est_map.size() > 10u) {
108 target_est_map.erase(target_est_map.begin());
109 }
110 }
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800111 int64_t image_timestamp = 0;
Jim Ostrowski5caf81c2022-01-30 21:02:19 -0800112 if (!image_fetcher.Fetch()) {
Jim Ostrowski210765a2022-02-27 12:52:14 -0800113 VLOG(2) << "Couldn't fetch image";
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800114 return true;
115 }
Jim Ostrowski210765a2022-02-27 12:52:14 -0800116 const CameraImage *image = image_fetcher.get();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800117 CHECK(image != nullptr) << "Couldn't read image";
118 image_timestamp = image->monotonic_timestamp_ns();
119 VLOG(2) << "Got image at timestamp: " << image_timestamp;
120
121 // Create color image:
122 cv::Mat image_color_mat(cv::Size(image->cols(), image->rows()), CV_8UC2,
123 (void *)image->data()->data());
Milind Upadhyayec41e132022-02-05 17:14:05 -0800124 cv::Mat bgr_image(cv::Size(image->cols(), image->rows()), CV_8UC3);
Milind Upadhyay40522942022-02-19 15:30:31 -0800125 cv::cvtColor(image_color_mat, bgr_image, cv::COLOR_YUV2BGR_YUYV);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800126
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700127 if (!absl::GetFlag(FLAGS_capture).empty()) {
128 cv::imwrite(absl::GetFlag(FLAGS_capture), bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800129 return false;
130 }
131
Jim Ostrowski210765a2022-02-27 12:52:14 -0800132 auto target_est_it = target_est_map.find(image_timestamp);
133 if (target_est_it != target_est_map.end()) {
134 LOG(INFO) << image->monotonic_timestamp_ns() << ": # unfiltered blobs: "
135 << target_est_it->second.unfiltered_blobs.size()
136 << "; # filtered blobs: "
137 << target_est_it->second.filtered_blobs.size();
Henry Speisere45e7a22022-02-04 23:17:01 -0800138
Jim Ostrowski210765a2022-02-27 12:52:14 -0800139 cv::Mat ret_image =
140 cv::Mat::zeros(cv::Size(image->cols(), image->rows()), CV_8UC3);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800141 BlobDetector::DrawBlobs(target_est_it->second, ret_image);
Jim Ostrowski46a78382022-02-06 14:05:58 -0800142 cv::imshow("blobs", ret_image);
143 }
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800144
Milind Upadhyayec41e132022-02-05 17:14:05 -0800145 cv::imshow("image", bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800146
147 int keystroke = cv::waitKey(1);
148 if ((keystroke & 0xFF) == static_cast<int>('c')) {
149 // Convert again, to get clean image
Milind Upadhyayec41e132022-02-05 17:14:05 -0800150 cv::cvtColor(image_color_mat, bgr_image, cv::COLOR_YUV2BGR_YUYV);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800151 std::stringstream name;
152 name << "capture-" << aos::realtime_clock::now() << ".png";
Milind Upadhyayec41e132022-02-05 17:14:05 -0800153 cv::imwrite(name.str(), bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800154 LOG(INFO) << "Saved image file: " << name.str();
155 } else if ((keystroke & 0xFF) == static_cast<int>('q')) {
156 return false;
157 }
158 return true;
159}
160
161void ViewerMain() {
162 aos::FlatbufferDetachedBuffer<aos::Configuration> config =
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700163 aos::configuration::ReadConfig(absl::GetFlag(FLAGS_config));
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800164
165 aos::ShmEventLoop event_loop(&config.message());
166
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700167 image_fetcher = event_loop.MakeFetcher<frc971::vision::CameraImage>(
168 absl::GetFlag(FLAGS_channel));
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800169
Jim Ostrowski46a78382022-02-06 14:05:58 -0800170 target_estimate_fetcher =
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700171 event_loop.MakeFetcher<y2022::vision::TargetEstimate>(
172 absl::GetFlag(FLAGS_channel));
Jim Ostrowski46a78382022-02-06 14:05:58 -0800173
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800174 // Run the display loop
175 event_loop.AddPhasedLoop(
176 [&event_loop](int) {
177 if (!DisplayLoop()) {
178 LOG(INFO) << "Calling event_loop Exit";
179 event_loop.Exit();
180 };
181 },
182 ::std::chrono::milliseconds(100));
183
184 event_loop.Run();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800185}
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800186
Milind Upadhyaye3215862022-03-24 19:59:19 -0700187size_t FindImageTimestamp(std::string_view filename) {
188 // Find the first number in the string
189 const auto timestamp_start = std::find_if(
190 filename.begin(), filename.end(), [](char c) { return std::isdigit(c); });
191 CHECK_NE(timestamp_start, filename.end())
192 << "Expected a number in image filename, got " << filename;
193 const auto timestamp_end =
194 std::find_if_not(timestamp_start + 1, filename.end(),
195 [](char c) { return std::isdigit(c); });
196
197 return static_cast<size_t>(
198 std::atoi(filename
199 .substr(timestamp_start - filename.begin(),
200 timestamp_end - timestamp_start)
201 .data()));
202}
203
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800204void ViewerLocal() {
205 std::vector<cv::String> file_list;
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700206 cv::glob(absl::StrFormat("%s/%s.png", absl::GetFlag(FLAGS_png_dir),
207 absl::GetFlag(FLAGS_png_pattern)),
Milind Upadhyay1a293ea2022-03-27 17:41:24 -0700208 file_list, false);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800209
Milind Upadhyaye3215862022-03-24 19:59:19 -0700210 // Sort the images by timestamp
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700211 if (absl::GetFlag(FLAGS_sort_by_time)) {
Milind Upadhyaye3215862022-03-24 19:59:19 -0700212 std::sort(file_list.begin(), file_list.end(),
213 [](std::string_view filename_1, std::string_view filename_2) {
214 return (FindImageTimestamp(filename_1) <
215 FindImageTimestamp(filename_2));
216 });
217 }
218
milind-ucafdd5d2022-03-01 19:58:57 -0800219 const aos::FlatbufferSpan<calibration::CalibrationData> calibration_data(
220 CalibrationData());
221
Milind Upadhyaya31f0272022-04-03 13:55:22 -0700222 const calibration::CameraCalibration *calibration =
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700223 CameraReader::FindCameraCalibration(
224 &calibration_data.message(), absl::GetFlag(FLAGS_calibration_node),
225 absl::GetFlag(FLAGS_calibration_team_number));
Milind Upadhyaya31f0272022-04-03 13:55:22 -0700226 const auto intrinsics = CameraReader::CameraIntrinsics(calibration);
227 const auto extrinsics = CameraReader::CameraExtrinsics(calibration);
228 const auto dist_coeffs = CameraReader::CameraDistCoeffs(calibration);
milind-ucafdd5d2022-03-01 19:58:57 -0800229
Milind Upadhyaya31f0272022-04-03 13:55:22 -0700230 // Compute undistortion map once for efficiency
231 const auto undistort_maps =
232 CameraReader::ComputeUndistortMaps(intrinsics, dist_coeffs);
Milind Upadhyay3c1a5c02022-03-27 16:27:19 -0700233
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800234 TargetEstimator estimator(intrinsics, extrinsics);
235
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700236 for (auto it = file_list.begin() + absl::GetFlag(FLAGS_skip);
237 it < file_list.end(); it++) {
Milind Upadhyay07f6f9e2022-03-18 18:40:34 -0700238 LOG(INFO) << "Reading file " << (it - file_list.begin()) << ": " << *it;
Milind Upadhyaya31f0272022-04-03 13:55:22 -0700239 cv::Mat image_mat =
240 CameraReader::UndistortImage(cv::imread(it->c_str()), undistort_maps);
Milind Upadhyay3c1a5c02022-03-27 16:27:19 -0700241
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800242 BlobDetector::BlobResult blob_result;
243 blob_result.binarized_image =
244 cv::Mat::zeros(cv::Size(image_mat.cols, image_mat.rows), CV_8UC1);
245 BlobDetector::ExtractBlobs(image_mat, &blob_result);
246
247 cv::Mat ret_image =
248 cv::Mat::zeros(cv::Size(image_mat.cols, image_mat.rows), CV_8UC3);
249 BlobDetector::DrawBlobs(blob_result, ret_image);
250
251 LOG(INFO) << ": # blobs: " << blob_result.filtered_blobs.size()
252 << " (# removed: "
253 << blob_result.unfiltered_blobs.size() -
254 blob_result.filtered_blobs.size()
255 << ")";
256
Milind Upadhyaye5003102022-04-02 22:16:39 -0700257 estimator.Solve(blob_result.filtered_stats,
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700258 absl::GetFlag(FLAGS_display_estimation)
259 ? std::make_optional(ret_image)
260 : std::nullopt);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800261 if (blob_result.filtered_blobs.size() > 0) {
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800262 estimator.DrawEstimate(ret_image);
Austin Schuha685b5d2022-04-02 14:53:54 -0700263 LOG(INFO) << "Read file " << (it - file_list.begin()) << ": " << *it;
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800264 }
265
266 cv::imshow("image", image_mat);
267 cv::imshow("mask", blob_result.binarized_image);
268 cv::imshow("blobs", ret_image);
269
Milind Upadhyaye3215862022-03-24 19:59:19 -0700270 constexpr size_t kWaitKeyDelay = 0; // ms
271 int keystroke = cv::waitKey(kWaitKeyDelay) & 0xFF;
272 // Ignore alt key
273 while (keystroke == 233) {
274 keystroke = cv::waitKey(kWaitKeyDelay);
275 }
276 if (keystroke == static_cast<int>('q')) {
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800277 return;
278 }
279 }
280}
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800281} // namespace
Stephan Pleinesf63bde82024-01-13 15:59:33 -0800282} // namespace y2022::vision
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800283
284// Quick and lightweight viewer for images
285int main(int argc, char **argv) {
286 aos::InitGoogle(&argc, &argv);
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700287 if (absl::GetFlag(FLAGS_png_dir) != "")
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800288 y2022::vision::ViewerLocal();
289 else
290 y2022::vision::ViewerMain();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800291}