blob: 7c35ce944fb1f952d18f7edd4f39dec1e09c6678 [file] [log] [blame]
Milind Upadhyaye3215862022-03-24 19:59:19 -07001#include <algorithm>
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -08002#include <map>
3#include <opencv2/calib3d.hpp>
4#include <opencv2/features2d.hpp>
5#include <opencv2/highgui/highgui.hpp>
6#include <opencv2/imgproc.hpp>
7#include <random>
8
9#include "aos/events/shm_event_loop.h"
10#include "aos/init.h"
11#include "aos/time/time.h"
Jim Ostrowski977850f2022-01-22 21:04:22 -080012#include "frc971/vision/vision_generated.h"
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080013#include "y2022/vision/blob_detector.h"
milind-ucafdd5d2022-03-01 19:58:57 -080014#include "y2022/vision/calibration_data.h"
Henry Speisere45e7a22022-02-04 23:17:01 -080015#include "y2022/vision/target_estimate_generated.h"
Milind Upadhyayf61e1482022-02-11 20:42:55 -080016#include "y2022/vision/target_estimator.h"
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080017
18DEFINE_string(capture, "",
19 "If set, capture a single image and save it to this filename.");
20DEFINE_string(channel, "/camera", "Channel name for the image.");
Austin Schuhc5fa6d92022-02-25 14:36:28 -080021DEFINE_string(config, "aos_config.json", "Path to the config file to use.");
Jim Ostrowski5caf81c2022-01-30 21:02:19 -080022DEFINE_string(png_dir, "", "Path to a set of images to display.");
milind-ucafdd5d2022-03-01 19:58:57 -080023DEFINE_string(calibration_node, "",
24 "If reading locally, use the calibration for this node");
25DEFINE_int32(
26 calibration_team_number, 971,
27 "If reading locally, use the calibration for a node with this team number");
Milind Upadhyayf61e1482022-02-11 20:42:55 -080028DEFINE_uint64(skip, 0,
29 "Number of images to skip if doing local reading (png_dir set).");
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080030DEFINE_bool(show_features, true, "Show the blobs.");
Milind Upadhyayf61e1482022-02-11 20:42:55 -080031DEFINE_bool(display_estimation, false,
32 "If true, display the target estimation graphically");
Milind Upadhyaye3215862022-03-24 19:59:19 -070033DEFINE_bool(sort_by_time, true, "If true, sort the images by time");
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080034
35namespace y2022 {
36namespace vision {
37namespace {
38
Jim Ostrowski210765a2022-02-27 12:52:14 -080039using namespace frc971::vision;
40
41std::map<int64_t, BlobDetector::BlobResult> target_est_map;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080042aos::Fetcher<frc971::vision::CameraImage> image_fetcher;
Henry Speisere45e7a22022-02-04 23:17:01 -080043aos::Fetcher<y2022::vision::TargetEstimate> target_estimate_fetcher;
44
Milind Upadhyayf61e1482022-02-11 20:42:55 -080045std::vector<cv::Point> FbsToCvPoints(
46 const flatbuffers::Vector<const Point *> &points_fbs) {
47 std::vector<cv::Point> points;
48 for (const Point *point : points_fbs) {
49 points.emplace_back(point->x(), point->y());
50 }
51 return points;
52}
53
Henry Speisere45e7a22022-02-04 23:17:01 -080054std::vector<std::vector<cv::Point>> FbsToCvBlobs(
James Kuszmauld230d7a2022-03-06 15:00:43 -080055 const flatbuffers::Vector<flatbuffers::Offset<Blob>> *blobs_fbs) {
56 if (blobs_fbs == nullptr) {
57 return {};
58 }
Henry Speisere45e7a22022-02-04 23:17:01 -080059 std::vector<std::vector<cv::Point>> blobs;
James Kuszmauld230d7a2022-03-06 15:00:43 -080060 for (const auto blob : *blobs_fbs) {
Milind Upadhyayf61e1482022-02-11 20:42:55 -080061 blobs.emplace_back(FbsToCvPoints(*blob->points()));
Henry Speisere45e7a22022-02-04 23:17:01 -080062 }
63 return blobs;
64}
65
66std::vector<BlobDetector::BlobStats> FbsToBlobStats(
67 const flatbuffers::Vector<flatbuffers::Offset<BlobStatsFbs>>
68 &blob_stats_fbs) {
69 std::vector<BlobDetector::BlobStats> blob_stats;
70 for (const auto stats_fbs : blob_stats_fbs) {
71 cv::Point centroid{stats_fbs->centroid()->x(), stats_fbs->centroid()->y()};
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080072 cv::Size size{stats_fbs->size()->width(), stats_fbs->size()->height()};
Henry Speisere45e7a22022-02-04 23:17:01 -080073 blob_stats.emplace_back(BlobDetector::BlobStats{
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080074 centroid, size, stats_fbs->aspect_ratio(), stats_fbs->area(),
Henry Speisere45e7a22022-02-04 23:17:01 -080075 static_cast<size_t>(stats_fbs->num_points())});
76 }
77 return blob_stats;
78}
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080079
80bool DisplayLoop() {
Jim Ostrowski210765a2022-02-27 12:52:14 -080081 int64_t target_timestamp = 0;
82 if (target_estimate_fetcher.Fetch()) {
83 const TargetEstimate *target_est = target_estimate_fetcher.get();
84 CHECK(target_est != nullptr)
85 << "Got null when trying to fetch target estimate";
86
87 target_timestamp = target_est->image_monotonic_timestamp_ns();
88 if (target_est->blob_result()->filtered_blobs()->size() > 0) {
89 VLOG(2) << "Got blobs for timestamp " << target_est << "\n";
90 }
91 // Store the TargetEstimate data so we can match timestamp with image
Milind Upadhyayf61e1482022-02-11 20:42:55 -080092 target_est_map[target_timestamp] = BlobDetector::BlobResult{
93 cv::Mat(),
James Kuszmauld230d7a2022-03-06 15:00:43 -080094 FbsToCvBlobs(target_est->blob_result()->filtered_blobs()),
95 FbsToCvBlobs(target_est->blob_result()->unfiltered_blobs()),
Milind Upadhyayf61e1482022-02-11 20:42:55 -080096 FbsToBlobStats(*target_est->blob_result()->blob_stats()),
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080097 FbsToBlobStats(*target_est->blob_result()->filtered_stats()),
Milind Upadhyayf61e1482022-02-11 20:42:55 -080098 cv::Point{target_est->blob_result()->centroid()->x(),
99 target_est->blob_result()->centroid()->y()}};
Jim Ostrowski210765a2022-02-27 12:52:14 -0800100 // Only keep last 10 matches
101 while (target_est_map.size() > 10u) {
102 target_est_map.erase(target_est_map.begin());
103 }
104 }
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800105 int64_t image_timestamp = 0;
Jim Ostrowski5caf81c2022-01-30 21:02:19 -0800106 if (!image_fetcher.Fetch()) {
Jim Ostrowski210765a2022-02-27 12:52:14 -0800107 VLOG(2) << "Couldn't fetch image";
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800108 return true;
109 }
Jim Ostrowski210765a2022-02-27 12:52:14 -0800110 const CameraImage *image = image_fetcher.get();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800111 CHECK(image != nullptr) << "Couldn't read image";
112 image_timestamp = image->monotonic_timestamp_ns();
113 VLOG(2) << "Got image at timestamp: " << image_timestamp;
114
115 // Create color image:
116 cv::Mat image_color_mat(cv::Size(image->cols(), image->rows()), CV_8UC2,
117 (void *)image->data()->data());
Milind Upadhyayec41e132022-02-05 17:14:05 -0800118 cv::Mat bgr_image(cv::Size(image->cols(), image->rows()), CV_8UC3);
Milind Upadhyay40522942022-02-19 15:30:31 -0800119 cv::cvtColor(image_color_mat, bgr_image, cv::COLOR_YUV2BGR_YUYV);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800120
121 if (!FLAGS_capture.empty()) {
Milind Upadhyayec41e132022-02-05 17:14:05 -0800122 cv::imwrite(FLAGS_capture, bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800123 return false;
124 }
125
Jim Ostrowski210765a2022-02-27 12:52:14 -0800126 auto target_est_it = target_est_map.find(image_timestamp);
127 if (target_est_it != target_est_map.end()) {
128 LOG(INFO) << image->monotonic_timestamp_ns() << ": # unfiltered blobs: "
129 << target_est_it->second.unfiltered_blobs.size()
130 << "; # filtered blobs: "
131 << target_est_it->second.filtered_blobs.size();
Henry Speisere45e7a22022-02-04 23:17:01 -0800132
Jim Ostrowski210765a2022-02-27 12:52:14 -0800133 cv::Mat ret_image =
134 cv::Mat::zeros(cv::Size(image->cols(), image->rows()), CV_8UC3);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800135 BlobDetector::DrawBlobs(target_est_it->second, ret_image);
Jim Ostrowski46a78382022-02-06 14:05:58 -0800136 cv::imshow("blobs", ret_image);
137 }
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800138
Milind Upadhyayec41e132022-02-05 17:14:05 -0800139 cv::imshow("image", bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800140
141 int keystroke = cv::waitKey(1);
142 if ((keystroke & 0xFF) == static_cast<int>('c')) {
143 // Convert again, to get clean image
Milind Upadhyayec41e132022-02-05 17:14:05 -0800144 cv::cvtColor(image_color_mat, bgr_image, cv::COLOR_YUV2BGR_YUYV);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800145 std::stringstream name;
146 name << "capture-" << aos::realtime_clock::now() << ".png";
Milind Upadhyayec41e132022-02-05 17:14:05 -0800147 cv::imwrite(name.str(), bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800148 LOG(INFO) << "Saved image file: " << name.str();
149 } else if ((keystroke & 0xFF) == static_cast<int>('q')) {
150 return false;
151 }
152 return true;
153}
154
155void ViewerMain() {
156 aos::FlatbufferDetachedBuffer<aos::Configuration> config =
157 aos::configuration::ReadConfig(FLAGS_config);
158
159 aos::ShmEventLoop event_loop(&config.message());
160
161 image_fetcher =
162 event_loop.MakeFetcher<frc971::vision::CameraImage>(FLAGS_channel);
163
Jim Ostrowski46a78382022-02-06 14:05:58 -0800164 target_estimate_fetcher =
165 event_loop.MakeFetcher<y2022::vision::TargetEstimate>(FLAGS_channel);
166
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800167 // Run the display loop
168 event_loop.AddPhasedLoop(
169 [&event_loop](int) {
170 if (!DisplayLoop()) {
171 LOG(INFO) << "Calling event_loop Exit";
172 event_loop.Exit();
173 };
174 },
175 ::std::chrono::milliseconds(100));
176
177 event_loop.Run();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800178}
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800179
Milind Upadhyaye3215862022-03-24 19:59:19 -0700180size_t FindImageTimestamp(std::string_view filename) {
181 // Find the first number in the string
182 const auto timestamp_start = std::find_if(
183 filename.begin(), filename.end(), [](char c) { return std::isdigit(c); });
184 CHECK_NE(timestamp_start, filename.end())
185 << "Expected a number in image filename, got " << filename;
186 const auto timestamp_end =
187 std::find_if_not(timestamp_start + 1, filename.end(),
188 [](char c) { return std::isdigit(c); });
189
190 return static_cast<size_t>(
191 std::atoi(filename
192 .substr(timestamp_start - filename.begin(),
193 timestamp_end - timestamp_start)
194 .data()));
195}
196
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800197void ViewerLocal() {
198 std::vector<cv::String> file_list;
199 cv::glob(FLAGS_png_dir + "/*.png", file_list, false);
200
Milind Upadhyaye3215862022-03-24 19:59:19 -0700201 // Sort the images by timestamp
202 if (FLAGS_sort_by_time) {
203 std::sort(file_list.begin(), file_list.end(),
204 [](std::string_view filename_1, std::string_view filename_2) {
205 return (FindImageTimestamp(filename_1) <
206 FindImageTimestamp(filename_2));
207 });
208 }
209
milind-ucafdd5d2022-03-01 19:58:57 -0800210 const aos::FlatbufferSpan<calibration::CalibrationData> calibration_data(
211 CalibrationData());
212
213 const calibration::CameraCalibration *calibration = nullptr;
214 for (const calibration::CameraCalibration *candidate :
215 *calibration_data.message().camera_calibrations()) {
216 if ((candidate->node_name()->string_view() == FLAGS_calibration_node) &&
217 (candidate->team_number() == FLAGS_calibration_team_number)) {
218 calibration = candidate;
219 break;
220 }
221 }
222
223 CHECK(calibration) << "No calibration data found for node \""
224 << FLAGS_calibration_node << "\" with team number "
225 << FLAGS_calibration_team_number;
226
227 auto intrinsics_float = cv::Mat(3, 3, CV_32F,
228 const_cast<void *>(static_cast<const void *>(
229 calibration->intrinsics()->data())));
230 cv::Mat intrinsics;
231 intrinsics_float.convertTo(intrinsics, CV_64F);
232
Milind Upadhyaya4cce2f2022-03-13 21:50:13 -0700233 const frc971::vision::calibration::TransformationMatrix *transform =
234 calibration->has_turret_extrinsics() ? calibration->turret_extrinsics()
235 : calibration->fixed_extrinsics();
236
237 const auto extrinsics_float = cv::Mat(
238 4, 4, CV_32F,
239 const_cast<void *>(static_cast<const void *>(transform->data()->data())));
milind-ucafdd5d2022-03-01 19:58:57 -0800240 cv::Mat extrinsics;
241 extrinsics_float.convertTo(extrinsics, CV_64F);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800242
243 TargetEstimator estimator(intrinsics, extrinsics);
244
Milind Upadhyayae998722022-03-13 12:45:55 -0700245 for (auto it = file_list.begin() + FLAGS_skip; it < file_list.end(); it++) {
Milind Upadhyay07f6f9e2022-03-18 18:40:34 -0700246 LOG(INFO) << "Reading file " << (it - file_list.begin()) << ": " << *it;
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800247 cv::Mat image_mat = cv::imread(it->c_str());
248 BlobDetector::BlobResult blob_result;
249 blob_result.binarized_image =
250 cv::Mat::zeros(cv::Size(image_mat.cols, image_mat.rows), CV_8UC1);
251 BlobDetector::ExtractBlobs(image_mat, &blob_result);
252
253 cv::Mat ret_image =
254 cv::Mat::zeros(cv::Size(image_mat.cols, image_mat.rows), CV_8UC3);
255 BlobDetector::DrawBlobs(blob_result, ret_image);
256
257 LOG(INFO) << ": # blobs: " << blob_result.filtered_blobs.size()
258 << " (# removed: "
259 << blob_result.unfiltered_blobs.size() -
260 blob_result.filtered_blobs.size()
261 << ")";
262
263 if (blob_result.filtered_blobs.size() > 0) {
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800264 estimator.Solve(blob_result.filtered_stats,
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800265 FLAGS_display_estimation ? std::make_optional(ret_image)
266 : std::nullopt);
267 estimator.DrawEstimate(ret_image);
268 }
269
270 cv::imshow("image", image_mat);
271 cv::imshow("mask", blob_result.binarized_image);
272 cv::imshow("blobs", ret_image);
273
Milind Upadhyaye3215862022-03-24 19:59:19 -0700274 constexpr size_t kWaitKeyDelay = 0; // ms
275 int keystroke = cv::waitKey(kWaitKeyDelay) & 0xFF;
276 // Ignore alt key
277 while (keystroke == 233) {
278 keystroke = cv::waitKey(kWaitKeyDelay);
279 }
280 if (keystroke == static_cast<int>('q')) {
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800281 return;
282 }
283 }
284}
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800285} // namespace
286} // namespace vision
287} // namespace y2022
288
289// Quick and lightweight viewer for images
290int main(int argc, char **argv) {
291 aos::InitGoogle(&argc, &argv);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800292 if (FLAGS_png_dir != "")
293 y2022::vision::ViewerLocal();
294 else
295 y2022::vision::ViewerMain();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800296}