149f759ad50befebb136bf501490cb1cc0c9fb51
1 /******************************************************************************
2 * Copyright (c) 2018, Texas Instruments Incorporated - http://www.ti.com/
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of Texas Instruments Incorporated nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
26 * THE POSSIBILITY OF SUCH DAMAGE.
27 *****************************************************************************/
28 #include <signal.h>
29 #include <iostream>
30 #include <iomanip>
31 #include <fstream>
32 #include <cassert>
33 #include <string>
34 #include <functional>
35 #include <algorithm>
36 #include <time.h>
37 #include <unistd.h>
39 #include <queue>
40 #include <vector>
41 #include <chrono>
43 #include "executor.h"
44 #include "execution_object.h"
45 #include "execution_object_pipeline.h"
46 #include "configuration.h"
47 #include "imagenet_classes.h"
48 #include "imgutil.h"
49 #include "../common/video_utils.h"
51 #include "opencv2/core.hpp"
52 #include "opencv2/imgproc.hpp"
53 #include "opencv2/highgui.hpp"
54 #include "opencv2/videoio.hpp"
56 using namespace std;
57 using namespace tidl;
58 using namespace cv;
60 #define NUM_VIDEO_FRAMES 300
61 #define DEFAULT_CONFIG "j11_v2"
62 #define NUM_DEFAULT_INPUTS 1
63 const char *default_inputs[NUM_DEFAULT_INPUTS] =
64 {
65 "../test/testvecs/input/objects/cat-pet-animal-domestic-104827.jpeg"
66 };
68 Executor* CreateExecutor(DeviceType dt, uint32_t num, const Configuration& c);
69 bool RunConfiguration(cmdline_opts_t& opts);
70 bool ReadFrame(ExecutionObjectPipeline& eop,
71 uint32_t frame_idx, const Configuration& c,
72 const cmdline_opts_t& opts, VideoCapture &cap);
73 bool WriteFrameOutput(const ExecutionObjectPipeline &eop);
74 void DisplayHelp();
77 int main(int argc, char *argv[])
78 {
79 // Catch ctrl-c to ensure a clean exit
80 signal(SIGABRT, exit);
81 signal(SIGTERM, exit);
83 // If there are no devices capable of offloading TIDL on the SoC, exit
84 uint32_t num_eves = Executor::GetNumDevices(DeviceType::EVE);
85 uint32_t num_dsps = Executor::GetNumDevices(DeviceType::DSP);
86 if (num_eves == 0 && num_dsps == 0)
87 {
88 cout << "TI DL not supported on this SoC." << endl;
89 return EXIT_SUCCESS;
90 }
92 // Process arguments
93 cmdline_opts_t opts;
94 opts.config = DEFAULT_CONFIG;
95 if (num_eves != 0) { opts.num_eves = 1; opts.num_dsps = 0; }
96 else { opts.num_eves = 0; opts.num_dsps = 1; }
97 if (! ProcessArgs(argc, argv, opts))
98 {
99 DisplayHelp();
100 exit(EXIT_SUCCESS);
101 }
102 assert(opts.num_dsps != 0 || opts.num_eves != 0);
103 if (opts.num_frames == 0)
104 opts.num_frames = (opts.is_camera_input || opts.is_video_input) ?
105 NUM_VIDEO_FRAMES : 1;
106 if (opts.input_file.empty())
107 cout << "Input: " << default_inputs[0] << endl;
108 else
109 cout << "Input: " << opts.input_file << endl;
111 // Run network
112 bool status = RunConfiguration(opts);
113 if (!status)
114 {
115 cout << "imagenet FAILED" << endl;
116 return EXIT_FAILURE;
117 }
119 cout << "imagenet PASSED" << endl;
120 return EXIT_SUCCESS;
121 }
123 bool RunConfiguration(cmdline_opts_t& opts)
124 {
125 // Read the TI DL configuration file
126 Configuration c;
127 string config_file = "../test/testvecs/config/infer/tidl_config_"
128 + opts.config + ".txt";
129 bool status = c.ReadFromFile(config_file);
130 if (!status)
131 {
132 cerr << "Error in configuration file: " << config_file << endl;
133 return false;
134 }
135 c.enableApiTrace = opts.verbose;
137 // setup camera/video input/output
138 VideoCapture cap;
139 if (! SetVideoInputOutput(cap, opts, "ImageNet")) return false;
141 try
142 {
143 // Create Executors with the approriate core type, number of cores
144 // and configuration specified
145 Executor* e_eve = CreateExecutor(DeviceType::EVE, opts.num_eves, c);
146 Executor* e_dsp = CreateExecutor(DeviceType::DSP, opts.num_dsps, c);
148 // Get ExecutionObjects from Executors
149 vector<ExecutionObject*> eos;
150 for (uint32_t i = 0; i < opts.num_eves; i++) eos.push_back((*e_eve)[i]);
151 for (uint32_t i = 0; i < opts.num_dsps; i++) eos.push_back((*e_dsp)[i]);
152 uint32_t num_eos = eos.size();
154 // Use duplicate EOPs to do double buffering on frame input/output
155 // because each EOP has its own set of input/output buffers,
156 // so that host ReadFrame() can be overlapped with device processing
157 // Use one EO as an example, with different buffer_factor,
158 // we have different execution behavior:
159 // If buffer_factor is set to 1 -> single buffering
160 // we create one EOP: eop0 (eo0)
161 // pipeline execution of multiple frames over time is as follows:
162 // --------------------- time ------------------->
163 // eop0: [RF][eo0.....][WF]
164 // eop0: [RF][eo0.....][WF]
165 // eop0: [RF][eo0.....][WF]
166 // If buffer_factor is set to 2 -> double buffering
167 // we create two EOPs: eop0 (eo0), eop1(eo0)
168 // pipeline execution of multiple frames over time is as follows:
169 // --------------------- time ------------------->
170 // eop0: [RF][eo0.....][WF]
171 // eop1: [RF] [eo0.....][WF]
172 // eop0: [RF] [eo0.....][WF]
173 // eop1: [RF] [eo0.....][WF]
174 vector<ExecutionObjectPipeline *> eops;
175 uint32_t buffer_factor = 2; // set to 1 for single buffering
176 for (uint32_t j = 0; j < buffer_factor; j++)
177 for (uint32_t i = 0; i < num_eos; i++)
178 eops.push_back(new ExecutionObjectPipeline({eos[i]}));
179 uint32_t num_eops = eops.size();
181 // Allocate input and output buffers for each EOP
182 AllocateMemory(eops);
184 chrono::time_point<chrono::steady_clock> tloop0, tloop1;
185 tloop0 = chrono::steady_clock::now();
187 // Process frames with available eops in a pipelined manner
188 // additional num_eos iterations to flush the pipeline (epilogue)
189 for (uint32_t frame_idx = 0;
190 frame_idx < opts.num_frames + num_eops; frame_idx++)
191 {
192 ExecutionObjectPipeline* eop = eops[frame_idx % num_eops];
194 // Wait for previous frame on the same eop to finish processing
195 if (eop->ProcessFrameWait())
196 {
197 WriteFrameOutput(*eop);
198 }
200 // Read a frame and start processing it with current eop
201 if (ReadFrame(*eop, frame_idx, c, opts, cap))
202 eop->ProcessFrameStartAsync();
203 }
205 tloop1 = chrono::steady_clock::now();
206 chrono::duration<float> elapsed = tloop1 - tloop0;
207 cout << "Loop total time (including read/write/opencv/print/etc): "
208 << setw(6) << setprecision(4)
209 << (elapsed.count() * 1000) << "ms" << endl;
211 FreeMemory(eops);
212 for (auto eop : eops) delete eop;
213 delete e_eve;
214 delete e_dsp;
215 }
216 catch (tidl::Exception &e)
217 {
218 cerr << e.what() << endl;
219 status = false;
220 }
222 return status;
223 }
225 // Create an Executor with the specified type and number of EOs
226 Executor* CreateExecutor(DeviceType dt, uint32_t num, const Configuration& c)
227 {
228 if (num == 0) return nullptr;
230 DeviceIds ids;
231 for (uint32_t i = 0; i < num; i++)
232 ids.insert(static_cast<DeviceId>(i));
234 return new Executor(dt, ids, c);
235 }
237 bool ReadFrame(ExecutionObjectPipeline &eop,
238 uint32_t frame_idx, const Configuration& c,
239 const cmdline_opts_t& opts, VideoCapture &cap)
240 {
241 if (frame_idx >= opts.num_frames)
242 return false;
244 eop.SetFrameIndex(frame_idx);
246 char* frame_buffer = eop.GetInputBufferPtr();
247 assert (frame_buffer != nullptr);
249 Mat image;
250 if (! opts.is_camera_input && ! opts.is_video_input)
251 {
252 if (opts.input_file.empty())
253 image = cv::imread(default_inputs[frame_idx % NUM_DEFAULT_INPUTS],
254 CV_LOAD_IMAGE_COLOR);
255 else
256 image = cv::imread(opts.input_file, CV_LOAD_IMAGE_COLOR);
257 if (image.empty())
258 {
259 cerr << "Unable to read input image" << endl;
260 return false;
261 }
262 }
263 else
264 {
265 Mat v_image;
266 if (! cap.grab()) return false;
267 if (! cap.retrieve(v_image)) return false;
268 int orig_width = v_image.cols;
269 int orig_height = v_image.rows;
270 // Crop camera/video input to center 256x256 input
271 if (orig_width > 256 && orig_height > 256)
272 {
273 image = Mat(v_image, Rect((orig_width-256)/2, (orig_height-256)/2,
274 256, 256));
275 }
276 else
277 image = v_image;
278 cv::imshow("ImageNet", image);
279 waitKey(2);
280 }
282 // TI DL image preprocessing, into frame_buffer
283 return imgutil::PreprocessImage(image, frame_buffer, c);
284 }
286 // Display top 5 classified imagenet classes with probabilities
287 bool WriteFrameOutput(const ExecutionObjectPipeline &eop)
288 {
289 const int k = 5;
290 unsigned char *out = (unsigned char *) eop.GetOutputBufferPtr();
291 int out_size = eop.GetOutputBufferSizeInBytes();
293 // sort and get k largest values and corresponding indices
294 typedef pair<unsigned char, int> val_index;
295 auto constexpr cmp = [](val_index &left, val_index &right)
296 { return left.first > right.first; };
297 priority_queue<val_index, vector<val_index>, decltype(cmp)> queue(cmp);
298 // initialize priority queue with smallest value on top
299 for (int i = 0; i < k; i++)
300 queue.push(val_index(out[i], i));
302 // for rest output, if larger than current min, pop min, push new val
303 for (int i = k; i < out_size; i++)
304 {
305 if (out[i] > queue.top().first)
306 {
307 queue.pop();
308 queue.push(val_index(out[i], i));
309 }
310 }
312 // output top k values in reverse order: largest val first
313 vector<val_index> sorted;
314 while (! queue.empty())
315 {
316 sorted.push_back(queue.top());
317 queue.pop();
318 }
320 for (int i = k - 1; i >= 0; i--)
321 cout << k-i << ": " << imagenet_classes[sorted[i].second] << endl;
323 return true;
324 }
326 void DisplayHelp()
327 {
328 cout <<
329 "Usage: imagenet\n"
330 " Will run imagenet network to predict top 5 object"
331 " classes for the input.\n Use -c to run a"
332 " different imagenet network. Default is j11_v2.\n"
333 "Optional arguments:\n"
334 " -c <config> Valid configs: j11_bn, j11_prelu, j11_v2\n"
335 " -d <number> Number of dsp cores to use\n"
336 " -e <number> Number of eve cores to use\n"
337 " -i <image> Path to the image file as input\n"
338 " -i camera<number> Use camera as input\n"
339 " video input port: /dev/video<number>\n"
340 " -i <name>.{mp4,mov,avi} Use video file as input\n"
341 " -f <number> Number of frames to process\n"
342 " -v Verbose output during execution\n"
343 " -h Help\n";
344 }