blob: 990ad7a54c782dc45a1cb1748244e1148a8decb0 [file] [log] [blame]
Austin Schuhdb2ed9d2022-12-26 14:02:26 -08001#include <opencv2/highgui/highgui.hpp>
2#include <opencv2/imgproc.hpp>
3
4#include "aos/events/shm_event_loop.h"
5#include "aos/init.h"
6#include "aos/time/time.h"
7#include "frc971/vision/vision_generated.h"
8
9DEFINE_string(config, "aos_config.json", "Path to the config file to use.");
10DEFINE_string(channel, "/camera", "Channel name for the image.");
11
12DEFINE_string(capture, "",
13 "If set, capture a single image and save it to this filename.");
14
15namespace frc971 {
16namespace vision {
17namespace {
18
19aos::Fetcher<CameraImage> image_fetcher;
20bool DisplayLoop() {
21 const CameraImage *image;
22
23 // Read next image
24 if (!image_fetcher.Fetch()) {
25 VLOG(2) << "Couldn't fetch next image";
26 return true;
27 }
28
29 image = image_fetcher.get();
30 CHECK(image != nullptr) << "Couldn't read image";
31
32 // Create color image:
33 cv::Mat image_color_mat(cv::Size(image->cols(), image->rows()), CV_8UC2,
34 (void *)image->data()->data());
35 cv::Mat bgr_image(cv::Size(image->cols(), image->rows()), CV_8UC3);
36 cv::cvtColor(image_color_mat, bgr_image, cv::COLOR_YUV2BGR_YUYV);
37
38 if (!FLAGS_capture.empty()) {
39 cv::imwrite(FLAGS_capture, bgr_image);
40 return false;
41 }
42
43 cv::imshow("Display", bgr_image);
44 int keystroke = cv::waitKey(1);
45 if ((keystroke & 0xFF) == static_cast<int>('c')) {
46 // Convert again, to get clean image
47 cv::cvtColor(image_color_mat, bgr_image, cv::COLOR_YUV2BGR_YUYV);
48 std::stringstream name;
49 name << "capture-" << aos::realtime_clock::now() << ".png";
50 cv::imwrite(name.str(), bgr_image);
51 LOG(INFO) << "Saved image file: " << name.str();
52 } else if ((keystroke & 0xFF) == static_cast<int>('q')) {
53 return false;
54 }
55 return true;
56}
57
58void ViewerMain() {
59 aos::FlatbufferDetachedBuffer<aos::Configuration> config =
60 aos::configuration::ReadConfig(FLAGS_config);
61
62 aos::ShmEventLoop event_loop(&config.message());
63
64 image_fetcher = event_loop.MakeFetcher<CameraImage>(FLAGS_channel);
65
66 // Run the display loop
67 event_loop.AddPhasedLoop(
68 [&event_loop](int) {
69 if (!DisplayLoop()) {
70 LOG(INFO) << "Calling event_loop Exit";
71 event_loop.Exit();
72 };
73 },
74 ::std::chrono::milliseconds(100));
75
76 event_loop.Run();
77
78 image_fetcher = aos::Fetcher<CameraImage>();
79}
80
81} // namespace
82} // namespace vision
83} // namespace frc971
84
85int main(int argc, char **argv) {
86 aos::InitGoogle(&argc, &argv);
87 frc971::vision::ViewerMain();
88}