blob: 15427e41f53942388c8f1ca333776152e679d3ee [file] [log] [blame]
Philipp Schrader790cb542023-07-05 21:06:52 -07001#include "opencv2/calib3d.hpp"
2#include "opencv2/features2d.hpp"
3#include "opencv2/highgui/highgui.hpp"
4#include "opencv2/imgproc.hpp"
5
Milind Upadhyayb7e3c242022-03-12 20:05:25 -08006#include "aos/events/logging/log_reader.h"
7#include "aos/events/simulated_event_loop.h"
8#include "aos/init.h"
Milind Upadhyaye3215862022-03-24 19:59:19 -07009#include "frc971/control_loops/drivetrain/drivetrain_status_generated.h"
10#include "frc971/input/joystick_state_generated.h"
Milind Upadhyayb7e3c242022-03-12 20:05:25 -080011#include "frc971/vision/vision_generated.h"
Milind Upadhyaye3215862022-03-24 19:59:19 -070012#include "y2022/control_loops/superstructure/superstructure_status_generated.h"
Milind Upadhyayb7e3c242022-03-12 20:05:25 -080013#include "y2022/vision/blob_detector.h"
14
Milind Upadhyaye3215862022-03-24 19:59:19 -070015DEFINE_string(pi, "pi3", "Node name to replay.");
Milind Upadhyayb7e3c242022-03-12 20:05:25 -080016DEFINE_string(image_save_prefix, "/tmp/img",
17 "Prefix to use for saving images from the logfile.");
18DEFINE_bool(display, false, "If true, display the images with a timeout.");
19DEFINE_bool(detected_only, false,
20 "If true, only write images which had blobs (unfiltered) detected");
21DEFINE_bool(filtered_only, false,
22 "If true, only write images which had blobs (filtered) detected");
Milind Upadhyaye3215862022-03-24 19:59:19 -070023DEFINE_bool(match_timestamps, false,
24 "If true, name the files based on the time since the robot was "
25 "enabled (match start). Only consider images during this time");
26DEFINE_string(logger_pi_log, "/tmp/logger_pi/", "Path to logger pi log");
27DEFINE_string(roborio_log, "/tmp/roborio/", "Path to roborio log");
Milind Upadhyayb7e3c242022-03-12 20:05:25 -080028
Stephan Pleinesf63bde82024-01-13 15:59:33 -080029namespace y2022::vision {
Milind Upadhyayb7e3c242022-03-12 20:05:25 -080030namespace {
31
Milind Upadhyaye3215862022-03-24 19:59:19 -070032using aos::monotonic_clock;
33namespace superstructure = control_loops::superstructure;
34
35// Information to extract from the roborio log
36struct ReplayData {
37 monotonic_clock::time_point match_start;
38 monotonic_clock::time_point match_end;
39 std::map<monotonic_clock::time_point, bool> robot_moving;
40 std::map<monotonic_clock::time_point, superstructure::SuperstructureState>
41 superstructure_states;
42};
43
44// Extract the useful data from the roborio log to be used for naming images
45void ReplayRoborio(ReplayData *data) {
46 data->match_start = monotonic_clock::min_time;
47 data->match_end = monotonic_clock::min_time;
48
Milind Upadhyaye3215862022-03-24 19:59:19 -070049 // Open logfiles
Austin Schuhc1609732023-06-26 11:51:28 -070050 aos::logger::LogReader reader(
51 aos::logger::SortParts(aos::logger::FindLogs(FLAGS_roborio_log)));
Milind Upadhyaye3215862022-03-24 19:59:19 -070052 reader.Register();
53 const aos::Node *roborio =
54 aos::configuration::GetNode(reader.configuration(), "roborio");
55
56 std::unique_ptr<aos::EventLoop> event_loop =
57 reader.event_loop_factory()->MakeEventLoop("roborio", roborio);
58
59 auto joystick_state_fetcher =
60 event_loop->MakeFetcher<aos::JoystickState>("/roborio/aos");
61 auto drivetrain_status_fetcher =
62 event_loop->MakeFetcher<frc971::control_loops::drivetrain::Status>(
63 "/drivetrain");
64 auto superstructure_status_fetcher =
65 event_loop->MakeFetcher<superstructure::Status>("/superstructure");
66
67 // Periodically check if the robot state updated
68 event_loop->AddPhasedLoop(
69 [&](int) {
70 // Find the match start and end times
71 if (joystick_state_fetcher.Fetch()) {
72 if (data->match_start == monotonic_clock::min_time &&
73 joystick_state_fetcher->enabled()) {
74 data->match_start =
75 joystick_state_fetcher.context().monotonic_event_time;
76 } else {
77 if (data->match_end == monotonic_clock::min_time &&
78 data->match_start != monotonic_clock::min_time &&
79 !joystick_state_fetcher->autonomous() &&
80 !joystick_state_fetcher->enabled()) {
81 data->match_end =
82 joystick_state_fetcher.context().monotonic_event_time;
83 }
84 }
85 }
86
87 // Add whether the robot was moving at a non-negligible speed to
88 // the image name for debugging.
89 drivetrain_status_fetcher.Fetch();
90 if (drivetrain_status_fetcher.get()) {
91 // If the robot speed was atleast this (m/s), it is
92 // considered moving.
93 constexpr double kMinMovingRobotSpeed = 0.5;
94 data->robot_moving[drivetrain_status_fetcher.context()
95 .monotonic_event_time] =
96 (std::abs(drivetrain_status_fetcher->robot_speed()) >=
97 kMinMovingRobotSpeed);
98 }
99
100 superstructure_status_fetcher.Fetch();
101 if (superstructure_status_fetcher.get()) {
102 data->superstructure_states[superstructure_status_fetcher.context()
103 .monotonic_event_time] =
104 superstructure_status_fetcher->state();
105 }
106 },
107 std::chrono::milliseconds(50));
108 reader.event_loop_factory()->Run();
109}
110
111template <typename T>
112T ClosestElement(const std::map<monotonic_clock::time_point, T> &map,
113 monotonic_clock::time_point now) {
114 T closest;
115
116 // The closest element is either the one right above it, or the element before
117 // that one
118 auto closest_it = map.lower_bound(now);
119 // Handle the case where now is greater than all times in the map
120 if (closest_it == map.cend()) {
121 closest_it--;
122 closest = closest_it->second;
123 } else {
124 // Start off with the closest as the first after now
125 closest = closest_it->second;
126 const monotonic_clock::duration after_duration = closest_it->first - now;
127 closest_it--;
128
129 // If there is a time before, check if that's closer to now
130 if (closest_it != map.cbegin()) {
131 const monotonic_clock::duration before_duration = now - closest_it->first;
132 if (before_duration < after_duration) {
133 closest = closest_it->second;
134 }
135 }
136 }
137
138 return closest;
139}
140
141// Extract images from the pi logs
142void ReplayPi(const ReplayData &data) {
143 if (FLAGS_match_timestamps) {
144 CHECK_NE(data.match_start, monotonic_clock::min_time)
145 << "Can't use match timestamps if match never started";
146 CHECK_NE(data.match_end, monotonic_clock::min_time)
147 << "Can't use match timestamps if match never ended";
148 }
149
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800150 // Open logfiles
Austin Schuhc1609732023-06-26 11:51:28 -0700151 aos::logger::LogReader reader(
152 aos::logger::SortParts(aos::logger::FindLogs(FLAGS_logger_pi_log)));
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800153 reader.Register();
Milind Upadhyaye3215862022-03-24 19:59:19 -0700154 const aos::Node *pi =
155 aos::configuration::GetNode(reader.configuration(), FLAGS_pi);
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800156
Milind Upadhyaye3215862022-03-24 19:59:19 -0700157 std::unique_ptr<aos::EventLoop> event_loop =
158 reader.event_loop_factory()->MakeEventLoop("player", pi);
159
160 LOG(INFO) << "Match start: " << data.match_start
161 << ", match end: " << data.match_end;
162
163 size_t nonmatch_image_count = 0;
164
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800165 event_loop->MakeWatcher(
Milind Upadhyaye3215862022-03-24 19:59:19 -0700166 "/camera/decimated", [&](const frc971::vision::CameraImage &image) {
167 const auto match_start = data.match_start;
168 // Find the closest robot moving and superstructure state to now
169 const bool robot_moving =
170 ClosestElement(data.robot_moving, event_loop->monotonic_now());
171 const auto superstructure_state = ClosestElement(
172 data.superstructure_states, event_loop->monotonic_now());
173
174 if (FLAGS_match_timestamps) {
175 if (event_loop->monotonic_now() < data.match_start) {
176 // Ignore prematch images if we only care about ones during the
177 // match
178 return;
179 } else if (event_loop->monotonic_now() >= data.match_end) {
180 // We're done if the match is over and we only wanted match images
181 reader.event_loop_factory()->Exit();
182 return;
183 }
184 }
185
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800186 // Create color image:
187 cv::Mat image_color_mat(cv::Size(image.cols(), image.rows()), CV_8UC2,
188 (void *)image.data()->data());
189 cv::Mat image_mat(cv::Size(image.cols(), image.rows()), CV_8UC3);
190 cv::cvtColor(image_color_mat, image_mat, cv::COLOR_YUV2BGR_YUYV);
191
192 bool use_image = true;
193 if (FLAGS_detected_only || FLAGS_filtered_only) {
Milind Upadhyaya31f0272022-04-03 13:55:22 -0700194 // TODO(milind): if adding target estimation here in the future,
195 // undistortion is needed
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800196 BlobDetector::BlobResult blob_result;
197 BlobDetector::ExtractBlobs(image_mat, &blob_result);
198
199 use_image =
200 ((FLAGS_filtered_only ? blob_result.filtered_blobs.size()
201 : blob_result.unfiltered_blobs.size()) > 0);
202 }
Milind Upadhyaye3215862022-03-24 19:59:19 -0700203
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800204 if (use_image) {
205 if (!FLAGS_image_save_prefix.empty()) {
Milind Upadhyaye3215862022-03-24 19:59:19 -0700206 std::stringstream image_name;
207 image_name << FLAGS_image_save_prefix;
208
209 if (FLAGS_match_timestamps) {
210 // Add the time since match start into the image for debugging.
211 // We can match images with the game recording.
212 image_name << "match_"
213 << std::chrono::duration_cast<std::chrono::seconds>(
214 event_loop->monotonic_now() - match_start)
215 .count()
216 << 's';
217 } else {
218 image_name << nonmatch_image_count++;
219 }
220
221 // Add superstructure state to the filename
222 if (superstructure_state !=
223 superstructure::SuperstructureState::IDLE) {
224 std::string superstructure_state_name =
225 superstructure::EnumNameSuperstructureState(
226 superstructure_state);
227 std::transform(superstructure_state_name.begin(),
228 superstructure_state_name.end(),
229 superstructure_state_name.begin(),
230 [](char c) { return std::tolower(c); });
231 image_name << '_' << superstructure_state_name;
232 }
233
234 if (robot_moving) {
235 image_name << "_moving";
236 }
237
238 image_name << ".png";
239
240 cv::imwrite(image_name.str(), image_mat);
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800241 }
242 if (FLAGS_display) {
243 cv::imshow("Display", image_mat);
244 cv::waitKey(FLAGS_detected_only || FLAGS_filtered_only ? 10 : 1);
245 }
246 }
247 });
248
249 reader.event_loop_factory()->Run();
250}
251
Milind Upadhyaye3215862022-03-24 19:59:19 -0700252void ViewerMain() {
253 ReplayData data;
254 ReplayRoborio(&data);
255 ReplayPi(data);
256}
257
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800258} // namespace
Stephan Pleinesf63bde82024-01-13 15:59:33 -0800259} // namespace y2022::vision
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800260
261// Quick and lightweight viewer for image logs
262int main(int argc, char **argv) {
263 aos::InitGoogle(&argc, &argv);
Milind Upadhyaye3215862022-03-24 19:59:19 -0700264 y2022::vision::ViewerMain();
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800265}