blob: 5d09d5516f6d6e58f42c684ba38bbdb161143894 [file] [log] [blame]
Milind Upadhyayb7e3c242022-03-12 20:05:25 -08001#include "aos/events/logging/log_reader.h"
2#include "aos/events/simulated_event_loop.h"
3#include "aos/init.h"
Milind Upadhyaye3215862022-03-24 19:59:19 -07004#include "frc971/control_loops/drivetrain/drivetrain_status_generated.h"
5#include "frc971/input/joystick_state_generated.h"
Milind Upadhyayb7e3c242022-03-12 20:05:25 -08006#include "frc971/vision/vision_generated.h"
7#include "opencv2/calib3d.hpp"
8#include "opencv2/features2d.hpp"
9#include "opencv2/highgui/highgui.hpp"
10#include "opencv2/imgproc.hpp"
Milind Upadhyaye3215862022-03-24 19:59:19 -070011#include "y2022/control_loops/superstructure/superstructure_status_generated.h"
Milind Upadhyayb7e3c242022-03-12 20:05:25 -080012#include "y2022/vision/blob_detector.h"
13
Milind Upadhyaye3215862022-03-24 19:59:19 -070014DEFINE_string(pi, "pi3", "Node name to replay.");
Milind Upadhyayb7e3c242022-03-12 20:05:25 -080015DEFINE_string(image_save_prefix, "/tmp/img",
16 "Prefix to use for saving images from the logfile.");
17DEFINE_bool(display, false, "If true, display the images with a timeout.");
18DEFINE_bool(detected_only, false,
19 "If true, only write images which had blobs (unfiltered) detected");
20DEFINE_bool(filtered_only, false,
21 "If true, only write images which had blobs (filtered) detected");
Milind Upadhyaye3215862022-03-24 19:59:19 -070022DEFINE_bool(match_timestamps, false,
23 "If true, name the files based on the time since the robot was "
24 "enabled (match start). Only consider images during this time");
25DEFINE_string(logger_pi_log, "/tmp/logger_pi/", "Path to logger pi log");
26DEFINE_string(roborio_log, "/tmp/roborio/", "Path to roborio log");
Milind Upadhyayb7e3c242022-03-12 20:05:25 -080027
28namespace y2022 {
29namespace vision {
30namespace {
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 Upadhyayb7e3c242022-03-12 20:05:25 -080049 std::vector<std::string> unsorted_logfiles =
Milind Upadhyaye3215862022-03-24 19:59:19 -070050 aos::logger::FindLogs(FLAGS_roborio_log);
51 // Open logfiles
52 aos::logger::LogReader reader(aos::logger::SortParts(unsorted_logfiles));
53 reader.Register();
54 const aos::Node *roborio =
55 aos::configuration::GetNode(reader.configuration(), "roborio");
56
57 std::unique_ptr<aos::EventLoop> event_loop =
58 reader.event_loop_factory()->MakeEventLoop("roborio", roborio);
59
60 auto joystick_state_fetcher =
61 event_loop->MakeFetcher<aos::JoystickState>("/roborio/aos");
62 auto drivetrain_status_fetcher =
63 event_loop->MakeFetcher<frc971::control_loops::drivetrain::Status>(
64 "/drivetrain");
65 auto superstructure_status_fetcher =
66 event_loop->MakeFetcher<superstructure::Status>("/superstructure");
67
68 // Periodically check if the robot state updated
69 event_loop->AddPhasedLoop(
70 [&](int) {
71 // Find the match start and end times
72 if (joystick_state_fetcher.Fetch()) {
73 if (data->match_start == monotonic_clock::min_time &&
74 joystick_state_fetcher->enabled()) {
75 data->match_start =
76 joystick_state_fetcher.context().monotonic_event_time;
77 } else {
78 if (data->match_end == monotonic_clock::min_time &&
79 data->match_start != monotonic_clock::min_time &&
80 !joystick_state_fetcher->autonomous() &&
81 !joystick_state_fetcher->enabled()) {
82 data->match_end =
83 joystick_state_fetcher.context().monotonic_event_time;
84 }
85 }
86 }
87
88 // Add whether the robot was moving at a non-negligible speed to
89 // the image name for debugging.
90 drivetrain_status_fetcher.Fetch();
91 if (drivetrain_status_fetcher.get()) {
92 // If the robot speed was atleast this (m/s), it is
93 // considered moving.
94 constexpr double kMinMovingRobotSpeed = 0.5;
95 data->robot_moving[drivetrain_status_fetcher.context()
96 .monotonic_event_time] =
97 (std::abs(drivetrain_status_fetcher->robot_speed()) >=
98 kMinMovingRobotSpeed);
99 }
100
101 superstructure_status_fetcher.Fetch();
102 if (superstructure_status_fetcher.get()) {
103 data->superstructure_states[superstructure_status_fetcher.context()
104 .monotonic_event_time] =
105 superstructure_status_fetcher->state();
106 }
107 },
108 std::chrono::milliseconds(50));
109 reader.event_loop_factory()->Run();
110}
111
112template <typename T>
113T ClosestElement(const std::map<monotonic_clock::time_point, T> &map,
114 monotonic_clock::time_point now) {
115 T closest;
116
117 // The closest element is either the one right above it, or the element before
118 // that one
119 auto closest_it = map.lower_bound(now);
120 // Handle the case where now is greater than all times in the map
121 if (closest_it == map.cend()) {
122 closest_it--;
123 closest = closest_it->second;
124 } else {
125 // Start off with the closest as the first after now
126 closest = closest_it->second;
127 const monotonic_clock::duration after_duration = closest_it->first - now;
128 closest_it--;
129
130 // If there is a time before, check if that's closer to now
131 if (closest_it != map.cbegin()) {
132 const monotonic_clock::duration before_duration = now - closest_it->first;
133 if (before_duration < after_duration) {
134 closest = closest_it->second;
135 }
136 }
137 }
138
139 return closest;
140}
141
142// Extract images from the pi logs
143void ReplayPi(const ReplayData &data) {
144 if (FLAGS_match_timestamps) {
145 CHECK_NE(data.match_start, monotonic_clock::min_time)
146 << "Can't use match timestamps if match never started";
147 CHECK_NE(data.match_end, monotonic_clock::min_time)
148 << "Can't use match timestamps if match never ended";
149 }
150
151 std::vector<std::string> unsorted_logfiles =
152 aos::logger::FindLogs(FLAGS_logger_pi_log);
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800153
154 // Open logfiles
155 aos::logger::LogReader reader(aos::logger::SortParts(unsorted_logfiles));
156 reader.Register();
Milind Upadhyaye3215862022-03-24 19:59:19 -0700157 const aos::Node *pi =
158 aos::configuration::GetNode(reader.configuration(), FLAGS_pi);
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800159
Milind Upadhyaye3215862022-03-24 19:59:19 -0700160 std::unique_ptr<aos::EventLoop> event_loop =
161 reader.event_loop_factory()->MakeEventLoop("player", pi);
162
163 LOG(INFO) << "Match start: " << data.match_start
164 << ", match end: " << data.match_end;
165
166 size_t nonmatch_image_count = 0;
167
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800168 event_loop->MakeWatcher(
Milind Upadhyaye3215862022-03-24 19:59:19 -0700169 "/camera/decimated", [&](const frc971::vision::CameraImage &image) {
170 const auto match_start = data.match_start;
171 // Find the closest robot moving and superstructure state to now
172 const bool robot_moving =
173 ClosestElement(data.robot_moving, event_loop->monotonic_now());
174 const auto superstructure_state = ClosestElement(
175 data.superstructure_states, event_loop->monotonic_now());
176
177 if (FLAGS_match_timestamps) {
178 if (event_loop->monotonic_now() < data.match_start) {
179 // Ignore prematch images if we only care about ones during the
180 // match
181 return;
182 } else if (event_loop->monotonic_now() >= data.match_end) {
183 // We're done if the match is over and we only wanted match images
184 reader.event_loop_factory()->Exit();
185 return;
186 }
187 }
188
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800189 // Create color image:
190 cv::Mat image_color_mat(cv::Size(image.cols(), image.rows()), CV_8UC2,
191 (void *)image.data()->data());
192 cv::Mat image_mat(cv::Size(image.cols(), image.rows()), CV_8UC3);
193 cv::cvtColor(image_color_mat, image_mat, cv::COLOR_YUV2BGR_YUYV);
194
195 bool use_image = true;
196 if (FLAGS_detected_only || FLAGS_filtered_only) {
Milind Upadhyaya31f0272022-04-03 13:55:22 -0700197 // TODO(milind): if adding target estimation here in the future,
198 // undistortion is needed
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800199 BlobDetector::BlobResult blob_result;
200 BlobDetector::ExtractBlobs(image_mat, &blob_result);
201
202 use_image =
203 ((FLAGS_filtered_only ? blob_result.filtered_blobs.size()
204 : blob_result.unfiltered_blobs.size()) > 0);
205 }
Milind Upadhyaye3215862022-03-24 19:59:19 -0700206
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800207 if (use_image) {
208 if (!FLAGS_image_save_prefix.empty()) {
Milind Upadhyaye3215862022-03-24 19:59:19 -0700209 std::stringstream image_name;
210 image_name << FLAGS_image_save_prefix;
211
212 if (FLAGS_match_timestamps) {
213 // Add the time since match start into the image for debugging.
214 // We can match images with the game recording.
215 image_name << "match_"
216 << std::chrono::duration_cast<std::chrono::seconds>(
217 event_loop->monotonic_now() - match_start)
218 .count()
219 << 's';
220 } else {
221 image_name << nonmatch_image_count++;
222 }
223
224 // Add superstructure state to the filename
225 if (superstructure_state !=
226 superstructure::SuperstructureState::IDLE) {
227 std::string superstructure_state_name =
228 superstructure::EnumNameSuperstructureState(
229 superstructure_state);
230 std::transform(superstructure_state_name.begin(),
231 superstructure_state_name.end(),
232 superstructure_state_name.begin(),
233 [](char c) { return std::tolower(c); });
234 image_name << '_' << superstructure_state_name;
235 }
236
237 if (robot_moving) {
238 image_name << "_moving";
239 }
240
241 image_name << ".png";
242
243 cv::imwrite(image_name.str(), image_mat);
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800244 }
245 if (FLAGS_display) {
246 cv::imshow("Display", image_mat);
247 cv::waitKey(FLAGS_detected_only || FLAGS_filtered_only ? 10 : 1);
248 }
249 }
250 });
251
252 reader.event_loop_factory()->Run();
253}
254
Milind Upadhyaye3215862022-03-24 19:59:19 -0700255void ViewerMain() {
256 ReplayData data;
257 ReplayRoborio(&data);
258 ReplayPi(data);
259}
260
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800261} // namespace
262} // namespace vision
263} // namespace y2022
264
265// Quick and lightweight viewer for image logs
266int main(int argc, char **argv) {
267 aos::InitGoogle(&argc, &argv);
Milind Upadhyaye3215862022-03-24 19:59:19 -0700268 y2022::vision::ViewerMain();
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800269}