1
+ import org .intel .openvino .*;
2
+ import org .opencv .core .*;
3
+ import org .opencv .highgui .HighGui ;
4
+ import org .opencv .imgcodecs .*;
5
+ import org .opencv .imgproc .Imgproc ;
6
+ import org .opencv .videoio .*;
7
+
8
+ import java .util .ArrayList ;
9
+ import java .util .LinkedList ;
10
+ import java .util .Map ;
11
+ import java .util .Queue ;
12
+ import java .util .Vector ;
13
+ import java .util .concurrent .BlockingQueue ;
14
+ import java .util .concurrent .LinkedBlockingQueue ;
15
+ import java .util .concurrent .TimeUnit ;
16
+
17
+ /*
18
+ This is async face detection Java sample (for OpenVINO Java API 2.0).
19
+ Upon the start-up the sample application reads command line parameters and loads a network
20
+ and an image to the Inference Engine device. When inference is done, the application will show
21
+ the image with detected objects enclosed in rectangles in new window. It also outputs the
22
+ confidence value and the coordinates of the rectangle to the standard output stream.
23
+ To get the list of command line parameters run the application with `--help` parameter.
24
+ */
25
+ public class Main {
26
+ static final float CONFIDENCE_THRESHOLD = 0.7f ;
27
+ static int waitingTime = 1 ;
28
+
29
+ static BlockingQueue <Mat > processedFramesQueue = new LinkedBlockingQueue <Mat >();
30
+ static BlockingQueue <float []> detectionOutput = new LinkedBlockingQueue <float []>();
31
+
32
+ static String outputName ;
33
+ static Queue <Integer > startedRequestsIds = new LinkedList <Integer >();
34
+ static Vector <InferRequest > inferRequests = new Vector <InferRequest >();
35
+ static Vector <Boolean > asyncInferIsFree ;
36
+
37
+ static int framesCounter = 0 ;
38
+ static int resultCounter = 0 ;
39
+
40
+ public static Tensor imageToTensor (Mat image ) {
41
+ int [] dimsArr = {1 , image .rows (), image .cols (), 3 };
42
+ return new Tensor (ElementType .u8 , dimsArr , image .dataAddr ());
43
+ }
44
+
45
+ static void processInferRequests () {
46
+ while (!startedRequestsIds .isEmpty ()) {
47
+ int requestId = startedRequestsIds .peek ();
48
+ InferRequest inferRequest = inferRequests .get (requestId );
49
+
50
+ if (!inferRequest .wait_for (0 )) return ;
51
+
52
+ Tensor outputTensor = inferRequest .get_output_tensor ();
53
+ float [] res = outputTensor .data ();
54
+
55
+ detectionOutput .add (res );
56
+
57
+ resultCounter ++;
58
+ asyncInferIsFree .setElementAt (true , requestId );
59
+ startedRequestsIds .remove ();
60
+ }
61
+ }
62
+
63
+ public static void main (String [] args ) {
64
+ try {
65
+ System .loadLibrary (Core .NATIVE_LIBRARY_NAME );
66
+ } catch (UnsatisfiedLinkError e ) {
67
+ System .err .println ("Failed to load OpenCV library\n " + e );
68
+ System .exit (1 );
69
+ }
70
+
71
+ ArgumentParser parser = new ArgumentParser ("This is async face detection sample" );
72
+ parser .addArgument ("-i" , "path to video" );
73
+ parser .addArgument ("-m" , "path to model .xml" );
74
+ parser .addArgument ("-d" , "device" );
75
+ parser .addArgument ("-nireq" , "number of infer requests" );
76
+ parser .parseArgs (args );
77
+
78
+ String imgsPath = parser .get ("-i" , null );
79
+ String xmlPath = parser .get ("-m" , null );
80
+ String device = parser .get ("-d" , "CPU" );
81
+ int inferRequestsSize = parser .getInteger ("-nireq" , 2 );
82
+
83
+ if (imgsPath == null ) {
84
+ System .out .println ("Error: Missed argument: -i" );
85
+ return ;
86
+ }
87
+ if (xmlPath == null ) {
88
+ System .out .println ("Error: Missed argument: -m" );
89
+ return ;
90
+ }
91
+
92
+ int warmupNum = inferRequestsSize * 2 ;
93
+
94
+ BlockingQueue <Mat > framesQueue = new LinkedBlockingQueue <Mat >();
95
+
96
+ Runnable capture =
97
+ new Runnable () {
98
+ @ Override
99
+ public void run () {
100
+ Mat frame = new Mat ();
101
+
102
+ VideoCapture cam = new VideoCapture ();
103
+ try {
104
+ int idx = Integer .valueOf (imgsPath );
105
+ cam .open (idx );
106
+ } catch (NumberFormatException exception ) {
107
+ cam .open (imgsPath );
108
+ }
109
+
110
+ while (cam .read (frame ) && !Thread .interrupted ()) {
111
+ framesCounter ++;
112
+ framesQueue .add (frame .clone ());
113
+ }
114
+ if (framesCounter == 0 ) {
115
+ System .err .println ("ERROR: Can't get any video frame!" );
116
+ System .exit (1 );
117
+ }
118
+ }
119
+ };
120
+ Thread captureThread = new Thread (capture );
121
+
122
+ Runnable infer =
123
+ new Runnable () {
124
+ @ Override
125
+ public void run () {
126
+ try {
127
+ Core core = new Core ();
128
+ Model net = core .read_model (xmlPath );
129
+
130
+ PrePostProcessor p = new PrePostProcessor (net );
131
+ p .input ()
132
+ .tensor ()
133
+ .set_element_type (ElementType .u8 )
134
+ .set_layout (new Layout ("NHWC" ));
135
+ p .input ().preprocess ().resize (ResizeAlgorithm .RESIZE_LINEAR );
136
+ p .input ().model ().set_layout (new Layout ("NCHW" ));
137
+ p .build ();
138
+
139
+ CompiledModel compiledModel = core .compile_model (net , device );
140
+
141
+ asyncInferIsFree = new Vector <Boolean >(inferRequestsSize );
142
+
143
+ for (int i = 0 ; i < inferRequestsSize ; i ++) {
144
+ inferRequests .add (compiledModel .create_infer_request ());
145
+ asyncInferIsFree .add (true );
146
+ }
147
+
148
+ boolean isRunning = true ;
149
+
150
+ while (captureThread .isAlive () || !framesQueue .isEmpty ()) {
151
+ if (Thread .interrupted ()) break ;
152
+
153
+ processInferRequests ();
154
+ for (int i = 0 ; i < inferRequestsSize ; i ++) {
155
+ if (!asyncInferIsFree .get (i )) continue ;
156
+
157
+ Mat frame = framesQueue .poll (0 , TimeUnit .SECONDS );
158
+
159
+ if (frame == null ) break ;
160
+
161
+ InferRequest request = inferRequests .get (i );
162
+
163
+ asyncInferIsFree .setElementAt (false , i );
164
+
165
+ processedFramesQueue .add (frame );
166
+
167
+ Tensor imgTensor = imageToTensor (frame );
168
+ request .set_input_tensor (imgTensor );
169
+
170
+ startedRequestsIds .add (i );
171
+ request .start_async ();
172
+ }
173
+ }
174
+ processInferRequests ();
175
+ } catch (InterruptedException e ) {
176
+ e .printStackTrace ();
177
+
178
+ for (Thread t : Thread .getAllStackTraces ().keySet ())
179
+ if (t .getState () == Thread .State .RUNNABLE ) t .interrupt ();
180
+ }
181
+ }
182
+ };
183
+ Thread inferThread = new Thread (infer );
184
+
185
+ captureThread .start ();
186
+ inferThread .start ();
187
+
188
+ TickMeter tm = new TickMeter ();
189
+ Scalar color = new Scalar (0 , 255 , 0 );
190
+ try {
191
+ while (inferThread .isAlive () || !detectionOutput .isEmpty ()) {
192
+
193
+ float [] detection = detectionOutput .poll (waitingTime , TimeUnit .SECONDS );
194
+ if (detection == null ) continue ;
195
+
196
+ Mat img = processedFramesQueue .poll (waitingTime , TimeUnit .SECONDS );
197
+ int maxProposalCount = detection .length / 7 ;
198
+
199
+ for (int curProposal = 0 ; curProposal < maxProposalCount ; curProposal ++) {
200
+ int imageId = (int ) detection [curProposal * 7 ];
201
+ if (imageId < 0 ) break ;
202
+
203
+ float confidence = detection [curProposal * 7 + 2 ];
204
+
205
+ // Drawing only objects with >70% probability
206
+ if (confidence < CONFIDENCE_THRESHOLD ) continue ;
207
+
208
+ int xmin = (int ) (detection [curProposal * 7 + 3 ] * img .cols ());
209
+ int ymin = (int ) (detection [curProposal * 7 + 4 ] * img .rows ());
210
+ int xmax = (int ) (detection [curProposal * 7 + 5 ] * img .cols ());
211
+ int ymax = (int ) (detection [curProposal * 7 + 6 ] * img .rows ());
212
+
213
+ // Draw rectangle around detected object.
214
+ Point lt = new Point (xmin , ymin );
215
+ Point br = new Point (xmax , ymax );
216
+ Imgproc .rectangle (img , lt , br , color , 2 );
217
+ }
218
+
219
+ if (resultCounter == warmupNum ) {
220
+ tm .start ();
221
+ } else if (resultCounter > warmupNum ) {
222
+ tm .stop ();
223
+ double worksFps = ((double ) (resultCounter - warmupNum )) / tm .getTimeSec ();
224
+ double readFps = ((double ) (framesCounter - warmupNum )) / tm .getTimeSec ();
225
+ tm .start ();
226
+
227
+ String label = "Reading fps: " + String .format ("%.3f" , readFps );
228
+ String label1 = "Inference fps: " + String .format ("%.3f" , worksFps );
229
+
230
+ Imgproc .putText (img , label , new Point (10 , 50 ), 0 , 0.7 , color , 1 );
231
+ Imgproc .putText (img , label1 , new Point (10 , 80 ), 0 , 0.7 , color , 1 );
232
+ }
233
+ HighGui .imshow ("Detection" , img );
234
+
235
+ if (HighGui .waitKey (1 ) != -1 ) {
236
+ inferThread .interrupt ();
237
+ captureThread .interrupt ();
238
+ break ;
239
+ }
240
+ }
241
+
242
+ HighGui .waitKey (1 );
243
+ HighGui .destroyAllWindows ();
244
+
245
+ captureThread .join ();
246
+ inferThread .join ();
247
+ } catch (InterruptedException e ) {
248
+ e .printStackTrace ();
249
+ for (Thread t : Thread .getAllStackTraces ().keySet ())
250
+ if (t .getState () == Thread .State .RUNNABLE ) t .interrupt ();
251
+ }
252
+ }
253
+ }
0 commit comments