blob: e20f4332ddee95025762f761f3a09e748c2b31d7 [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"
Henry Speisere45e7a22022-02-04 23:17:01 -080013#include "y2022/vision/target_estimate_generated.h"
Milind Upadhyayf61e1482022-02-11 20:42:55 -080014#include "y2022/vision/target_estimator.h"
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080015
16DEFINE_string(capture, "",
17 "If set, capture a single image and save it to this filename.");
18DEFINE_string(channel, "/camera", "Channel name for the image.");
Austin Schuhc5fa6d92022-02-25 14:36:28 -080019DEFINE_string(config, "aos_config.json", "Path to the config file to use.");
Jim Ostrowski5caf81c2022-01-30 21:02:19 -080020DEFINE_string(png_dir, "", "Path to a set of images to display.");
Milind Upadhyayf61e1482022-02-11 20:42:55 -080021DEFINE_uint64(skip, 0,
22 "Number of images to skip if doing local reading (png_dir set).");
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080023DEFINE_bool(show_features, true, "Show the blobs.");
Milind Upadhyayf61e1482022-02-11 20:42:55 -080024DEFINE_bool(display_estimation, false,
25 "If true, display the target estimation graphically");
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080026
27namespace y2022 {
28namespace vision {
29namespace {
30
Jim Ostrowski210765a2022-02-27 12:52:14 -080031using namespace frc971::vision;
32
33std::map<int64_t, BlobDetector::BlobResult> target_est_map;
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080034aos::Fetcher<frc971::vision::CameraImage> image_fetcher;
Henry Speisere45e7a22022-02-04 23:17:01 -080035aos::Fetcher<y2022::vision::TargetEstimate> target_estimate_fetcher;
36
Milind Upadhyayf61e1482022-02-11 20:42:55 -080037std::vector<cv::Point> FbsToCvPoints(
38 const flatbuffers::Vector<const Point *> &points_fbs) {
39 std::vector<cv::Point> points;
40 for (const Point *point : points_fbs) {
41 points.emplace_back(point->x(), point->y());
42 }
43 return points;
44}
45
Henry Speisere45e7a22022-02-04 23:17:01 -080046std::vector<std::vector<cv::Point>> FbsToCvBlobs(
47 const flatbuffers::Vector<flatbuffers::Offset<Blob>> &blobs_fbs) {
48 std::vector<std::vector<cv::Point>> blobs;
49 for (const auto blob : blobs_fbs) {
Milind Upadhyayf61e1482022-02-11 20:42:55 -080050 blobs.emplace_back(FbsToCvPoints(*blob->points()));
Henry Speisere45e7a22022-02-04 23:17:01 -080051 }
52 return blobs;
53}
54
55std::vector<BlobDetector::BlobStats> FbsToBlobStats(
56 const flatbuffers::Vector<flatbuffers::Offset<BlobStatsFbs>>
57 &blob_stats_fbs) {
58 std::vector<BlobDetector::BlobStats> blob_stats;
59 for (const auto stats_fbs : blob_stats_fbs) {
60 cv::Point centroid{stats_fbs->centroid()->x(), stats_fbs->centroid()->y()};
61 blob_stats.emplace_back(BlobDetector::BlobStats{
62 centroid, stats_fbs->aspect_ratio(), stats_fbs->area(),
63 static_cast<size_t>(stats_fbs->num_points())});
64 }
65 return blob_stats;
66}
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080067
68bool DisplayLoop() {
Jim Ostrowski210765a2022-02-27 12:52:14 -080069 int64_t target_timestamp = 0;
70 if (target_estimate_fetcher.Fetch()) {
71 const TargetEstimate *target_est = target_estimate_fetcher.get();
72 CHECK(target_est != nullptr)
73 << "Got null when trying to fetch target estimate";
74
75 target_timestamp = target_est->image_monotonic_timestamp_ns();
76 if (target_est->blob_result()->filtered_blobs()->size() > 0) {
77 VLOG(2) << "Got blobs for timestamp " << target_est << "\n";
78 }
79 // Store the TargetEstimate data so we can match timestamp with image
Milind Upadhyayf61e1482022-02-11 20:42:55 -080080 target_est_map[target_timestamp] = BlobDetector::BlobResult{
81 cv::Mat(),
82 FbsToCvBlobs(*target_est->blob_result()->filtered_blobs()),
83 FbsToCvBlobs(*target_est->blob_result()->unfiltered_blobs()),
84 FbsToBlobStats(*target_est->blob_result()->blob_stats()),
85 FbsToCvPoints(*target_est->blob_result()->filtered_centroids()),
86 cv::Point{target_est->blob_result()->centroid()->x(),
87 target_est->blob_result()->centroid()->y()}};
Jim Ostrowski210765a2022-02-27 12:52:14 -080088 // Only keep last 10 matches
89 while (target_est_map.size() > 10u) {
90 target_est_map.erase(target_est_map.begin());
91 }
92 }
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080093 int64_t image_timestamp = 0;
Jim Ostrowski5caf81c2022-01-30 21:02:19 -080094 if (!image_fetcher.Fetch()) {
Jim Ostrowski210765a2022-02-27 12:52:14 -080095 VLOG(2) << "Couldn't fetch image";
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080096 return true;
97 }
Jim Ostrowski210765a2022-02-27 12:52:14 -080098 const CameraImage *image = image_fetcher.get();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080099 CHECK(image != nullptr) << "Couldn't read image";
100 image_timestamp = image->monotonic_timestamp_ns();
101 VLOG(2) << "Got image at timestamp: " << image_timestamp;
102
103 // Create color image:
104 cv::Mat image_color_mat(cv::Size(image->cols(), image->rows()), CV_8UC2,
105 (void *)image->data()->data());
Milind Upadhyayec41e132022-02-05 17:14:05 -0800106 cv::Mat bgr_image(cv::Size(image->cols(), image->rows()), CV_8UC3);
Milind Upadhyay40522942022-02-19 15:30:31 -0800107 cv::cvtColor(image_color_mat, bgr_image, cv::COLOR_YUV2BGR_YUYV);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800108
109 if (!FLAGS_capture.empty()) {
Milind Upadhyayec41e132022-02-05 17:14:05 -0800110 cv::imwrite(FLAGS_capture, bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800111 return false;
112 }
113
Jim Ostrowski210765a2022-02-27 12:52:14 -0800114 auto target_est_it = target_est_map.find(image_timestamp);
115 if (target_est_it != target_est_map.end()) {
116 LOG(INFO) << image->monotonic_timestamp_ns() << ": # unfiltered blobs: "
117 << target_est_it->second.unfiltered_blobs.size()
118 << "; # filtered blobs: "
119 << target_est_it->second.filtered_blobs.size();
Henry Speisere45e7a22022-02-04 23:17:01 -0800120
Jim Ostrowski210765a2022-02-27 12:52:14 -0800121 cv::Mat ret_image =
122 cv::Mat::zeros(cv::Size(image->cols(), image->rows()), CV_8UC3);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800123 BlobDetector::DrawBlobs(target_est_it->second, ret_image);
Jim Ostrowski46a78382022-02-06 14:05:58 -0800124 cv::imshow("blobs", ret_image);
125 }
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800126
Milind Upadhyayec41e132022-02-05 17:14:05 -0800127 cv::imshow("image", bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800128
129 int keystroke = cv::waitKey(1);
130 if ((keystroke & 0xFF) == static_cast<int>('c')) {
131 // Convert again, to get clean image
Milind Upadhyayec41e132022-02-05 17:14:05 -0800132 cv::cvtColor(image_color_mat, bgr_image, cv::COLOR_YUV2BGR_YUYV);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800133 std::stringstream name;
134 name << "capture-" << aos::realtime_clock::now() << ".png";
Milind Upadhyayec41e132022-02-05 17:14:05 -0800135 cv::imwrite(name.str(), bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800136 LOG(INFO) << "Saved image file: " << name.str();
137 } else if ((keystroke & 0xFF) == static_cast<int>('q')) {
138 return false;
139 }
140 return true;
141}
142
143void ViewerMain() {
144 aos::FlatbufferDetachedBuffer<aos::Configuration> config =
145 aos::configuration::ReadConfig(FLAGS_config);
146
147 aos::ShmEventLoop event_loop(&config.message());
148
149 image_fetcher =
150 event_loop.MakeFetcher<frc971::vision::CameraImage>(FLAGS_channel);
151
Jim Ostrowski46a78382022-02-06 14:05:58 -0800152 target_estimate_fetcher =
153 event_loop.MakeFetcher<y2022::vision::TargetEstimate>(FLAGS_channel);
154
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800155 // Run the display loop
156 event_loop.AddPhasedLoop(
157 [&event_loop](int) {
158 if (!DisplayLoop()) {
159 LOG(INFO) << "Calling event_loop Exit";
160 event_loop.Exit();
161 };
162 },
163 ::std::chrono::milliseconds(100));
164
165 event_loop.Run();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800166}
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800167
168// TODO(milind): delete this when viewer can accumulate local images and results
169void ViewerLocal() {
170 std::vector<cv::String> file_list;
171 cv::glob(FLAGS_png_dir + "/*.png", file_list, false);
172
173 cv::Mat intrinsics = cv::Mat::zeros(cv::Size(3, 3), CV_64F);
174 intrinsics.at<double>(0, 0) = 391.63916;
175 intrinsics.at<double>(0, 1) = 0.0;
176 intrinsics.at<double>(0, 2) = 312.691162;
177 intrinsics.at<double>(1, 0) = 0.0;
178 intrinsics.at<double>(1, 1) = 391.535889;
179 intrinsics.at<double>(1, 2) = 267.138672;
180 intrinsics.at<double>(2, 0) = 0.0;
181 intrinsics.at<double>(2, 1) = 0.0;
182 intrinsics.at<double>(2, 2) = 1.0;
183 cv::Mat extrinsics = cv::Mat::zeros(cv::Size(4, 4), CV_64F);
184 extrinsics.at<double>(2, 3) = 0.9398;
185
186 TargetEstimator estimator(intrinsics, extrinsics);
187
188 for (auto it = file_list.begin() + FLAGS_skip; it != file_list.end(); it++) {
189 LOG(INFO) << "Reading file " << *it;
190 cv::Mat image_mat = cv::imread(it->c_str());
191 BlobDetector::BlobResult blob_result;
192 blob_result.binarized_image =
193 cv::Mat::zeros(cv::Size(image_mat.cols, image_mat.rows), CV_8UC1);
194 BlobDetector::ExtractBlobs(image_mat, &blob_result);
195
196 cv::Mat ret_image =
197 cv::Mat::zeros(cv::Size(image_mat.cols, image_mat.rows), CV_8UC3);
198 BlobDetector::DrawBlobs(blob_result, ret_image);
199
200 LOG(INFO) << ": # blobs: " << blob_result.filtered_blobs.size()
201 << " (# removed: "
202 << blob_result.unfiltered_blobs.size() -
203 blob_result.filtered_blobs.size()
204 << ")";
205
206 if (blob_result.filtered_blobs.size() > 0) {
207 estimator.Solve(blob_result.filtered_centroids,
208 FLAGS_display_estimation ? std::make_optional(ret_image)
209 : std::nullopt);
210 estimator.DrawEstimate(ret_image);
211 }
212
213 cv::imshow("image", image_mat);
214 cv::imshow("mask", blob_result.binarized_image);
215 cv::imshow("blobs", ret_image);
216
217 int keystroke = cv::waitKey(0);
218 if ((keystroke & 0xFF) == static_cast<int>('q')) {
219 return;
220 }
221 }
222}
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800223} // namespace
224} // namespace vision
225} // namespace y2022
226
227// Quick and lightweight viewer for images
228int main(int argc, char **argv) {
229 aos::InitGoogle(&argc, &argv);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800230 if (FLAGS_png_dir != "")
231 y2022::vision::ViewerLocal();
232 else
233 y2022::vision::ViewerMain();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800234}