blob: b64bc2b0224f3456dc8ea877625ed839be1e7e62 [file] [log] [blame]
Jim Ostrowskiff7b3de2022-01-22 22:20:26 -08001#include "y2022/vision/camera_reader.h"
2
Henry Speiser3069ca92022-02-05 16:25:00 -08003#include <chrono>
Milind Upadhyay25610d22022-02-07 15:35:26 -08004#include <cmath>
Henry Speiser3069ca92022-02-05 16:25:00 -08005#include <thread>
Jim Ostrowskiff7b3de2022-01-22 22:20:26 -08006
Jim Ostrowskiff7b3de2022-01-22 22:20:26 -08007#include "aos/events/event_loop.h"
Henry Speiser1f34eea2022-01-30 14:35:21 -08008#include "aos/events/shm_event_loop.h"
Jim Ostrowskiff7b3de2022-01-22 22:20:26 -08009#include "aos/flatbuffer_merge.h"
10#include "aos/network/team_number.h"
milind-u2f101fc2023-01-21 12:28:49 -080011#include "frc971/vision/calibration_generated.h"
Jim Ostrowskiff7b3de2022-01-22 22:20:26 -080012#include "frc971/vision/v4l2_reader.h"
13#include "frc971/vision/vision_generated.h"
Milind Upadhyay25610d22022-02-07 15:35:26 -080014#include "opencv2/imgproc.hpp"
milind-u92195982022-01-22 20:29:31 -080015#include "y2022/vision/blob_detector.h"
Jim Ostrowskiff7b3de2022-01-22 22:20:26 -080016
Henry Speiser1f34eea2022-01-30 14:35:21 -080017DEFINE_string(image_png, "", "A set of PNG images");
18
Jim Ostrowskiff7b3de2022-01-22 22:20:26 -080019namespace y2022 {
20namespace vision {
21
22using namespace frc971::vision;
23
Milind Upadhyaya31f0272022-04-03 13:55:22 -070024const calibration::CameraCalibration *CameraReader::FindCameraCalibration(
25 const calibration::CalibrationData *calibration_data,
26 std::string_view node_name, int team_number) {
Jim Ostrowski007e2ea2022-01-30 13:13:26 -080027 for (const calibration::CameraCalibration *candidate :
Milind Upadhyaya31f0272022-04-03 13:55:22 -070028 *calibration_data->camera_calibrations()) {
Jim Ostrowskiff7b3de2022-01-22 22:20:26 -080029 if (candidate->node_name()->string_view() != node_name) {
30 continue;
31 }
32 if (candidate->team_number() != team_number) {
33 continue;
34 }
35 return candidate;
36 }
37 LOG(FATAL) << ": Failed to find camera calibration for " << node_name
38 << " on " << team_number;
39}
40
Henry Speisere45e7a22022-02-04 23:17:01 -080041namespace {
Milind Upadhyayf61e1482022-02-11 20:42:55 -080042flatbuffers::Offset<flatbuffers::Vector<const Point *>> CvPointsToFbs(
43 const std::vector<cv::Point> &points,
44 aos::Sender<TargetEstimate>::Builder *builder) {
45 std::vector<Point> points_fbs;
46 for (auto p : points) {
47 points_fbs.push_back(Point{p.x, p.y});
48 }
49 return builder->fbb()->CreateVectorOfStructs(points_fbs);
50}
51
James Kuszmauld230d7a2022-03-06 15:00:43 -080052constexpr size_t kMaxBlobsForDebug = 100;
53
Henry Speisere45e7a22022-02-04 23:17:01 -080054// Converts a vector of cv::Point to PointT for the flatbuffer
55flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Blob>>>
56CvBlobsToFbs(const std::vector<std::vector<cv::Point>> &blobs,
Milind Upadhyayf61e1482022-02-11 20:42:55 -080057 aos::Sender<TargetEstimate>::Builder *builder) {
Henry Speisere45e7a22022-02-04 23:17:01 -080058 std::vector<flatbuffers::Offset<Blob>> blobs_fbs;
59 for (auto &blob : blobs) {
Milind Upadhyayf61e1482022-02-11 20:42:55 -080060 const auto points_offset = CvPointsToFbs(blob, builder);
61 auto blob_builder = builder->MakeBuilder<Blob>();
Henry Speisere45e7a22022-02-04 23:17:01 -080062 blob_builder.add_points(points_offset);
63 blobs_fbs.emplace_back(blob_builder.Finish());
James Kuszmauld230d7a2022-03-06 15:00:43 -080064 if (blobs_fbs.size() == kMaxBlobsForDebug) {
65 break;
66 }
Henry Speisere45e7a22022-02-04 23:17:01 -080067 }
Milind Upadhyayf61e1482022-02-11 20:42:55 -080068 return builder->fbb()->CreateVector(blobs_fbs.data(), blobs_fbs.size());
Henry Speisere45e7a22022-02-04 23:17:01 -080069}
70
71flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<BlobStatsFbs>>>
72BlobStatsToFbs(const std::vector<BlobDetector::BlobStats> blob_stats,
Milind Upadhyayf61e1482022-02-11 20:42:55 -080073 aos::Sender<TargetEstimate>::Builder *builder) {
Henry Speisere45e7a22022-02-04 23:17:01 -080074 std::vector<flatbuffers::Offset<BlobStatsFbs>> stats_fbs;
75 for (auto &stats : blob_stats) {
76 // Make BlobStatsFbs builder then fill each field using the BlobStats
77 // struct, then you finish it and add it to stats_fbs.
Milind Upadhyayf61e1482022-02-11 20:42:55 -080078 auto stats_builder = builder->MakeBuilder<BlobStatsFbs>();
Henry Speisere45e7a22022-02-04 23:17:01 -080079 Point centroid_fbs = Point{stats.centroid.x, stats.centroid.y};
80 stats_builder.add_centroid(&centroid_fbs);
81 stats_builder.add_aspect_ratio(stats.aspect_ratio);
82 stats_builder.add_area(stats.area);
83 stats_builder.add_num_points(stats.num_points);
84
85 auto current_stats = stats_builder.Finish();
86 stats_fbs.emplace_back(current_stats);
87 }
Milind Upadhyayf61e1482022-02-11 20:42:55 -080088 return builder->fbb()->CreateVector(stats_fbs.data(), stats_fbs.size());
Henry Speisere45e7a22022-02-04 23:17:01 -080089}
90} // namespace
91
Milind Upadhyay3c1a5c02022-03-27 16:27:19 -070092void CameraReader::ProcessImage(cv::Mat image_mat_distorted,
Jim Ostrowski210765a2022-02-27 12:52:14 -080093 int64_t image_monotonic_timestamp_ns) {
Milind Upadhyaya31f0272022-04-03 13:55:22 -070094 cv::Mat image_mat = UndistortImage(image_mat_distorted, undistort_maps_);
Milind Upadhyay3c1a5c02022-03-27 16:27:19 -070095
Milind Upadhyay25610d22022-02-07 15:35:26 -080096 BlobDetector::BlobResult blob_result;
Milind Upadhyay25610d22022-02-07 15:35:26 -080097 BlobDetector::ExtractBlobs(image_mat, &blob_result);
milind-u92195982022-01-22 20:29:31 -080098 auto builder = target_estimate_sender_.MakeBuilder();
Milind Upadhyay25610d22022-02-07 15:35:26 -080099 flatbuffers::Offset<BlobResultFbs> blob_result_offset;
Henry Speisere45e7a22022-02-04 23:17:01 -0800100 {
Milind Upadhyay25610d22022-02-07 15:35:26 -0800101 const auto filtered_blobs_offset =
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800102 CvBlobsToFbs(blob_result.filtered_blobs, &builder);
Henry Speisere45e7a22022-02-04 23:17:01 -0800103 const auto unfiltered_blobs_offset =
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800104 CvBlobsToFbs(blob_result.unfiltered_blobs, &builder);
Milind Upadhyay25610d22022-02-07 15:35:26 -0800105 const auto blob_stats_offset =
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800106 BlobStatsToFbs(blob_result.blob_stats, &builder);
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800107 const auto filtered_stats_offset =
108 BlobStatsToFbs(blob_result.filtered_stats, &builder);
Milind Upadhyay25610d22022-02-07 15:35:26 -0800109 const Point centroid_fbs =
110 Point{blob_result.centroid.x, blob_result.centroid.y};
Henry Speisere45e7a22022-02-04 23:17:01 -0800111
Milind Upadhyay25610d22022-02-07 15:35:26 -0800112 auto blob_result_builder = builder.MakeBuilder<BlobResultFbs>();
Henry Speisere45e7a22022-02-04 23:17:01 -0800113 blob_result_builder.add_filtered_blobs(filtered_blobs_offset);
114 blob_result_builder.add_unfiltered_blobs(unfiltered_blobs_offset);
115 blob_result_builder.add_blob_stats(blob_stats_offset);
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800116 blob_result_builder.add_filtered_stats(filtered_stats_offset);
Henry Speisere45e7a22022-02-04 23:17:01 -0800117 blob_result_builder.add_centroid(&centroid_fbs);
118 blob_result_offset = blob_result_builder.Finish();
119 }
120
Milind Upadhyay8f38ad82022-03-03 10:06:18 -0800121 target_estimator_.Solve(blob_result.filtered_stats, std::nullopt);
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800122
Milind Upadhyaye2f40d72022-02-24 13:55:53 -0800123 const auto camera_calibration_offset =
124 aos::RecursiveCopyFlatBuffer(camera_calibration_, builder.fbb());
125
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800126 const auto rotation =
127 Rotation{target_estimator_.roll(), target_estimator_.pitch(),
128 target_estimator_.yaw()};
129
Henry Speisere45e7a22022-02-04 23:17:01 -0800130 auto target_estimate_builder = builder.MakeBuilder<TargetEstimate>();
Milind Upadhyayf61e1482022-02-11 20:42:55 -0800131
132 target_estimate_builder.add_distance(target_estimator_.distance());
133 target_estimate_builder.add_angle_to_target(
134 target_estimator_.angle_to_target());
135 target_estimate_builder.add_angle_to_camera(
136 target_estimator_.angle_to_camera());
137 target_estimate_builder.add_rotation_camera_hub(&rotation);
Milind Upadhyay14279de2022-02-26 16:07:53 -0800138 target_estimate_builder.add_confidence(target_estimator_.confidence());
Henry Speisere45e7a22022-02-04 23:17:01 -0800139 target_estimate_builder.add_blob_result(blob_result_offset);
Milind Upadhyaye2f40d72022-02-24 13:55:53 -0800140 target_estimate_builder.add_camera_calibration(camera_calibration_offset);
Jim Ostrowski210765a2022-02-27 12:52:14 -0800141 target_estimate_builder.add_image_monotonic_timestamp_ns(
142 image_monotonic_timestamp_ns);
Henry Speisere45e7a22022-02-04 23:17:01 -0800143 builder.CheckOk(builder.Send(target_estimate_builder.Finish()));
Jim Ostrowskiff7b3de2022-01-22 22:20:26 -0800144}
145
146void CameraReader::ReadImage() {
Henry Speiser1f34eea2022-01-30 14:35:21 -0800147 // Path is for reading from the Disk.
148 if (FLAGS_image_png != "") {
149 std::vector<cv::String> file_list;
150 cv::glob(FLAGS_image_png + "/*.png", file_list, false);
Henry Speiser1f34eea2022-01-30 14:35:21 -0800151 for (auto file : file_list) {
Henry Speiser3069ca92022-02-05 16:25:00 -0800152 // Sleep for 0.05 seconds in order to not reach the max number of messages
153 // that can be sent in a second.
154 std::this_thread::sleep_for(std::chrono::milliseconds(50));
Henry Speiser1f34eea2022-01-30 14:35:21 -0800155 LOG(INFO) << "Reading file " << file;
Milind Upadhyayec41e132022-02-05 17:14:05 -0800156 cv::Mat bgr_image = cv::imread(file.c_str());
Jim Ostrowskia045aee2022-02-27 15:08:22 -0800157 cv::Mat image_color_mat;
158 cv::cvtColor(bgr_image, image_color_mat, cv::COLOR_BGR2YUV);
159
160 // Convert YUV (3 channels) to YUYV (stacked format)
161 std::vector<uint8_t> yuyv;
162 for (int i = 0; i < image_color_mat.rows; i++) {
163 for (int j = 0; j < image_color_mat.cols; j++) {
164 // Always push a Y value
165 yuyv.emplace_back(image_color_mat.at<cv::Vec3b>(i, j)[0]);
166 if ((j % 2) == 0) {
167 // If column # is even, push a U value.
168 yuyv.emplace_back(image_color_mat.at<cv::Vec3b>(i, j)[1]);
169 } else {
170 // If column # is odd, push a V value.
171 yuyv.emplace_back(image_color_mat.at<cv::Vec3b>(i, j)[2]);
172 }
173 }
174 }
175
176 CHECK_EQ(static_cast<int>(yuyv.size()),
177 image_color_mat.rows * image_color_mat.cols * 2);
178
179 auto builder = image_sender_.MakeBuilder();
180 auto image_offset = builder.fbb()->CreateVector(yuyv);
181 auto image_builder = builder.MakeBuilder<CameraImage>();
182
Jim Ostrowski210765a2022-02-27 12:52:14 -0800183 int64_t timestamp =
184 aos::monotonic_clock::now().time_since_epoch().count();
Jim Ostrowskia045aee2022-02-27 15:08:22 -0800185
186 image_builder.add_rows(image_color_mat.rows);
187 image_builder.add_cols(image_color_mat.cols);
188 image_builder.add_data(image_offset);
189 image_builder.add_monotonic_timestamp_ns(timestamp);
190
Jim Ostrowski210765a2022-02-27 12:52:14 -0800191 ProcessImage(bgr_image, timestamp);
Jim Ostrowskia045aee2022-02-27 15:08:22 -0800192 builder.CheckOk(builder.Send(image_builder.Finish()));
Henry Speiser1f34eea2022-01-30 14:35:21 -0800193 }
194 event_loop_->Exit();
195 return;
196 }
197 // If we are not reading from the disk, we read the live camera stream.
Jim Ostrowskiff7b3de2022-01-22 22:20:26 -0800198 if (!reader_->ReadLatestImage()) {
199 read_image_timer_->Setup(event_loop_->monotonic_now() +
200 std::chrono::milliseconds(10));
201 return;
202 }
203
Henry Speiser1f34eea2022-01-30 14:35:21 -0800204 const CameraImage &image = reader_->LatestImage();
Henry Speiser1f34eea2022-01-30 14:35:21 -0800205
Jim Ostrowski210765a2022-02-27 12:52:14 -0800206 cv::Mat image_color_mat(cv::Size(image.cols(), image.rows()), CV_8UC2,
207 (void *)image.data()->data());
208 cv::Mat image_mat(cv::Size(image.cols(), image.rows()), CV_8UC3);
209 cv::cvtColor(image_color_mat, image_mat, cv::COLOR_YUV2BGR_YUYV);
Henry Speiser1f34eea2022-01-30 14:35:21 -0800210
Jim Ostrowski210765a2022-02-27 12:52:14 -0800211 ProcessImage(image_mat, image.monotonic_timestamp_ns());
Jim Ostrowskiff7b3de2022-01-22 22:20:26 -0800212
213 reader_->SendLatestImage();
214 read_image_timer_->Setup(event_loop_->monotonic_now());
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -0700215
216 // Disable the LEDs based on localizer output
217 if (localizer_output_fetcher_.Fetch()) {
218 const auto node_name = event_loop_->node()->name()->string_view();
219 const size_t pi_number =
Milind Upadhyay0fd96542022-03-13 21:24:45 -0700220 std::atol(node_name.substr(node_name.size() - 1).data()) - 1;
Milind Upadhyayd67e9cf2022-03-13 13:56:57 -0700221
222 CHECK(localizer_output_fetcher_->has_led_outputs() &&
223 localizer_output_fetcher_->led_outputs()->size() > pi_number);
224
225 const LedOutput led_output =
226 localizer_output_fetcher_->led_outputs()->Get(pi_number);
227
228 if (led_output != prev_led_output_) {
229 gpio_disable_control_.GPIOWrite(led_output == LedOutput::OFF ? kGPIOHigh
230 : kGPIOLow);
231
232 prev_led_output_ = led_output;
233 }
234 }
Jim Ostrowskiff7b3de2022-01-22 22:20:26 -0800235}
236
237} // namespace vision
238} // namespace y2022