blob: 6be52a5f072a84f8a9cad59b46746113acbd9b4c [file] [log] [blame]
Alex Perry24319272019-04-07 12:31:29 -07001#include <condition_variable>
Parker Schuh2a1447c2019-02-17 00:25:29 -08002#include <fstream>
Alex Perry24319272019-04-07 12:31:29 -07003#include <mutex>
Alex Perryb375df72019-04-07 12:31:21 -07004#include <random>
Alex Perry24319272019-04-07 12:31:29 -07005#include <thread>
Parker Schuh2a1447c2019-02-17 00:25:29 -08006
Austin Schuh99f7c6a2024-06-25 22:07:44 -07007#include "aos/init.h"
Parker Schuh2a1447c2019-02-17 00:25:29 -08008#include "aos/vision/blob/codec.h"
9#include "aos/vision/blob/find_blob.h"
10#include "aos/vision/events/socket_types.h"
11#include "aos/vision/events/udp.h"
Parker Schuh5e8e3a52019-02-24 13:36:19 -080012#include "y2019/jevois/camera/image_stream.h"
13#include "y2019/jevois/camera/reader.h"
Parker Schuh2a1447c2019-02-17 00:25:29 -080014#include "y2019/jevois/serial.h"
Brian Silvermance4825f2019-02-17 18:28:39 -080015#include "y2019/jevois/structures.h"
16#include "y2019/jevois/uart.h"
Austin Schuh4e2629d2019-03-28 14:44:37 -070017#include "y2019/vision/image_writer.h"
Tyler Chatowd0a49742022-02-25 22:06:19 -080018#include "y2019/vision/target_finder.h"
Brian Silverman58899fd2019-03-24 11:03:11 -070019
20// This has to be last to preserve compatibility with other headers using AOS
21// logging.
Austin Schuh99f7c6a2024-06-25 22:07:44 -070022#include "absl/log/check.h"
23#include "absl/log/log.h"
Parker Schuh2a1447c2019-02-17 00:25:29 -080024
Tyler Chatowd0a49742022-02-25 22:06:19 -080025using ::aos::monotonic_clock;
Parker Schuh2a1447c2019-02-17 00:25:29 -080026using ::aos::events::DataSocket;
27using ::aos::events::RXUdpSocket;
28using ::aos::events::TCPServer;
29using ::aos::vision::DataRef;
30using ::aos::vision::Int32Codec;
Parker Schuh2a1447c2019-02-17 00:25:29 -080031using aos::vision::Segment;
Tyler Chatowd0a49742022-02-25 22:06:19 -080032using ::y2019::jevois::open_via_terminos;
Parker Schuh2a1447c2019-02-17 00:25:29 -080033
Parker Schuh5e8e3a52019-02-24 13:36:19 -080034class CameraStream : public ::y2019::camera::ImageStreamEvent {
Parker Schuh2a1447c2019-02-17 00:25:29 -080035 public:
36 CameraStream(::aos::vision::CameraParams params, const ::std::string &fname)
37 : ImageStreamEvent(fname, params) {}
38
39 void ProcessImage(DataRef data, monotonic_clock::time_point monotonic_now) {
Brian Silverman58899fd2019-03-24 11:03:11 -070040 LOG(INFO) << "got frame: " << data.size();
Parker Schuh2a1447c2019-02-17 00:25:29 -080041
Parker Schuh5e8e3a52019-02-24 13:36:19 -080042 if (on_frame_) on_frame_(data, monotonic_now);
Parker Schuh2a1447c2019-02-17 00:25:29 -080043 }
44
Tyler Chatowd0a49742022-02-25 22:06:19 -080045 void set_on_frame(
46 const std::function<void(DataRef, monotonic_clock::time_point)>
47 &on_frame) {
Parker Schuh5e8e3a52019-02-24 13:36:19 -080048 on_frame_ = on_frame;
49 }
50
51 private:
52 std::function<void(DataRef, monotonic_clock::time_point)> on_frame_;
Parker Schuh2a1447c2019-02-17 00:25:29 -080053};
54
55int open_terminos(const char *tty_name) { return open_via_terminos(tty_name); }
56
57std::string GetFileContents(const std::string &filename) {
58 std::ifstream in(filename, std::ios::in | std::ios::binary);
59 if (in) {
60 std::string contents;
61 in.seekg(0, std::ios::end);
62 contents.resize(in.tellg());
63 in.seekg(0, std::ios::beg);
64 in.read(&contents[0], contents.size());
65 in.close();
66 return (contents);
67 }
68 fprintf(stderr, "Could not read file: %s\n", filename.c_str());
69 exit(-1);
70}
71
Tyler Chatowd0a49742022-02-25 22:06:19 -080072using aos::vision::ImageFormat;
Parker Schuh5e8e3a52019-02-24 13:36:19 -080073using aos::vision::ImageRange;
74using aos::vision::RangeImage;
Alex Perry24319272019-04-07 12:31:29 -070075using y2019::vision::IntermediateResult;
76using y2019::vision::Target;
Tyler Chatowd0a49742022-02-25 22:06:19 -080077using y2019::vision::TargetFinder;
Alex Perry24319272019-04-07 12:31:29 -070078
79class TargetProcessPool {
80 public:
81 // The number of threads we'll use.
82 static constexpr int kThreads = 4;
83
84 TargetProcessPool(TargetFinder *finder);
85 ~TargetProcessPool();
86
87 std::vector<IntermediateResult> Process(std::vector<const Target *> &&inputs,
88 bool verbose);
89
90 private:
91 // The main function for a thread.
92 void RunThread();
93
94 std::array<std::thread, kThreads> threads_;
95 // Coordinates access to results_/inputs_ and coordinates with
96 // condition_variable_.
97 std::mutex mutex_;
98 // Signals changes to results_/inputs_ and quit_.
99 std::condition_variable condition_variable_;
100 bool quit_ = false;
101
102 bool verbose_ = false;
103 std::vector<const Target *> inputs_;
104 std::vector<IntermediateResult> results_;
105
106 TargetFinder *const finder_;
107};
108
109TargetProcessPool::TargetProcessPool(TargetFinder *finder) : finder_(finder) {
110 for (int i = 0; i < kThreads; ++i) {
111 threads_[i] = std::thread([this]() { RunThread(); });
112 }
113}
114
115TargetProcessPool::~TargetProcessPool() {
116 {
117 std::unique_lock<std::mutex> locker(mutex_);
118 quit_ = true;
119 condition_variable_.notify_all();
120 }
121 for (int i = 0; i < kThreads; ++i) {
122 threads_[i].join();
123 }
124}
125
126std::vector<IntermediateResult> TargetProcessPool::Process(
127 std::vector<const Target *> &&inputs, bool verbose) {
128 inputs_ = std::move(inputs);
129 results_.clear();
130 verbose_ = verbose;
131 const size_t number_targets = inputs_.size();
132 {
133 std::unique_lock<std::mutex> locker(mutex_);
134 condition_variable_.notify_all();
135 while (results_.size() < number_targets) {
136 condition_variable_.wait(locker);
137 }
138 }
139 return std::move(results_);
140}
141
142void TargetProcessPool::RunThread() {
143 while (true) {
144 const Target *my_input;
145 {
146 std::unique_lock<std::mutex> locker(mutex_);
147 while (inputs_.empty()) {
148 if (quit_) {
149 return;
150 }
151 condition_variable_.wait(locker);
152 }
153 my_input = inputs_.back();
154 inputs_.pop_back();
155 }
156 IntermediateResult my_output =
157 finder_->ProcessTargetToResult(*my_input, false);
158 {
159 std::unique_lock<std::mutex> locker(mutex_);
160 results_.emplace_back(std::move(my_output));
161 condition_variable_.notify_all();
162 }
163 }
164}
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800165
Parker Schuh2a1447c2019-02-17 00:25:29 -0800166int main(int argc, char **argv) {
Parker Schuh2a1447c2019-02-17 00:25:29 -0800167 using namespace y2019::vision;
Brian Silvermane9924fd2019-03-02 15:20:42 -0800168 using frc971::jevois::CameraCommand;
Austin Schuh99f7c6a2024-06-25 22:07:44 -0700169 aos::InitGoogle(&argc, &argv);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800170
171 int itsDev = open_terminos("/dev/ttyS0");
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800172 frc971::jevois::CobsPacketizer<frc971::jevois::uart_to_camera_size()> cobs;
173 // Uncomment these to printf directly to stdout to get debug info...
174 // dup2(itsDev, 1);
175 // dup2(itsDev, 2);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800176
Alex Perry24319272019-04-07 12:31:29 -0700177 TargetFinder finder;
178 TargetProcessPool process_pool(&finder);
Austin Schuh4e2629d2019-03-28 14:44:37 -0700179 ImageWriter writer;
180 uint32_t image_count = 0;
181 bool log_images = false;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800182
Parker Schuh2a1447c2019-02-17 00:25:29 -0800183 aos::vision::CameraParams params0;
Austin Schuh9f6d4ea2019-03-28 14:44:52 -0700184 params0.set_exposure(60);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800185 params0.set_brightness(40);
186 params0.set_width(640);
Alex Perry24319272019-04-07 12:31:29 -0700187 params0.set_fps(25);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800188 params0.set_height(480);
189
Brian Silverman20b57772019-03-23 22:02:49 -0700190 aos::vision::FastYuyvYPooledThresholder thresholder;
191
Alex Perryb375df72019-04-07 12:31:21 -0700192 // A source of psuedorandom numbers which gives different numbers each time we
193 // need to drop targets.
194 std::minstd_rand random_engine;
195
Parker Schuh2a1447c2019-02-17 00:25:29 -0800196 ::std::unique_ptr<CameraStream> camera0(
197 new CameraStream(params0, "/dev/video0"));
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800198 camera0->set_on_frame([&](DataRef data,
199 monotonic_clock::time_point monotonic_now) {
Parker Schuh2a1447c2019-02-17 00:25:29 -0800200 aos::vision::ImageFormat fmt{640, 480};
Brian Silverman20b57772019-03-23 22:02:49 -0700201 aos::vision::BlobList imgs =
202 aos::vision::FindBlobs(thresholder.Threshold(fmt, data.data(), 120));
Austin Schuh3b1586a2019-05-02 13:46:52 -0700203 const int num_pixels = finder.PixelCount(&imgs);
204 LOG(INFO) << "Number pixels: " << num_pixels;
Alex Perry24319272019-04-07 12:31:29 -0700205 finder.PreFilter(&imgs);
Brian Silverman58899fd2019-03-24 11:03:11 -0700206 LOG(INFO) << "Blobs: " << imgs.size();
Parker Schuh2a1447c2019-02-17 00:25:29 -0800207
Austin Schuh32ffac22019-03-09 22:42:02 -0800208 constexpr bool verbose = false;
Austin Schuh6e56faf2019-03-10 14:04:57 -0700209 ::std::vector<Polygon> raw_polys;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800210 for (const RangeImage &blob : imgs) {
Ben Fredricksonf7b68522019-03-02 21:19:42 -0800211 // Convert blobs to contours in the corrected space.
Alex Perry24319272019-04-07 12:31:29 -0700212 ContourNode *contour = finder.GetContour(blob);
Austin Schuh6e56faf2019-03-10 14:04:57 -0700213 ::std::vector<::Eigen::Vector2f> unwarped_contour =
Alex Perry24319272019-04-07 12:31:29 -0700214 finder.UnWarpContour(contour);
Austin Schuh6e56faf2019-03-10 14:04:57 -0700215 const Polygon polygon =
Alex Perry24319272019-04-07 12:31:29 -0700216 finder.FindPolygon(::std::move(unwarped_contour), verbose);
Austin Schuh6e56faf2019-03-10 14:04:57 -0700217 if (!polygon.segments.empty()) {
Parker Schuh2a1447c2019-02-17 00:25:29 -0800218 raw_polys.push_back(polygon);
219 }
220 }
Brian Silverman58899fd2019-03-24 11:03:11 -0700221 LOG(INFO) << "Polygons: " << raw_polys.size();
Parker Schuh2a1447c2019-02-17 00:25:29 -0800222
223 // Calculate each component side of a possible target.
Austin Schuh32ffac22019-03-09 22:42:02 -0800224 ::std::vector<TargetComponent> target_component_list =
Alex Perry24319272019-04-07 12:31:29 -0700225 finder.FillTargetComponentList(raw_polys, verbose);
Brian Silverman58899fd2019-03-24 11:03:11 -0700226 LOG(INFO) << "Components: " << target_component_list.size();
Parker Schuh2a1447c2019-02-17 00:25:29 -0800227
228 // Put the compenents together into targets.
Austin Schuh32ffac22019-03-09 22:42:02 -0800229 ::std::vector<Target> target_list =
Alex Perry24319272019-04-07 12:31:29 -0700230 finder.FindTargetsFromComponents(target_component_list, verbose);
Alex Perryb375df72019-04-07 12:31:21 -0700231 static constexpr size_t kMaximumPotentialTargets = 8;
232 LOG(INFO) << "Potential Targets (will filter to "
233 << kMaximumPotentialTargets << "): " << target_list.size();
234
235 // A list of all the indices into target_list which we're going to actually
236 // use.
237 std::vector<int> target_list_indices;
238 target_list_indices.resize(target_list.size());
239 for (size_t i = 0; i < target_list.size(); ++i) {
240 target_list_indices[i] = i;
241 }
242 // Drop random elements until we get sufficiently few of them. We drop
243 // different elements each time to ensure we will see different valid
244 // targets on successive frames, which provides more useful information to
245 // the localization.
246 while (target_list_indices.size() > kMaximumPotentialTargets) {
247 std::uniform_int_distribution<size_t> distribution(
248 0, target_list_indices.size() - 1);
249 const size_t index = distribution(random_engine);
250 target_list_indices.erase(target_list_indices.begin() + index);
251 }
Parker Schuh2a1447c2019-02-17 00:25:29 -0800252
253 // Use the solver to generate an intermediate version of our results.
Alex Perry24319272019-04-07 12:31:29 -0700254 std::vector<const Target *> inputs;
Alex Perryb375df72019-04-07 12:31:21 -0700255 for (size_t index : target_list_indices) {
Alex Perry24319272019-04-07 12:31:29 -0700256 inputs.push_back(&target_list[index]);
Parker Schuh2a1447c2019-02-17 00:25:29 -0800257 }
Alex Perry24319272019-04-07 12:31:29 -0700258 std::vector<IntermediateResult> results =
259 process_pool.Process(std::move(inputs), verbose);
Brian Silverman58899fd2019-03-24 11:03:11 -0700260 LOG(INFO) << "Raw Results: " << results.size();
Parker Schuh2a1447c2019-02-17 00:25:29 -0800261
Alex Perry24319272019-04-07 12:31:29 -0700262 results = finder.FilterResults(results, 30, verbose);
Brian Silverman58899fd2019-03-24 11:03:11 -0700263 LOG(INFO) << "Results: " << results.size();
Brian Silvermance4825f2019-02-17 18:28:39 -0800264
Alex Perry5b1e8e32019-04-07 13:25:31 -0700265 int desired_exposure;
Austin Schuh3b1586a2019-05-02 13:46:52 -0700266 if (finder.TestExposure(results, num_pixels, &desired_exposure)) {
Alex Perry5b1e8e32019-04-07 13:25:31 -0700267 camera0->SetExposure(desired_exposure);
268 }
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800269
Brian Silvermanc41fb862019-03-02 21:14:46 -0800270 frc971::jevois::CameraFrame frame{};
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800271
Tyler Chatowd0a49742022-02-25 22:06:19 -0800272 for (size_t i = 0; i < results.size() && i < frame.targets.capacity();
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800273 ++i) {
274 const auto &result = results[i].extrinsics;
275 frame.targets.push_back(frc971::jevois::Target{
276 static_cast<float>(result.z), static_cast<float>(result.y),
277 static_cast<float>(result.r2), static_cast<float>(result.r1)});
278 }
279
280 frame.age = std::chrono::duration_cast<frc971::jevois::camera_duration>(
281 aos::monotonic_clock::now() - monotonic_now);
282
Brian Silverman86891e52019-03-23 22:02:52 -0700283 // If we succeed in writing our delimiter, then write out the rest of
284 // the frame. If not, no point in continuing.
Brian Silvermance4825f2019-02-17 18:28:39 -0800285 if (write(itsDev, "\0", 1) == 1) {
Brian Silvermance4825f2019-02-17 18:28:39 -0800286 const auto serialized_frame = frc971::jevois::UartPackToTeensy(frame);
287 // We don't really care if this succeeds or not. If it fails for some
288 // reason, we'll just try again with the next frame, and the other end
289 // will find the new packet just fine.
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800290 ssize_t n =
291 write(itsDev, serialized_frame.data(), serialized_frame.size());
292
293 if (n != (ssize_t)serialized_frame.size()) {
Brian Silverman58899fd2019-03-24 11:03:11 -0700294 LOG(INFO) << "Some problem happened";
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800295 }
Brian Silvermance4825f2019-02-17 18:28:39 -0800296 }
Austin Schuh4e2629d2019-03-28 14:44:37 -0700297
298 if (log_images) {
299 if ((image_count % 5) == 0) {
300 writer.WriteImage(data);
301 }
302 ++image_count;
303 }
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800304 });
Parker Schuh2a1447c2019-02-17 00:25:29 -0800305
306 aos::events::EpollLoop loop;
307
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800308 while (true) {
309 std::this_thread::sleep_for(std::chrono::milliseconds(1));
Parker Schuh2a1447c2019-02-17 00:25:29 -0800310 camera0->ReadEvent();
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800311
312 {
313 constexpr size_t kBufferSize = frc971::jevois::uart_to_teensy_size();
314 char data[kBufferSize];
315 ssize_t n = read(itsDev, &data[0], kBufferSize);
316 if (n >= 1) {
Austin Schuhb72be802022-01-02 12:26:28 -0800317 cobs.ParseData(absl::Span<const char>(&data[0], n));
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800318 auto packet = cobs.received_packet();
319 if (!packet.empty()) {
320 auto calibration_question =
321 frc971::jevois::UartUnpackToCamera(packet);
322 if (calibration_question) {
323 const auto &calibration = *calibration_question;
Alex Perry24319272019-04-07 12:31:29 -0700324 IntrinsicParams *intrinsics = finder.mutable_intrinsics();
Alex Perry3bf1bee2019-02-23 20:01:15 -0800325 intrinsics->mount_angle = calibration.calibration(0, 0);
326 intrinsics->focal_length = calibration.calibration(0, 1);
327 intrinsics->barrel_mount = calibration.calibration(0, 2);
328
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800329 switch (calibration.camera_command) {
Brian Silvermane9924fd2019-03-02 15:20:42 -0800330 case CameraCommand::kNormal:
Brian Silvermanbac77542019-03-03 13:57:00 -0800331 case CameraCommand::kAs:
Austin Schuh4e2629d2019-03-28 14:44:37 -0700332 log_images = false;
333 break;
334 case CameraCommand::kLog:
335 log_images = true;
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800336 break;
Brian Silvermane9924fd2019-03-02 15:20:42 -0800337 case CameraCommand::kUsb:
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800338 return 0;
Brian Silvermane9924fd2019-03-02 15:20:42 -0800339 case CameraCommand::kCameraPassthrough:
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800340 return system("touch /tmp/do_not_export_sd_card");
341 }
342 } else {
Brian Silverman58899fd2019-03-24 11:03:11 -0700343 fprintf(stderr, "bad frame\n");
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800344 }
345 cobs.clear_received_packet();
346 }
347 }
348 }
Parker Schuh2a1447c2019-02-17 00:25:29 -0800349 }
350
351 // TODO: Fix event loop on jevois:
352 // loop.Add(camera0.get());
353 // loop.Run();
354}