blob: dfcd49dccf5f065222ee5be0569fb5b4e878329c [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(
53 const flatbuffers::Vector<flatbuffers::Offset<Blob>> &blobs_fbs) {
54 std::vector<std::vector<cv::Point>> blobs;
55 for (const auto blob : blobs_fbs) {
Milind Upadhyayf61e1482022-02-11 20:42:55 -080056 blobs.emplace_back(FbsToCvPoints(*blob->points()));
Henry Speisere45e7a22022-02-04 23:17:01 -080057 }
58 return blobs;
59}
60
61std::vector<BlobDetector::BlobStats> FbsToBlobStats(
62 const flatbuffers::Vector<flatbuffers::Offset<BlobStatsFbs>>
63 &blob_stats_fbs) {
64 std::vector<BlobDetector::BlobStats> blob_stats;
65 for (const auto stats_fbs : blob_stats_fbs) {
66 cv::Point centroid{stats_fbs->centroid()->x(), stats_fbs->centroid()->y()};
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080067 cv::Size size{stats_fbs->size()->width(), stats_fbs->size()->height()};
Henry Speisere45e7a22022-02-04 23:17:01 -080068 blob_stats.emplace_back(BlobDetector::BlobStats{
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080069 centroid, size, stats_fbs->aspect_ratio(), stats_fbs->area(),
Henry Speisere45e7a22022-02-04 23:17:01 -080070 static_cast<size_t>(stats_fbs->num_points())});
71 }
72 return blob_stats;
73}
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080074
75bool DisplayLoop() {
Jim Ostrowski210765a2022-02-27 12:52:14 -080076 int64_t target_timestamp = 0;
77 if (target_estimate_fetcher.Fetch()) {
78 const TargetEstimate *target_est = target_estimate_fetcher.get();
79 CHECK(target_est != nullptr)
80 << "Got null when trying to fetch target estimate";
81
82 target_timestamp = target_est->image_monotonic_timestamp_ns();
83 if (target_est->blob_result()->filtered_blobs()->size() > 0) {
84 VLOG(2) << "Got blobs for timestamp " << target_est << "\n";
85 }
86 // Store the TargetEstimate data so we can match timestamp with image
Milind Upadhyayf61e1482022-02-11 20:42:55 -080087 target_est_map[target_timestamp] = BlobDetector::BlobResult{
88 cv::Mat(),
89 FbsToCvBlobs(*target_est->blob_result()->filtered_blobs()),
90 FbsToCvBlobs(*target_est->blob_result()->unfiltered_blobs()),
91 FbsToBlobStats(*target_est->blob_result()->blob_stats()),
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080092 FbsToBlobStats(*target_est->blob_result()->filtered_stats()),
Milind Upadhyayf61e1482022-02-11 20:42:55 -080093 cv::Point{target_est->blob_result()->centroid()->x(),
94 target_est->blob_result()->centroid()->y()}};
Jim Ostrowski210765a2022-02-27 12:52:14 -080095 // Only keep last 10 matches
96 while (target_est_map.size() > 10u) {
97 target_est_map.erase(target_est_map.begin());
98 }
99 }
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800100 int64_t image_timestamp = 0;
Jim Ostrowski5caf81c2022-01-30 21:02:19 -0800101 if (!image_fetcher.Fetch()) {
Jim Ostrowski210765a2022-02-27 12:52:14 -0800102 VLOG(2) << "Couldn't fetch image";
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800103 return true;
104 }
Jim Ostrowski210765a2022-02-27 12:52:14 -0800105 const CameraImage *image = image_fetcher.get();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800106 CHECK(image != nullptr) << "Couldn't read image";
107 image_timestamp = image->monotonic_timestamp_ns();
108 VLOG(2) << "Got image at timestamp: " << image_timestamp;
109
110 // Create color image:
111 cv::Mat image_color_mat(cv::Size(image->cols(), image->rows()), CV_8UC2,
112 (void *)image->data()->data());
Milind Upadhyayec41e132022-02-05 17:14:05 -0800113 cv::Mat bgr_image(cv::Size(image->cols(), image->rows()), CV_8UC3);
Milind Upadhyay40522942022-02-19 15:30:31 -0800114 cv::cvtColor(image_color_mat, bgr_image, cv::COLOR_YUV2BGR_YUYV);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800115
116 if (!FLAGS_capture.empty()) {
Milind Upadhyayec41e132022-02-05 17:14:05 -0800117 cv::imwrite(FLAGS_capture, bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800118 return false;
119 }
120
Jim Ostrowski210765a2022-02-27 12:52:14 -0800121 auto target_est_it = target_est_map.find(image_timestamp);
122 if (target_est_it != target_est_map.end()) {
123 LOG(INFO) << image->monotonic_timestamp_ns() << ": # unfiltered blobs: "
124 << target_est_it->second.unfiltered_blobs.size()
125 << "; # filtered blobs: "
126 << target_est_it->second.filtered_blobs.size();
Henry Speisere45e7a22022-02-04 23:17:01 -0800127
Jim Ostrowski210765a2022-02-27 12:52:14 -0800128 cv::Mat ret_image =
129 cv::Mat::zeros(cv::Size(image->cols(), image->rows()), CV_8UC3);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800130 BlobDetector::DrawBlobs(target_est_it->second, ret_image);
Jim Ostrowski46a78382022-02-06 14:05:58 -0800131 cv::imshow("blobs", ret_image);
132 }
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800133
Milind Upadhyayec41e132022-02-05 17:14:05 -0800134 cv::imshow("image", bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800135
136 int keystroke = cv::waitKey(1);
137 if ((keystroke & 0xFF) == static_cast<int>('c')) {
138 // Convert again, to get clean image
Milind Upadhyayec41e132022-02-05 17:14:05 -0800139 cv::cvtColor(image_color_mat, bgr_image, cv::COLOR_YUV2BGR_YUYV);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800140 std::stringstream name;
141 name << "capture-" << aos::realtime_clock::now() << ".png";
Milind Upadhyayec41e132022-02-05 17:14:05 -0800142 cv::imwrite(name.str(), bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800143 LOG(INFO) << "Saved image file: " << name.str();
144 } else if ((keystroke & 0xFF) == static_cast<int>('q')) {
145 return false;
146 }
147 return true;
148}
149
150void ViewerMain() {
151 aos::FlatbufferDetachedBuffer<aos::Configuration> config =
152 aos::configuration::ReadConfig(FLAGS_config);
153
154 aos::ShmEventLoop event_loop(&config.message());
155
156 image_fetcher =
157 event_loop.MakeFetcher<frc971::vision::CameraImage>(FLAGS_channel);
158
Jim Ostrowski46a78382022-02-06 14:05:58 -0800159 target_estimate_fetcher =
160 event_loop.MakeFetcher<y2022::vision::TargetEstimate>(FLAGS_channel);
161
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800162 // Run the display loop
163 event_loop.AddPhasedLoop(
164 [&event_loop](int) {
165 if (!DisplayLoop()) {
166 LOG(INFO) << "Calling event_loop Exit";
167 event_loop.Exit();
168 };
169 },
170 ::std::chrono::milliseconds(100));
171
172 event_loop.Run();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800173}
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800174
175// TODO(milind): delete this when viewer can accumulate local images and results
176void ViewerLocal() {
177 std::vector<cv::String> file_list;
178 cv::glob(FLAGS_png_dir + "/*.png", file_list, false);
179
milind-ucafdd5d2022-03-01 19:58:57 -0800180 const aos::FlatbufferSpan<calibration::CalibrationData> calibration_data(
181 CalibrationData());
182
183 const calibration::CameraCalibration *calibration = nullptr;
184 for (const calibration::CameraCalibration *candidate :
185 *calibration_data.message().camera_calibrations()) {
186 if ((candidate->node_name()->string_view() == FLAGS_calibration_node) &&
187 (candidate->team_number() == FLAGS_calibration_team_number)) {
188 calibration = candidate;
189 break;
190 }
191 }
192
193 CHECK(calibration) << "No calibration data found for node \""
194 << FLAGS_calibration_node << "\" with team number "
195 << FLAGS_calibration_team_number;
196
197 auto intrinsics_float = cv::Mat(3, 3, CV_32F,
198 const_cast<void *>(static_cast<const void *>(
199 calibration->intrinsics()->data())));
200 cv::Mat intrinsics;
201 intrinsics_float.convertTo(intrinsics, CV_64F);
202
203 const auto extrinsics_float =
204 cv::Mat(4, 4, CV_32F,
205 const_cast<void *>(static_cast<const void *>(
206 calibration->fixed_extrinsics()->data()->data())));
207 cv::Mat extrinsics;
208 extrinsics_float.convertTo(extrinsics, CV_64F);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800209
210 TargetEstimator estimator(intrinsics, extrinsics);
211
212 for (auto it = file_list.begin() + FLAGS_skip; it != file_list.end(); it++) {
213 LOG(INFO) << "Reading file " << *it;
214 cv::Mat image_mat = cv::imread(it->c_str());
215 BlobDetector::BlobResult blob_result;
216 blob_result.binarized_image =
217 cv::Mat::zeros(cv::Size(image_mat.cols, image_mat.rows), CV_8UC1);
218 BlobDetector::ExtractBlobs(image_mat, &blob_result);
219
220 cv::Mat ret_image =
221 cv::Mat::zeros(cv::Size(image_mat.cols, image_mat.rows), CV_8UC3);
222 BlobDetector::DrawBlobs(blob_result, ret_image);
223
224 LOG(INFO) << ": # blobs: " << blob_result.filtered_blobs.size()
225 << " (# removed: "
226 << blob_result.unfiltered_blobs.size() -
227 blob_result.filtered_blobs.size()
228 << ")";
229
230 if (blob_result.filtered_blobs.size() > 0) {
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800231 estimator.Solve(blob_result.filtered_stats,
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800232 FLAGS_display_estimation ? std::make_optional(ret_image)
233 : std::nullopt);
234 estimator.DrawEstimate(ret_image);
235 }
236
237 cv::imshow("image", image_mat);
238 cv::imshow("mask", blob_result.binarized_image);
239 cv::imshow("blobs", ret_image);
240
241 int keystroke = cv::waitKey(0);
242 if ((keystroke & 0xFF) == static_cast<int>('q')) {
243 return;
244 }
245 }
246}
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800247} // namespace
248} // namespace vision
249} // namespace y2022
250
251// Quick and lightweight viewer for images
252int main(int argc, char **argv) {
253 aos::InitGoogle(&argc, &argv);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800254 if (FLAGS_png_dir != "")
255 y2022::vision::ViewerLocal();
256 else
257 y2022::vision::ViewerMain();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800258}