camera_mobilenet_sync_example.cpp
Go to the documentation of this file.
1 #include <cstdio>
2 #include <deque>
3 #include <iostream>
4 
5 #include "utility.hpp"
6 
7 // Includes common necessary includes for development using depthai library
8 #include "depthai/depthai.hpp"
9 
10 constexpr float CAMERA_FPS = 60;
11 
12 int main(int argc, char** argv) {
13  using namespace std;
14  using namespace std::chrono;
15 
16  // Default blob path provided by Hunter private data download
17  // Applicable for easier example usage only
18  std::string nnPath(BLOB_PATH);
19  // If path to blob specified, use that
20  if(argc > 1) {
21  nnPath = std::string(argv[1]);
22  }
23 
24  // Create pipeline
25  dai::Pipeline pipeline;
26 
27  // Define sources and outputs
28  auto camRgb = pipeline.create<dai::node::ColorCamera>();
29  auto nn = pipeline.create<dai::node::MobileNetDetectionNetwork>();
30  auto camOut = pipeline.create<dai::node::XLinkOut>();
31  auto resultOut = pipeline.create<dai::node::XLinkOut>();
32 
33  camOut->setStreamName("preview");
34  resultOut->setStreamName("resultOut");
35 
36  // ColorCamera options
37  camRgb->setPreviewSize(300, 300);
39  camRgb->setInterleaved(false);
40  camRgb->setColorOrder(dai::ColorCameraProperties::ColorOrder::BGR);
41  camRgb->setFps(CAMERA_FPS);
42 
43  // NN input options
44  nn->input.setBlocking(false);
45  nn->input.setQueueSize(1);
46  nn->setBlobPath(nnPath);
47  // Change to 1 to observe slower consumer syncing
48  nn->setNumInferenceThreads(2);
49 
50  // Link nodes CAM -> XLINK
51  camRgb->preview.link(nn->input);
52  camRgb->preview.link(camOut->input);
53  nn->out.link(resultOut->input);
54 
55  // Common variables
56  std::mutex queueMtx;
57  std::deque<cv::Mat> queue;
58  std::atomic<bool> running{true};
59 
60  // Worker thread
61  std::thread workerThread([&running, &queueMtx, &queue, &pipeline]() {
62  // Connect to device and start pipeline
63  dai::Device device(pipeline);
64 
65  // Create input & output queues
66  auto previewQueue = device.getOutputQueue("preview");
67  auto resultQueue = device.getOutputQueue("resultOut");
68 
69  // Get initial inference result
70  auto prevResult = resultQueue->get<dai::ImgDetections>();
71 
72  // statistics
73  nanoseconds sumLatency{0};
74  milliseconds avgLatency{0};
75  int numFrames = 0;
76  int nnFps = 0, lastNnFps = 0;
77  int camFps = 0, lastCamFps = 0;
78  auto lastTime = steady_clock::now();
79 
80  while(running) {
81  // Get first passthrough and result at the same time
82  auto result = resultQueue->get<dai::ImgDetections>();
83 
84  nnFps++;
85 
86  // Match up prevResults and previews
87  while(running) {
88  // pop the preview
89  auto preview = previewQueue->get<dai::ImgFrame>();
90  camFps++;
91 
92  // process
93  cv::Mat frame = toMat(preview->getData(), preview->getWidth(), preview->getHeight(), 3, 1);
94 
95  // Draw all detections
96  for(const auto& d : prevResult->detections) {
97  int x1 = d.xmin * frame.cols;
98  int y1 = d.ymin * frame.rows;
99  int x2 = d.xmax * frame.cols;
100  int y2 = d.ymax * frame.rows;
101  cv::rectangle(frame, cv::Rect(cv::Point(x1, y1), cv::Point(x2, y2)), cv::Scalar(255, 255, 255));
102  }
103 
104  // Draw avg latency and previous fps
105  cv::putText(frame, std::string("NN: ") + std::to_string(lastNnFps), cv::Point(5, 20), cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(255, 0, 0));
106  cv::putText(frame, std::string("Cam: ") + std::to_string(lastCamFps), cv::Point(5, 50), cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(255, 0, 0));
107  cv::putText(frame,
108  std::string("Latency: ") + std::to_string(avgLatency.count()),
109  cv::Point(frame.cols - 120, 20),
110  cv::FONT_HERSHEY_PLAIN,
111  1,
112  cv::Scalar(255, 0, 0));
113 
114  // Send to be displayed
115  {
116  std::unique_lock<std::mutex> l(queueMtx);
117  queue.push_back(std::move(frame));
118  }
119 
120  // If seq number >= next detection seq number - 1, break
121  if(preview->getSequenceNum() >= result->getSequenceNum() - 1) {
122  numFrames++;
123  sumLatency = sumLatency + (steady_clock::now() - preview->getTimestamp());
124 
125  if(steady_clock::now() - lastTime >= seconds(1)) {
126  // calculate fps
127  lastNnFps = nnFps;
128  nnFps = 0;
129 
130  // calculate cam fps
131  lastCamFps = camFps;
132  camFps = 0;
133 
134  // calculate latency
135  avgLatency = duration_cast<milliseconds>(sumLatency / numFrames);
136  sumLatency = nanoseconds(0);
137  numFrames = 0;
138 
139  // reset last time
140  lastTime = steady_clock::now();
141  }
142 
143  // break out of the loop
144  break;
145  }
146  }
147 
148  // Move current NN results to prev
149  prevResult = result;
150  }
151  });
152 
153  // Display (main) thread
154  using namespace std::chrono;
155  cv::Mat frame;
156  while(running) {
157  auto t1 = steady_clock::now();
158  {
159  std::unique_lock<std::mutex> l(queueMtx);
160  if(!queue.empty()) {
161  frame = queue.front();
162  queue.pop_front();
163  }
164  }
165  if(!frame.empty()) {
166  cv::imshow("frame", frame);
167  }
168  auto toSleep = (seconds(1) / CAMERA_FPS) - (steady_clock::now() - t1);
169  if(toSleep > milliseconds(0)) {
170  if(cv::waitKey(duration_cast<milliseconds>(toSleep).count()) == 'q') {
171  running = false;
172  }
173  }
174  }
175 
176  workerThread.join();
177 }
dai::node::XLinkOut
XLinkOut node. Sends messages over XLink.
Definition: XLinkOut.hpp:14
dai::Pipeline
Represents the pipeline, set of nodes and connections between them.
Definition: Pipeline.hpp:100
dai::node::ColorCamera
ColorCamera node. For use with color sensors.
Definition: ColorCamera.hpp:16
main
int main(int argc, char **argv)
Definition: camera_mobilenet_sync_example.cpp:12
toMat
cv::Mat toMat(const std::vector< uint8_t > &data, int w, int h, int numPlanes, int bpp)
Definition: utility.cpp:45
dai::Device::getOutputQueue
std::shared_ptr< DataOutputQueue > getOutputQueue(const std::string &name)
Definition: Device.cpp:86
dai::node::XLinkOut::input
Input input
Definition: XLinkOut.hpp:27
depthai.hpp
dai::Pipeline::create
std::shared_ptr< N > create()
Definition: Pipeline.hpp:145
dai::ColorCameraProperties::ColorOrder::BGR
@ BGR
CAMERA_FPS
constexpr float CAMERA_FPS
Definition: camera_mobilenet_sync_example.cpp:10
dai::ImgFrame
Definition: ImgFrame.hpp:25
nanorpc::core::exception::to_string
std::string to_string(std::exception const &e)
Definition: exception.h:46
dai::ColorCameraProperties::SensorResolution::THE_1080_P
@ THE_1080_P
1920 × 1080
dai::Device
Definition: Device.hpp:21
dai::node::ColorCamera::preview
Output preview
Definition: ColorCamera.hpp:69
std
Definition: Node.hpp:366
dai::Node::Output::link
void link(const Input &in)
Definition: Node.cpp:84
dai::node::MobileNetDetectionNetwork
MobileNetDetectionNetwork node. Parses MobileNet results.
Definition: DetectionNetwork.hpp:56
dai::node::XLinkOut::setStreamName
void setStreamName(const std::string &name)
Definition: XLinkOut.cpp:13
dai::ImgDetections
Definition: ImgDetections.hpp:14
utility.hpp


depthai
Author(s): Martin Peterlin
autogenerated on Sat Mar 22 2025 02:58:18