blob: 72e79398343c32e58451e052bdf806cfeeb42b07 [file] [log] [blame]
Brian Silverman58899fd2019-03-24 11:03:11 -07001#include "y2019/vision/target_finder.h"
2
Parker Schuh2a1447c2019-02-17 00:25:29 -08003#include <fstream>
Alex Perryb375df72019-04-07 12:31:21 -07004#include <random>
Parker Schuh2a1447c2019-02-17 00:25:29 -08005
Parker Schuh2a1447c2019-02-17 00:25:29 -08006#include "aos/vision/blob/codec.h"
7#include "aos/vision/blob/find_blob.h"
8#include "aos/vision/events/socket_types.h"
9#include "aos/vision/events/udp.h"
Parker Schuh5e8e3a52019-02-24 13:36:19 -080010#include "y2019/jevois/camera/image_stream.h"
11#include "y2019/jevois/camera/reader.h"
Parker Schuh2a1447c2019-02-17 00:25:29 -080012#include "y2019/jevois/serial.h"
Brian Silvermance4825f2019-02-17 18:28:39 -080013#include "y2019/jevois/structures.h"
14#include "y2019/jevois/uart.h"
Austin Schuh4e2629d2019-03-28 14:44:37 -070015#include "y2019/vision/image_writer.h"
Brian Silverman58899fd2019-03-24 11:03:11 -070016
17// This has to be last to preserve compatibility with other headers using AOS
18// logging.
19#include "glog/logging.h"
Parker Schuh2a1447c2019-02-17 00:25:29 -080020
21using ::aos::events::DataSocket;
22using ::aos::events::RXUdpSocket;
23using ::aos::events::TCPServer;
24using ::aos::vision::DataRef;
25using ::aos::vision::Int32Codec;
26using ::aos::monotonic_clock;
27using ::y2019::jevois::open_via_terminos;
28using aos::vision::Segment;
29
Parker Schuh5e8e3a52019-02-24 13:36:19 -080030class CameraStream : public ::y2019::camera::ImageStreamEvent {
Parker Schuh2a1447c2019-02-17 00:25:29 -080031 public:
32 CameraStream(::aos::vision::CameraParams params, const ::std::string &fname)
33 : ImageStreamEvent(fname, params) {}
34
35 void ProcessImage(DataRef data, monotonic_clock::time_point monotonic_now) {
Brian Silverman58899fd2019-03-24 11:03:11 -070036 LOG(INFO) << "got frame: " << data.size();
Parker Schuh2a1447c2019-02-17 00:25:29 -080037
Parker Schuh5e8e3a52019-02-24 13:36:19 -080038 if (on_frame_) on_frame_(data, monotonic_now);
Parker Schuh2a1447c2019-02-17 00:25:29 -080039 }
40
Parker Schuh5e8e3a52019-02-24 13:36:19 -080041 void set_on_frame(const std::function<
42 void(DataRef, monotonic_clock::time_point)> &on_frame) {
43 on_frame_ = on_frame;
44 }
45
46 private:
47 std::function<void(DataRef, monotonic_clock::time_point)> on_frame_;
Parker Schuh2a1447c2019-02-17 00:25:29 -080048};
49
50int open_terminos(const char *tty_name) { return open_via_terminos(tty_name); }
51
52std::string GetFileContents(const std::string &filename) {
53 std::ifstream in(filename, std::ios::in | std::ios::binary);
54 if (in) {
55 std::string contents;
56 in.seekg(0, std::ios::end);
57 contents.resize(in.tellg());
58 in.seekg(0, std::ios::beg);
59 in.read(&contents[0], contents.size());
60 in.close();
61 return (contents);
62 }
63 fprintf(stderr, "Could not read file: %s\n", filename.c_str());
64 exit(-1);
65}
66
Parker Schuh5e8e3a52019-02-24 13:36:19 -080067using aos::vision::ImageRange;
68using aos::vision::RangeImage;
69using aos::vision::ImageFormat;
70
Parker Schuh2a1447c2019-02-17 00:25:29 -080071int main(int argc, char **argv) {
72 (void)argc;
73 (void)argv;
74 using namespace y2019::vision;
Brian Silvermane9924fd2019-03-02 15:20:42 -080075 using frc971::jevois::CameraCommand;
Parker Schuh2a1447c2019-02-17 00:25:29 -080076 // gflags::ParseCommandLineFlags(&argc, &argv, false);
Brian Silverman58899fd2019-03-24 11:03:11 -070077 FLAGS_logtostderr = true;
78 google::InitGoogleLogging(argv[0]);
Parker Schuh2a1447c2019-02-17 00:25:29 -080079
80 int itsDev = open_terminos("/dev/ttyS0");
Parker Schuh5e8e3a52019-02-24 13:36:19 -080081 frc971::jevois::CobsPacketizer<frc971::jevois::uart_to_camera_size()> cobs;
82 // Uncomment these to printf directly to stdout to get debug info...
83 // dup2(itsDev, 1);
84 // dup2(itsDev, 2);
Parker Schuh2a1447c2019-02-17 00:25:29 -080085
86 TargetFinder finder_;
Austin Schuh4e2629d2019-03-28 14:44:37 -070087 ImageWriter writer;
88 uint32_t image_count = 0;
89 bool log_images = false;
Parker Schuh2a1447c2019-02-17 00:25:29 -080090
Parker Schuh2a1447c2019-02-17 00:25:29 -080091 aos::vision::CameraParams params0;
Ben Fredricksona8c3d552019-03-03 14:14:53 -080092 params0.set_exposure(50);
Parker Schuh2a1447c2019-02-17 00:25:29 -080093 params0.set_brightness(40);
94 params0.set_width(640);
Ben Fredricksona8c3d552019-03-03 14:14:53 -080095 params0.set_fps(15);
Parker Schuh2a1447c2019-02-17 00:25:29 -080096 params0.set_height(480);
97
Brian Silverman20b57772019-03-23 22:02:49 -070098 aos::vision::FastYuyvYPooledThresholder thresholder;
99
Alex Perryb375df72019-04-07 12:31:21 -0700100 // A source of psuedorandom numbers which gives different numbers each time we
101 // need to drop targets.
102 std::minstd_rand random_engine;
103
Parker Schuh2a1447c2019-02-17 00:25:29 -0800104 ::std::unique_ptr<CameraStream> camera0(
105 new CameraStream(params0, "/dev/video0"));
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800106 camera0->set_on_frame([&](DataRef data,
107 monotonic_clock::time_point monotonic_now) {
Parker Schuh2a1447c2019-02-17 00:25:29 -0800108 aos::vision::ImageFormat fmt{640, 480};
Brian Silverman20b57772019-03-23 22:02:49 -0700109 aos::vision::BlobList imgs =
110 aos::vision::FindBlobs(thresholder.Threshold(fmt, data.data(), 120));
Parker Schuh2a1447c2019-02-17 00:25:29 -0800111 finder_.PreFilter(&imgs);
Brian Silverman58899fd2019-03-24 11:03:11 -0700112 LOG(INFO) << "Blobs: " << imgs.size();
Parker Schuh2a1447c2019-02-17 00:25:29 -0800113
Austin Schuh32ffac22019-03-09 22:42:02 -0800114 constexpr bool verbose = false;
Austin Schuh6e56faf2019-03-10 14:04:57 -0700115 ::std::vector<Polygon> raw_polys;
Parker Schuh2a1447c2019-02-17 00:25:29 -0800116 for (const RangeImage &blob : imgs) {
Ben Fredricksonf7b68522019-03-02 21:19:42 -0800117 // Convert blobs to contours in the corrected space.
Brian Silverman86891e52019-03-23 22:02:52 -0700118 ContourNode *contour = finder_.GetContour(blob);
Austin Schuh6e56faf2019-03-10 14:04:57 -0700119 ::std::vector<::Eigen::Vector2f> unwarped_contour =
Austin Schuhe5015972019-03-09 17:47:34 -0800120 finder_.UnWarpContour(contour);
Austin Schuh6e56faf2019-03-10 14:04:57 -0700121 const Polygon polygon =
122 finder_.FindPolygon(::std::move(unwarped_contour), verbose);
123 if (!polygon.segments.empty()) {
Parker Schuh2a1447c2019-02-17 00:25:29 -0800124 raw_polys.push_back(polygon);
125 }
126 }
Brian Silverman58899fd2019-03-24 11:03:11 -0700127 LOG(INFO) << "Polygons: " << raw_polys.size();
Parker Schuh2a1447c2019-02-17 00:25:29 -0800128
129 // Calculate each component side of a possible target.
Austin Schuh32ffac22019-03-09 22:42:02 -0800130 ::std::vector<TargetComponent> target_component_list =
131 finder_.FillTargetComponentList(raw_polys, verbose);
Brian Silverman58899fd2019-03-24 11:03:11 -0700132 LOG(INFO) << "Components: " << target_component_list.size();
Parker Schuh2a1447c2019-02-17 00:25:29 -0800133
134 // Put the compenents together into targets.
Austin Schuh32ffac22019-03-09 22:42:02 -0800135 ::std::vector<Target> target_list =
Parker Schuh2a1447c2019-02-17 00:25:29 -0800136 finder_.FindTargetsFromComponents(target_component_list, verbose);
Alex Perryb375df72019-04-07 12:31:21 -0700137 static constexpr size_t kMaximumPotentialTargets = 8;
138 LOG(INFO) << "Potential Targets (will filter to "
139 << kMaximumPotentialTargets << "): " << target_list.size();
140
141 // A list of all the indices into target_list which we're going to actually
142 // use.
143 std::vector<int> target_list_indices;
144 target_list_indices.resize(target_list.size());
145 for (size_t i = 0; i < target_list.size(); ++i) {
146 target_list_indices[i] = i;
147 }
148 // Drop random elements until we get sufficiently few of them. We drop
149 // different elements each time to ensure we will see different valid
150 // targets on successive frames, which provides more useful information to
151 // the localization.
152 while (target_list_indices.size() > kMaximumPotentialTargets) {
153 std::uniform_int_distribution<size_t> distribution(
154 0, target_list_indices.size() - 1);
155 const size_t index = distribution(random_engine);
156 target_list_indices.erase(target_list_indices.begin() + index);
157 }
Parker Schuh2a1447c2019-02-17 00:25:29 -0800158
159 // Use the solver to generate an intermediate version of our results.
Austin Schuh32ffac22019-03-09 22:42:02 -0800160 ::std::vector<IntermediateResult> results;
Alex Perryb375df72019-04-07 12:31:21 -0700161 for (size_t index : target_list_indices) {
162 const Target &target = target_list[index];
Parker Schuh2a1447c2019-02-17 00:25:29 -0800163 results.emplace_back(finder_.ProcessTargetToResult(target, verbose));
164 }
Brian Silverman58899fd2019-03-24 11:03:11 -0700165 LOG(INFO) << "Raw Results: " << results.size();
Parker Schuh2a1447c2019-02-17 00:25:29 -0800166
Alex Perrybac3d3f2019-03-10 14:26:51 -0700167 results = finder_.FilterResults(results, 30, verbose);
Brian Silverman58899fd2019-03-24 11:03:11 -0700168 LOG(INFO) << "Results: " << results.size();
Brian Silvermance4825f2019-02-17 18:28:39 -0800169
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800170 // TODO: Select top 3 (randomly?)
171
Brian Silvermanc41fb862019-03-02 21:14:46 -0800172 frc971::jevois::CameraFrame frame{};
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800173
174 for (size_t i = 0; i < results.size() && i < frame.targets.max_size();
175 ++i) {
176 const auto &result = results[i].extrinsics;
177 frame.targets.push_back(frc971::jevois::Target{
178 static_cast<float>(result.z), static_cast<float>(result.y),
179 static_cast<float>(result.r2), static_cast<float>(result.r1)});
180 }
181
182 frame.age = std::chrono::duration_cast<frc971::jevois::camera_duration>(
183 aos::monotonic_clock::now() - monotonic_now);
184
Brian Silverman86891e52019-03-23 22:02:52 -0700185 // If we succeed in writing our delimiter, then write out the rest of
186 // the frame. If not, no point in continuing.
Brian Silvermance4825f2019-02-17 18:28:39 -0800187 if (write(itsDev, "\0", 1) == 1) {
Brian Silvermance4825f2019-02-17 18:28:39 -0800188 const auto serialized_frame = frc971::jevois::UartPackToTeensy(frame);
189 // We don't really care if this succeeds or not. If it fails for some
190 // reason, we'll just try again with the next frame, and the other end
191 // will find the new packet just fine.
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800192 ssize_t n =
193 write(itsDev, serialized_frame.data(), serialized_frame.size());
194
195 if (n != (ssize_t)serialized_frame.size()) {
Brian Silverman58899fd2019-03-24 11:03:11 -0700196 LOG(INFO) << "Some problem happened";
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800197 }
Brian Silvermance4825f2019-02-17 18:28:39 -0800198 }
Austin Schuh4e2629d2019-03-28 14:44:37 -0700199
200 if (log_images) {
201 if ((image_count % 5) == 0) {
202 writer.WriteImage(data);
203 }
204 ++image_count;
205 }
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800206 });
Parker Schuh2a1447c2019-02-17 00:25:29 -0800207
208 aos::events::EpollLoop loop;
209
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800210 while (true) {
211 std::this_thread::sleep_for(std::chrono::milliseconds(1));
Parker Schuh2a1447c2019-02-17 00:25:29 -0800212 camera0->ReadEvent();
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800213
214 {
215 constexpr size_t kBufferSize = frc971::jevois::uart_to_teensy_size();
216 char data[kBufferSize];
217 ssize_t n = read(itsDev, &data[0], kBufferSize);
218 if (n >= 1) {
219 cobs.ParseData(gsl::span<const char>(&data[0], n));
220 auto packet = cobs.received_packet();
221 if (!packet.empty()) {
222 auto calibration_question =
223 frc971::jevois::UartUnpackToCamera(packet);
224 if (calibration_question) {
225 const auto &calibration = *calibration_question;
Alex Perry3bf1bee2019-02-23 20:01:15 -0800226 IntrinsicParams *intrinsics = finder_.mutable_intrinsics();
227 intrinsics->mount_angle = calibration.calibration(0, 0);
228 intrinsics->focal_length = calibration.calibration(0, 1);
229 intrinsics->barrel_mount = calibration.calibration(0, 2);
230
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800231 switch (calibration.camera_command) {
Brian Silvermane9924fd2019-03-02 15:20:42 -0800232 case CameraCommand::kNormal:
Brian Silvermanbac77542019-03-03 13:57:00 -0800233 case CameraCommand::kAs:
Austin Schuh4e2629d2019-03-28 14:44:37 -0700234 log_images = false;
235 break;
236 case CameraCommand::kLog:
237 log_images = true;
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800238 break;
Brian Silvermane9924fd2019-03-02 15:20:42 -0800239 case CameraCommand::kUsb:
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800240 return 0;
Brian Silvermane9924fd2019-03-02 15:20:42 -0800241 case CameraCommand::kCameraPassthrough:
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800242 return system("touch /tmp/do_not_export_sd_card");
243 }
244 } else {
Brian Silverman58899fd2019-03-24 11:03:11 -0700245 fprintf(stderr, "bad frame\n");
Parker Schuh5e8e3a52019-02-24 13:36:19 -0800246 }
247 cobs.clear_received_packet();
248 }
249 }
250 }
Parker Schuh2a1447c2019-02-17 00:25:29 -0800251 }
252
253 // TODO: Fix event loop on jevois:
254 // loop.Add(camera0.get());
255 // loop.Run();
256}