blob: feff59247cbe12e7e0c4d4a7b1506649f61934c5 [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()};
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080061 cv::Size size{stats_fbs->size()->width(), stats_fbs->size()->height()};
Henry Speisere45e7a22022-02-04 23:17:01 -080062 blob_stats.emplace_back(BlobDetector::BlobStats{
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080063 centroid, size, stats_fbs->aspect_ratio(), stats_fbs->area(),
Henry Speisere45e7a22022-02-04 23:17:01 -080064 static_cast<size_t>(stats_fbs->num_points())});
65 }
66 return blob_stats;
67}
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080068
69bool DisplayLoop() {
Jim Ostrowski210765a2022-02-27 12:52:14 -080070 int64_t target_timestamp = 0;
71 if (target_estimate_fetcher.Fetch()) {
72 const TargetEstimate *target_est = target_estimate_fetcher.get();
73 CHECK(target_est != nullptr)
74 << "Got null when trying to fetch target estimate";
75
76 target_timestamp = target_est->image_monotonic_timestamp_ns();
77 if (target_est->blob_result()->filtered_blobs()->size() > 0) {
78 VLOG(2) << "Got blobs for timestamp " << target_est << "\n";
79 }
80 // Store the TargetEstimate data so we can match timestamp with image
Milind Upadhyayf61e1482022-02-11 20:42:55 -080081 target_est_map[target_timestamp] = BlobDetector::BlobResult{
82 cv::Mat(),
83 FbsToCvBlobs(*target_est->blob_result()->filtered_blobs()),
84 FbsToCvBlobs(*target_est->blob_result()->unfiltered_blobs()),
85 FbsToBlobStats(*target_est->blob_result()->blob_stats()),
Milind Upadhyay8f38ad82022-03-03 10:06:18 -080086 FbsToBlobStats(*target_est->blob_result()->filtered_stats()),
Milind Upadhyayf61e1482022-02-11 20:42:55 -080087 cv::Point{target_est->blob_result()->centroid()->x(),
88 target_est->blob_result()->centroid()->y()}};
Jim Ostrowski210765a2022-02-27 12:52:14 -080089 // Only keep last 10 matches
90 while (target_est_map.size() > 10u) {
91 target_est_map.erase(target_est_map.begin());
92 }
93 }
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080094 int64_t image_timestamp = 0;
Jim Ostrowski5caf81c2022-01-30 21:02:19 -080095 if (!image_fetcher.Fetch()) {
Jim Ostrowski210765a2022-02-27 12:52:14 -080096 VLOG(2) << "Couldn't fetch image";
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -080097 return true;
98 }
Jim Ostrowski210765a2022-02-27 12:52:14 -080099 const CameraImage *image = image_fetcher.get();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800100 CHECK(image != nullptr) << "Couldn't read image";
101 image_timestamp = image->monotonic_timestamp_ns();
102 VLOG(2) << "Got image at timestamp: " << image_timestamp;
103
104 // Create color image:
105 cv::Mat image_color_mat(cv::Size(image->cols(), image->rows()), CV_8UC2,
106 (void *)image->data()->data());
Milind Upadhyayec41e132022-02-05 17:14:05 -0800107 cv::Mat bgr_image(cv::Size(image->cols(), image->rows()), CV_8UC3);
Milind Upadhyay40522942022-02-19 15:30:31 -0800108 cv::cvtColor(image_color_mat, bgr_image, cv::COLOR_YUV2BGR_YUYV);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800109
110 if (!FLAGS_capture.empty()) {
Milind Upadhyayec41e132022-02-05 17:14:05 -0800111 cv::imwrite(FLAGS_capture, bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800112 return false;
113 }
114
Jim Ostrowski210765a2022-02-27 12:52:14 -0800115 auto target_est_it = target_est_map.find(image_timestamp);
116 if (target_est_it != target_est_map.end()) {
117 LOG(INFO) << image->monotonic_timestamp_ns() << ": # unfiltered blobs: "
118 << target_est_it->second.unfiltered_blobs.size()
119 << "; # filtered blobs: "
120 << target_est_it->second.filtered_blobs.size();
Henry Speisere45e7a22022-02-04 23:17:01 -0800121
Jim Ostrowski210765a2022-02-27 12:52:14 -0800122 cv::Mat ret_image =
123 cv::Mat::zeros(cv::Size(image->cols(), image->rows()), CV_8UC3);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800124 BlobDetector::DrawBlobs(target_est_it->second, ret_image);
Jim Ostrowski46a78382022-02-06 14:05:58 -0800125 cv::imshow("blobs", ret_image);
126 }
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800127
Milind Upadhyayec41e132022-02-05 17:14:05 -0800128 cv::imshow("image", bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800129
130 int keystroke = cv::waitKey(1);
131 if ((keystroke & 0xFF) == static_cast<int>('c')) {
132 // Convert again, to get clean image
Milind Upadhyayec41e132022-02-05 17:14:05 -0800133 cv::cvtColor(image_color_mat, bgr_image, cv::COLOR_YUV2BGR_YUYV);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800134 std::stringstream name;
135 name << "capture-" << aos::realtime_clock::now() << ".png";
Milind Upadhyayec41e132022-02-05 17:14:05 -0800136 cv::imwrite(name.str(), bgr_image);
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800137 LOG(INFO) << "Saved image file: " << name.str();
138 } else if ((keystroke & 0xFF) == static_cast<int>('q')) {
139 return false;
140 }
141 return true;
142}
143
144void ViewerMain() {
145 aos::FlatbufferDetachedBuffer<aos::Configuration> config =
146 aos::configuration::ReadConfig(FLAGS_config);
147
148 aos::ShmEventLoop event_loop(&config.message());
149
150 image_fetcher =
151 event_loop.MakeFetcher<frc971::vision::CameraImage>(FLAGS_channel);
152
Jim Ostrowski46a78382022-02-06 14:05:58 -0800153 target_estimate_fetcher =
154 event_loop.MakeFetcher<y2022::vision::TargetEstimate>(FLAGS_channel);
155
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800156 // Run the display loop
157 event_loop.AddPhasedLoop(
158 [&event_loop](int) {
159 if (!DisplayLoop()) {
160 LOG(INFO) << "Calling event_loop Exit";
161 event_loop.Exit();
162 };
163 },
164 ::std::chrono::milliseconds(100));
165
166 event_loop.Run();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800167}
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800168
169// TODO(milind): delete this when viewer can accumulate local images and results
170void ViewerLocal() {
171 std::vector<cv::String> file_list;
172 cv::glob(FLAGS_png_dir + "/*.png", file_list, false);
173
174 cv::Mat intrinsics = cv::Mat::zeros(cv::Size(3, 3), CV_64F);
175 intrinsics.at<double>(0, 0) = 391.63916;
176 intrinsics.at<double>(0, 1) = 0.0;
177 intrinsics.at<double>(0, 2) = 312.691162;
178 intrinsics.at<double>(1, 0) = 0.0;
179 intrinsics.at<double>(1, 1) = 391.535889;
180 intrinsics.at<double>(1, 2) = 267.138672;
181 intrinsics.at<double>(2, 0) = 0.0;
182 intrinsics.at<double>(2, 1) = 0.0;
183 intrinsics.at<double>(2, 2) = 1.0;
184 cv::Mat extrinsics = cv::Mat::zeros(cv::Size(4, 4), CV_64F);
185 extrinsics.at<double>(2, 3) = 0.9398;
186
187 TargetEstimator estimator(intrinsics, extrinsics);
188
189 for (auto it = file_list.begin() + FLAGS_skip; it != file_list.end(); it++) {
190 LOG(INFO) << "Reading file " << *it;
191 cv::Mat image_mat = cv::imread(it->c_str());
192 BlobDetector::BlobResult blob_result;
193 blob_result.binarized_image =
194 cv::Mat::zeros(cv::Size(image_mat.cols, image_mat.rows), CV_8UC1);
195 BlobDetector::ExtractBlobs(image_mat, &blob_result);
196
197 cv::Mat ret_image =
198 cv::Mat::zeros(cv::Size(image_mat.cols, image_mat.rows), CV_8UC3);
199 BlobDetector::DrawBlobs(blob_result, ret_image);
200
201 LOG(INFO) << ": # blobs: " << blob_result.filtered_blobs.size()
202 << " (# removed: "
203 << blob_result.unfiltered_blobs.size() -
204 blob_result.filtered_blobs.size()
205 << ")";
206
207 if (blob_result.filtered_blobs.size() > 0) {
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800208 estimator.Solve(blob_result.filtered_stats,
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800209 FLAGS_display_estimation ? std::make_optional(ret_image)
210 : std::nullopt);
211 estimator.DrawEstimate(ret_image);
212 }
213
214 cv::imshow("image", image_mat);
215 cv::imshow("mask", blob_result.binarized_image);
216 cv::imshow("blobs", ret_image);
217
218 int keystroke = cv::waitKey(0);
219 if ((keystroke & 0xFF) == static_cast<int>('q')) {
220 return;
221 }
222 }
223}
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800224} // namespace
225} // namespace vision
226} // namespace y2022
227
228// Quick and lightweight viewer for images
229int main(int argc, char **argv) {
230 aos::InitGoogle(&argc, &argv);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800231 if (FLAGS_png_dir != "")
232 y2022::vision::ViewerLocal();
233 else
234 y2022::vision::ViewerMain();
Jim Ostrowskiff0f5e42022-01-22 01:35:31 -0800235}