blob: f847dbdf3a4d41a40ea2173a93ea3d806adf1d65 [file] [log] [blame]
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -08001#include <map>
2#include <opencv2/calib3d.hpp>
3#include <opencv2/features2d.hpp>
4#include <opencv2/highgui/highgui.hpp>
5#include <opencv2/imgproc.hpp>
6#include <random>
7
8#include "aos/events/shm_event_loop.h"
9#include "aos/init.h"
10#include "aos/time/time.h"
Jim Ostrowski977850f2022-01-22 21:04:22 -080011#include "frc971/vision/vision_generated.h"
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080012#include "y2022/vision/blob_detector.h"
milind-ucafdd5d2022-03-01 19:58:57 -080013#include "y2022/vision/calibration_data.h"
Henry Speisere45e7a22022-02-04 23:17:01 -080014#include "y2022/vision/target_estimate_generated.h"
Milind Upadhyayf61e1482022-02-11 20:42:55 -080015#include "y2022/vision/target_estimator.h"
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080016
17DEFINE_string(capture, "",
18 "If set, capture a single image and save it to this filename.");
19DEFINE_string(channel, "/camera", "Channel name for the image.");
Austin Schuhc5fa6d92022-02-25 14:36:28 -080020DEFINE_string(config, "aos_config.json", "Path to the config file to use.");
Jim Ostrowski5caf81c2022-01-30 21:02:19 -080021DEFINE_string(png_dir, "", "Path to a set of images to display.");
milind-ucafdd5d2022-03-01 19:58:57 -080022DEFINE_string(calibration_node, "",
23 "If reading locally, use the calibration for this node");
24DEFINE_int32(
25 calibration_team_number, 971,
26 "If reading locally, use the calibration for a node with this team number");
Milind Upadhyayf61e1482022-02-11 20:42:55 -080027DEFINE_uint64(skip, 0,
28 "Number of images to skip if doing local reading (png_dir set).");
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080029DEFINE_bool(show_features, true, "Show the blobs.");
Milind Upadhyayf61e1482022-02-11 20:42:55 -080030DEFINE_bool(display_estimation, false,
31 "If true, display the target estimation graphically");
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080032
33namespace y2022 {
34namespace vision {
35namespace {
36
Jim Ostrowski210765a2022-02-27 12:52:14 -080037using namespace frc971::vision;
38
39std::map<int64_t, BlobDetector::BlobResult> target_est_map;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080040aos::Fetcher<frc971::vision::CameraImage> image_fetcher;
Henry Speisere45e7a22022-02-04 23:17:01 -080041aos::Fetcher<y2022::vision::TargetEstimate> target_estimate_fetcher;
42
Milind Upadhyayf61e1482022-02-11 20:42:55 -080043std::vector<cv::Point> FbsToCvPoints(
44 const flatbuffers::Vector<const Point *> &points_fbs) {
45 std::vector<cv::Point> points;
46 for (const Point *point : points_fbs) {
47 points.emplace_back(point->x(), point->y());
48 }
49 return points;
50}
51
Henry Speisere45e7a22022-02-04 23:17:01 -080052std::vector<std::vector<cv::Point>> FbsToCvBlobs(
James Kuszmauld230d7a2022-03-06 15:00:43 -080053 const flatbuffers::Vector<flatbuffers::Offset<Blob>> *blobs_fbs) {
54 if (blobs_fbs == nullptr) {
55 return {};
56 }
Henry Speisere45e7a22022-02-04 23:17:01 -080057 std::vector<std::vector<cv::Point>> blobs;
James Kuszmauld230d7a2022-03-06 15:00:43 -080058 for (const auto blob : *blobs_fbs) {
Milind Upadhyayf61e1482022-02-11 20:42:55 -080059 blobs.emplace_back(FbsToCvPoints(*blob->points()));
Henry Speisere45e7a22022-02-04 23:17:01 -080060 }
61 return blobs;
62}
63
64std::vector<BlobDetector::BlobStats> FbsToBlobStats(
65 const flatbuffers::Vector<flatbuffers::Offset<BlobStatsFbs>>
66 &blob_stats_fbs) {
67 std::vector<BlobDetector::BlobStats> blob_stats;
68 for (const auto stats_fbs : blob_stats_fbs) {
69 cv::Point centroid{stats_fbs->centroid()->x(), stats_fbs->centroid()->y()};
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080070 cv::Size size{stats_fbs->size()->width(), stats_fbs->size()->height()};
Henry Speisere45e7a22022-02-04 23:17:01 -080071 blob_stats.emplace_back(BlobDetector::BlobStats{
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080072 centroid, size, stats_fbs->aspect_ratio(), stats_fbs->area(),
Henry Speisere45e7a22022-02-04 23:17:01 -080073 static_cast<size_t>(stats_fbs->num_points())});
74 }
75 return blob_stats;
76}
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080077
78bool DisplayLoop() {
Jim Ostrowski210765a2022-02-27 12:52:14 -080079 int64_t target_timestamp = 0;
80 if (target_estimate_fetcher.Fetch()) {
81 const TargetEstimate *target_est = target_estimate_fetcher.get();
82 CHECK(target_est != nullptr)
83 << "Got null when trying to fetch target estimate";
84
85 target_timestamp = target_est->image_monotonic_timestamp_ns();
86 if (target_est->blob_result()->filtered_blobs()->size() > 0) {
87 VLOG(2) << "Got blobs for timestamp " << target_est << "\n";
88 }
89 // Store the TargetEstimate data so we can match timestamp with image
Milind Upadhyayf61e1482022-02-11 20:42:55 -080090 target_est_map[target_timestamp] = BlobDetector::BlobResult{
91 cv::Mat(),
James Kuszmauld230d7a2022-03-06 15:00:43 -080092 FbsToCvBlobs(target_est->blob_result()->filtered_blobs()),
93 FbsToCvBlobs(target_est->blob_result()->unfiltered_blobs()),
Milind Upadhyayf61e1482022-02-11 20:42:55 -080094 FbsToBlobStats(*target_est->blob_result()->blob_stats()),
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080095 FbsToBlobStats(*target_est->blob_result()->filtered_stats()),
Milind Upadhyayf61e1482022-02-11 20:42:55 -080096 cv::Point{target_est->blob_result()->centroid()->x(),
97 target_est->blob_result()->centroid()->y()}};
Jim Ostrowski210765a2022-02-27 12:52:14 -080098 // Only keep last 10 matches
99 while (target_est_map.size() > 10u) {
100 target_est_map.erase(target_est_map.begin());
101 }
102 }
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800103 int64_t image_timestamp = 0;
Jim Ostrowski5caf81c2022-01-30 21:02:19 -0800104 if (!image_fetcher.Fetch()) {
Jim Ostrowski210765a2022-02-27 12:52:14 -0800105 VLOG(2) << "Couldn't fetch image";
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800106 return true;
107 }
Jim Ostrowski210765a2022-02-27 12:52:14 -0800108 const CameraImage *image = image_fetcher.get();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800109 CHECK(image != nullptr) << "Couldn't read image";
110 image_timestamp = image->monotonic_timestamp_ns();
111 VLOG(2) << "Got image at timestamp: " << image_timestamp;
112
113 // Create color image:
114 cv::Mat image_color_mat(cv::Size(image->cols(), image->rows()), CV_8UC2,
115 (void *)image->data()->data());
Milind Upadhyayec41e132022-02-05 17:14:05 -0800116 cv::Mat bgr_image(cv::Size(image->cols(), image->rows()), CV_8UC3);
Milind Upadhyay40522942022-02-19 15:30:31 -0800117 cv::cvtColor(image_color_mat, bgr_image, cv::COLOR_YUV2BGR_YUYV);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800118
119 if (!FLAGS_capture.empty()) {
Milind Upadhyayec41e132022-02-05 17:14:05 -0800120 cv::imwrite(FLAGS_capture, bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800121 return false;
122 }
123
Jim Ostrowski210765a2022-02-27 12:52:14 -0800124 auto target_est_it = target_est_map.find(image_timestamp);
125 if (target_est_it != target_est_map.end()) {
126 LOG(INFO) << image->monotonic_timestamp_ns() << ": # unfiltered blobs: "
127 << target_est_it->second.unfiltered_blobs.size()
128 << "; # filtered blobs: "
129 << target_est_it->second.filtered_blobs.size();
Henry Speisere45e7a22022-02-04 23:17:01 -0800130
Jim Ostrowski210765a2022-02-27 12:52:14 -0800131 cv::Mat ret_image =
132 cv::Mat::zeros(cv::Size(image->cols(), image->rows()), CV_8UC3);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800133 BlobDetector::DrawBlobs(target_est_it->second, ret_image);
Jim Ostrowski46a78382022-02-06 14:05:58 -0800134 cv::imshow("blobs", ret_image);
135 }
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800136
Milind Upadhyayec41e132022-02-05 17:14:05 -0800137 cv::imshow("image", bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800138
139 int keystroke = cv::waitKey(1);
140 if ((keystroke & 0xFF) == static_cast<int>('c')) {
141 // Convert again, to get clean image
Milind Upadhyayec41e132022-02-05 17:14:05 -0800142 cv::cvtColor(image_color_mat, bgr_image, cv::COLOR_YUV2BGR_YUYV);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800143 std::stringstream name;
144 name << "capture-" << aos::realtime_clock::now() << ".png";
Milind Upadhyayec41e132022-02-05 17:14:05 -0800145 cv::imwrite(name.str(), bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800146 LOG(INFO) << "Saved image file: " << name.str();
147 } else if ((keystroke & 0xFF) == static_cast<int>('q')) {
148 return false;
149 }
150 return true;
151}
152
153void ViewerMain() {
154 aos::FlatbufferDetachedBuffer<aos::Configuration> config =
155 aos::configuration::ReadConfig(FLAGS_config);
156
157 aos::ShmEventLoop event_loop(&config.message());
158
159 image_fetcher =
160 event_loop.MakeFetcher<frc971::vision::CameraImage>(FLAGS_channel);
161
Jim Ostrowski46a78382022-02-06 14:05:58 -0800162 target_estimate_fetcher =
163 event_loop.MakeFetcher<y2022::vision::TargetEstimate>(FLAGS_channel);
164
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800165 // Run the display loop
166 event_loop.AddPhasedLoop(
167 [&event_loop](int) {
168 if (!DisplayLoop()) {
169 LOG(INFO) << "Calling event_loop Exit";
170 event_loop.Exit();
171 };
172 },
173 ::std::chrono::milliseconds(100));
174
175 event_loop.Run();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800176}
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800177
178// TODO(milind): delete this when viewer can accumulate local images and results
179void ViewerLocal() {
180 std::vector<cv::String> file_list;
181 cv::glob(FLAGS_png_dir + "/*.png", file_list, false);
182
milind-ucafdd5d2022-03-01 19:58:57 -0800183 const aos::FlatbufferSpan<calibration::CalibrationData> calibration_data(
184 CalibrationData());
185
186 const calibration::CameraCalibration *calibration = nullptr;
187 for (const calibration::CameraCalibration *candidate :
188 *calibration_data.message().camera_calibrations()) {
189 if ((candidate->node_name()->string_view() == FLAGS_calibration_node) &&
190 (candidate->team_number() == FLAGS_calibration_team_number)) {
191 calibration = candidate;
192 break;
193 }
194 }
195
196 CHECK(calibration) << "No calibration data found for node \""
197 << FLAGS_calibration_node << "\" with team number "
198 << FLAGS_calibration_team_number;
199
200 auto intrinsics_float = cv::Mat(3, 3, CV_32F,
201 const_cast<void *>(static_cast<const void *>(
202 calibration->intrinsics()->data())));
203 cv::Mat intrinsics;
204 intrinsics_float.convertTo(intrinsics, CV_64F);
205
206 const auto extrinsics_float =
207 cv::Mat(4, 4, CV_32F,
208 const_cast<void *>(static_cast<const void *>(
209 calibration->fixed_extrinsics()->data()->data())));
210 cv::Mat extrinsics;
211 extrinsics_float.convertTo(extrinsics, CV_64F);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800212
213 TargetEstimator estimator(intrinsics, extrinsics);
214
Milind Upadhyayae998722022-03-13 12:45:55 -0700215 for (auto it = file_list.begin() + FLAGS_skip; it < file_list.end(); it++) {
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800216 LOG(INFO) << "Reading file " << *it;
217 cv::Mat image_mat = cv::imread(it->c_str());
218 BlobDetector::BlobResult blob_result;
219 blob_result.binarized_image =
220 cv::Mat::zeros(cv::Size(image_mat.cols, image_mat.rows), CV_8UC1);
221 BlobDetector::ExtractBlobs(image_mat, &blob_result);
222
223 cv::Mat ret_image =
224 cv::Mat::zeros(cv::Size(image_mat.cols, image_mat.rows), CV_8UC3);
225 BlobDetector::DrawBlobs(blob_result, ret_image);
226
227 LOG(INFO) << ": # blobs: " << blob_result.filtered_blobs.size()
228 << " (# removed: "
229 << blob_result.unfiltered_blobs.size() -
230 blob_result.filtered_blobs.size()
231 << ")";
232
233 if (blob_result.filtered_blobs.size() > 0) {
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800234 estimator.Solve(blob_result.filtered_stats,
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800235 FLAGS_display_estimation ? std::make_optional(ret_image)
236 : std::nullopt);
237 estimator.DrawEstimate(ret_image);
238 }
239
240 cv::imshow("image", image_mat);
241 cv::imshow("mask", blob_result.binarized_image);
242 cv::imshow("blobs", ret_image);
243
244 int keystroke = cv::waitKey(0);
245 if ((keystroke & 0xFF) == static_cast<int>('q')) {
246 return;
247 }
248 }
249}
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800250} // namespace
251} // namespace vision
252} // namespace y2022
253
254// Quick and lightweight viewer for images
255int main(int argc, char **argv) {
256 aos::InitGoogle(&argc, &argv);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800257 if (FLAGS_png_dir != "")
258 y2022::vision::ViewerLocal();
259 else
260 y2022::vision::ViewerMain();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800261}