blob: 66087e5c00d5de2ff170b3cf590be2e6926e2456 [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
29namespace y2022 {
30namespace vision {
31namespace {
32
Milind Upadhyaye3215862022-03-24 19:59:19 -070033using aos::monotonic_clock;
34namespace superstructure = control_loops::superstructure;
35
36// Information to extract from the roborio log
37struct ReplayData {
38 monotonic_clock::time_point match_start;
39 monotonic_clock::time_point match_end;
40 std::map<monotonic_clock::time_point, bool> robot_moving;
41 std::map<monotonic_clock::time_point, superstructure::SuperstructureState>
42 superstructure_states;
43};
44
45// Extract the useful data from the roborio log to be used for naming images
46void ReplayRoborio(ReplayData *data) {
47 data->match_start = monotonic_clock::min_time;
48 data->match_end = monotonic_clock::min_time;
49
Milind Upadhyayb7e3c242022-03-12 20:05:25 -080050 std::vector<std::string> unsorted_logfiles =
Milind Upadhyaye3215862022-03-24 19:59:19 -070051 aos::logger::FindLogs(FLAGS_roborio_log);
52 // Open logfiles
53 aos::logger::LogReader reader(aos::logger::SortParts(unsorted_logfiles));
54 reader.Register();
55 const aos::Node *roborio =
56 aos::configuration::GetNode(reader.configuration(), "roborio");
57
58 std::unique_ptr<aos::EventLoop> event_loop =
59 reader.event_loop_factory()->MakeEventLoop("roborio", roborio);
60
61 auto joystick_state_fetcher =
62 event_loop->MakeFetcher<aos::JoystickState>("/roborio/aos");
63 auto drivetrain_status_fetcher =
64 event_loop->MakeFetcher<frc971::control_loops::drivetrain::Status>(
65 "/drivetrain");
66 auto superstructure_status_fetcher =
67 event_loop->MakeFetcher<superstructure::Status>("/superstructure");
68
69 // Periodically check if the robot state updated
70 event_loop->AddPhasedLoop(
71 [&](int) {
72 // Find the match start and end times
73 if (joystick_state_fetcher.Fetch()) {
74 if (data->match_start == monotonic_clock::min_time &&
75 joystick_state_fetcher->enabled()) {
76 data->match_start =
77 joystick_state_fetcher.context().monotonic_event_time;
78 } else {
79 if (data->match_end == monotonic_clock::min_time &&
80 data->match_start != monotonic_clock::min_time &&
81 !joystick_state_fetcher->autonomous() &&
82 !joystick_state_fetcher->enabled()) {
83 data->match_end =
84 joystick_state_fetcher.context().monotonic_event_time;
85 }
86 }
87 }
88
89 // Add whether the robot was moving at a non-negligible speed to
90 // the image name for debugging.
91 drivetrain_status_fetcher.Fetch();
92 if (drivetrain_status_fetcher.get()) {
93 // If the robot speed was atleast this (m/s), it is
94 // considered moving.
95 constexpr double kMinMovingRobotSpeed = 0.5;
96 data->robot_moving[drivetrain_status_fetcher.context()
97 .monotonic_event_time] =
98 (std::abs(drivetrain_status_fetcher->robot_speed()) >=
99 kMinMovingRobotSpeed);
100 }
101
102 superstructure_status_fetcher.Fetch();
103 if (superstructure_status_fetcher.get()) {
104 data->superstructure_states[superstructure_status_fetcher.context()
105 .monotonic_event_time] =
106 superstructure_status_fetcher->state();
107 }
108 },
109 std::chrono::milliseconds(50));
110 reader.event_loop_factory()->Run();
111}
112
113template <typename T>
114T ClosestElement(const std::map<monotonic_clock::time_point, T> &map,
115 monotonic_clock::time_point now) {
116 T closest;
117
118 // The closest element is either the one right above it, or the element before
119 // that one
120 auto closest_it = map.lower_bound(now);
121 // Handle the case where now is greater than all times in the map
122 if (closest_it == map.cend()) {
123 closest_it--;
124 closest = closest_it->second;
125 } else {
126 // Start off with the closest as the first after now
127 closest = closest_it->second;
128 const monotonic_clock::duration after_duration = closest_it->first - now;
129 closest_it--;
130
131 // If there is a time before, check if that's closer to now
132 if (closest_it != map.cbegin()) {
133 const monotonic_clock::duration before_duration = now - closest_it->first;
134 if (before_duration < after_duration) {
135 closest = closest_it->second;
136 }
137 }
138 }
139
140 return closest;
141}
142
143// Extract images from the pi logs
144void ReplayPi(const ReplayData &data) {
145 if (FLAGS_match_timestamps) {
146 CHECK_NE(data.match_start, monotonic_clock::min_time)
147 << "Can't use match timestamps if match never started";
148 CHECK_NE(data.match_end, monotonic_clock::min_time)
149 << "Can't use match timestamps if match never ended";
150 }
151
152 std::vector<std::string> unsorted_logfiles =
153 aos::logger::FindLogs(FLAGS_logger_pi_log);
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800154
155 // Open logfiles
156 aos::logger::LogReader reader(aos::logger::SortParts(unsorted_logfiles));
157 reader.Register();
Milind Upadhyaye3215862022-03-24 19:59:19 -0700158 const aos::Node *pi =
159 aos::configuration::GetNode(reader.configuration(), FLAGS_pi);
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800160
Milind Upadhyaye3215862022-03-24 19:59:19 -0700161 std::unique_ptr<aos::EventLoop> event_loop =
162 reader.event_loop_factory()->MakeEventLoop("player", pi);
163
164 LOG(INFO) << "Match start: " << data.match_start
165 << ", match end: " << data.match_end;
166
167 size_t nonmatch_image_count = 0;
168
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800169 event_loop->MakeWatcher(
Milind Upadhyaye3215862022-03-24 19:59:19 -0700170 "/camera/decimated", [&](const frc971::vision::CameraImage &image) {
171 const auto match_start = data.match_start;
172 // Find the closest robot moving and superstructure state to now
173 const bool robot_moving =
174 ClosestElement(data.robot_moving, event_loop->monotonic_now());
175 const auto superstructure_state = ClosestElement(
176 data.superstructure_states, event_loop->monotonic_now());
177
178 if (FLAGS_match_timestamps) {
179 if (event_loop->monotonic_now() < data.match_start) {
180 // Ignore prematch images if we only care about ones during the
181 // match
182 return;
183 } else if (event_loop->monotonic_now() >= data.match_end) {
184 // We're done if the match is over and we only wanted match images
185 reader.event_loop_factory()->Exit();
186 return;
187 }
188 }
189
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800190 // Create color image:
191 cv::Mat image_color_mat(cv::Size(image.cols(), image.rows()), CV_8UC2,
192 (void *)image.data()->data());
193 cv::Mat image_mat(cv::Size(image.cols(), image.rows()), CV_8UC3);
194 cv::cvtColor(image_color_mat, image_mat, cv::COLOR_YUV2BGR_YUYV);
195
196 bool use_image = true;
197 if (FLAGS_detected_only || FLAGS_filtered_only) {
Milind Upadhyaya31f0272022-04-03 13:55:22 -0700198 // TODO(milind): if adding target estimation here in the future,
199 // undistortion is needed
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800200 BlobDetector::BlobResult blob_result;
201 BlobDetector::ExtractBlobs(image_mat, &blob_result);
202
203 use_image =
204 ((FLAGS_filtered_only ? blob_result.filtered_blobs.size()
205 : blob_result.unfiltered_blobs.size()) > 0);
206 }
Milind Upadhyaye3215862022-03-24 19:59:19 -0700207
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800208 if (use_image) {
209 if (!FLAGS_image_save_prefix.empty()) {
Milind Upadhyaye3215862022-03-24 19:59:19 -0700210 std::stringstream image_name;
211 image_name << FLAGS_image_save_prefix;
212
213 if (FLAGS_match_timestamps) {
214 // Add the time since match start into the image for debugging.
215 // We can match images with the game recording.
216 image_name << "match_"
217 << std::chrono::duration_cast<std::chrono::seconds>(
218 event_loop->monotonic_now() - match_start)
219 .count()
220 << 's';
221 } else {
222 image_name << nonmatch_image_count++;
223 }
224
225 // Add superstructure state to the filename
226 if (superstructure_state !=
227 superstructure::SuperstructureState::IDLE) {
228 std::string superstructure_state_name =
229 superstructure::EnumNameSuperstructureState(
230 superstructure_state);
231 std::transform(superstructure_state_name.begin(),
232 superstructure_state_name.end(),
233 superstructure_state_name.begin(),
234 [](char c) { return std::tolower(c); });
235 image_name << '_' << superstructure_state_name;
236 }
237
238 if (robot_moving) {
239 image_name << "_moving";
240 }
241
242 image_name << ".png";
243
244 cv::imwrite(image_name.str(), image_mat);
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800245 }
246 if (FLAGS_display) {
247 cv::imshow("Display", image_mat);
248 cv::waitKey(FLAGS_detected_only || FLAGS_filtered_only ? 10 : 1);
249 }
250 }
251 });
252
253 reader.event_loop_factory()->Run();
254}
255
Milind Upadhyaye3215862022-03-24 19:59:19 -0700256void ViewerMain() {
257 ReplayData data;
258 ReplayRoborio(&data);
259 ReplayPi(data);
260}
261
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800262} // namespace
263} // namespace vision
264} // namespace y2022
265
266// Quick and lightweight viewer for image logs
267int main(int argc, char **argv) {
268 aos::InitGoogle(&argc, &argv);
Milind Upadhyaye3215862022-03-24 19:59:19 -0700269 y2022::vision::ViewerMain();
Milind Upadhyayb7e3c242022-03-12 20:05:25 -0800270}