-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
VisionProcessorBase.kt
415 lines (381 loc) · 13.7 KB
/
VisionProcessorBase.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
/*
* Copyright 2020 Google LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.mlkit.vision.demo.kotlin
import android.app.ActivityManager
import android.content.Context
import android.graphics.Bitmap
import android.os.Build.VERSION_CODES
import android.os.SystemClock
import android.util.Log
import android.widget.Toast
import androidx.annotation.GuardedBy
import androidx.annotation.RequiresApi
import androidx.camera.core.ExperimentalGetImage
import androidx.camera.core.ImageProxy
import com.google.android.gms.tasks.OnFailureListener
import com.google.android.gms.tasks.OnSuccessListener
import com.google.android.gms.tasks.Task
import com.google.android.gms.tasks.TaskExecutors
import com.google.android.gms.tasks.Tasks
import com.google.android.odml.image.BitmapMlImageBuilder
import com.google.android.odml.image.ByteBufferMlImageBuilder
import com.google.android.odml.image.MediaMlImageBuilder
import com.google.android.odml.image.MlImage
import com.google.mlkit.common.MlKitException
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.demo.BitmapUtils
import com.google.mlkit.vision.demo.CameraImageGraphic
import com.google.mlkit.vision.demo.FrameMetadata
import com.google.mlkit.vision.demo.GraphicOverlay
import com.google.mlkit.vision.demo.InferenceInfoGraphic
import com.google.mlkit.vision.demo.ScopedExecutor
import com.google.mlkit.vision.demo.VisionImageProcessor
import com.google.mlkit.vision.demo.preference.PreferenceUtils
import java.lang.Math.max
import java.lang.Math.min
import java.nio.ByteBuffer
import java.util.Timer
import java.util.TimerTask
/**
* Abstract base class for ML Kit frame processors. Subclasses need to implement {@link
* #onSuccess(T, FrameMetadata, GraphicOverlay)} to define what they want to with the detection
* results and {@link #detectInImage(VisionImage)} to specify the detector object.
*
* @param <T> The type of the detected feature.
*/
abstract class VisionProcessorBase<T>(context: Context) : VisionImageProcessor {
companion object {
const val MANUAL_TESTING_LOG = "LogTagForTest"
private const val TAG = "VisionProcessorBase"
}
private var activityManager: ActivityManager =
context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
private val fpsTimer = Timer()
private val executor = ScopedExecutor(TaskExecutors.MAIN_THREAD)
// Whether this processor is already shut down
private var isShutdown = false
// Used to calculate latency, running in the same thread, no sync needed.
private var numRuns = 0
private var totalFrameMs = 0L
private var maxFrameMs = 0L
private var minFrameMs = Long.MAX_VALUE
private var totalDetectorMs = 0L
private var maxDetectorMs = 0L
private var minDetectorMs = Long.MAX_VALUE
// Frame count that have been processed so far in an one second interval to calculate FPS.
private var frameProcessedInOneSecondInterval = 0
private var framesPerSecond = 0
// To keep the latest images and its metadata.
@GuardedBy("this") private var latestImage: ByteBuffer? = null
@GuardedBy("this") private var latestImageMetaData: FrameMetadata? = null
// To keep the images and metadata in process.
@GuardedBy("this") private var processingImage: ByteBuffer? = null
@GuardedBy("this") private var processingMetaData: FrameMetadata? = null
init {
fpsTimer.scheduleAtFixedRate(
object : TimerTask() {
override fun run() {
framesPerSecond = frameProcessedInOneSecondInterval
frameProcessedInOneSecondInterval = 0
}
},
0,
1000
)
}
// -----------------Code for processing single still image----------------------------------------
override fun processBitmap(bitmap: Bitmap?, graphicOverlay: GraphicOverlay) {
val frameStartMs = SystemClock.elapsedRealtime()
if (isMlImageEnabled(graphicOverlay.context)) {
val mlImage = BitmapMlImageBuilder(bitmap!!).build()
requestDetectInImage(
mlImage,
graphicOverlay,
/* originalCameraImage= */ null,
/* shouldShowFps= */ false,
frameStartMs
)
mlImage.close()
return
}
requestDetectInImage(
InputImage.fromBitmap(bitmap!!, 0),
graphicOverlay,
/* originalCameraImage= */ null,
/* shouldShowFps= */ false,
frameStartMs
)
}
// -----------------Code for processing live preview frame from Camera1 API-----------------------
@Synchronized
override fun processByteBuffer(
data: ByteBuffer?,
frameMetadata: FrameMetadata?,
graphicOverlay: GraphicOverlay
) {
latestImage = data
latestImageMetaData = frameMetadata
if (processingImage == null && processingMetaData == null) {
processLatestImage(graphicOverlay)
}
}
@Synchronized
private fun processLatestImage(graphicOverlay: GraphicOverlay) {
processingImage = latestImage
processingMetaData = latestImageMetaData
latestImage = null
latestImageMetaData = null
if (processingImage != null && processingMetaData != null && !isShutdown) {
processImage(processingImage!!, processingMetaData!!, graphicOverlay)
}
}
private fun processImage(
data: ByteBuffer,
frameMetadata: FrameMetadata,
graphicOverlay: GraphicOverlay
) {
val frameStartMs = SystemClock.elapsedRealtime()
// If live viewport is on (that is the underneath surface view takes care of the camera preview
// drawing), skip the unnecessary bitmap creation that used for the manual preview drawing.
val bitmap =
if (PreferenceUtils.isCameraLiveViewportEnabled(graphicOverlay.context)) null
else BitmapUtils.getBitmap(data, frameMetadata)
if (isMlImageEnabled(graphicOverlay.context)) {
val mlImage =
ByteBufferMlImageBuilder(
data,
frameMetadata.width,
frameMetadata.height,
MlImage.IMAGE_FORMAT_NV21
)
.setRotation(frameMetadata.rotation)
.build()
requestDetectInImage(mlImage, graphicOverlay, bitmap, /* shouldShowFps= */ true, frameStartMs)
.addOnSuccessListener(executor) { processLatestImage(graphicOverlay) }
// This is optional. Java Garbage collection can also close it eventually.
mlImage.close()
return
}
requestDetectInImage(
InputImage.fromByteBuffer(
data,
frameMetadata.width,
frameMetadata.height,
frameMetadata.rotation,
InputImage.IMAGE_FORMAT_NV21
),
graphicOverlay,
bitmap,
/* shouldShowFps= */ true,
frameStartMs
)
.addOnSuccessListener(executor) { processLatestImage(graphicOverlay) }
}
// -----------------Code for processing live preview frame from CameraX API-----------------------
@RequiresApi(VERSION_CODES.LOLLIPOP)
@ExperimentalGetImage
override fun processImageProxy(image: ImageProxy, graphicOverlay: GraphicOverlay) {
val frameStartMs = SystemClock.elapsedRealtime()
if (isShutdown) {
return
}
var bitmap: Bitmap? = null
if (!PreferenceUtils.isCameraLiveViewportEnabled(graphicOverlay.context)) {
bitmap = BitmapUtils.getBitmap(image)
}
if (isMlImageEnabled(graphicOverlay.context)) {
val mlImage =
MediaMlImageBuilder(image.image!!).setRotation(image.imageInfo.rotationDegrees).build()
requestDetectInImage(
mlImage,
graphicOverlay,
/* originalCameraImage= */ bitmap,
/* shouldShowFps= */ true,
frameStartMs
)
// When the image is from CameraX analysis use case, must call image.close() on received
// images when finished using them. Otherwise, new images may not be received or the camera
// may stall.
// Currently MlImage doesn't support ImageProxy directly, so we still need to call
// ImageProxy.close() here.
.addOnCompleteListener { image.close() }
return
}
requestDetectInImage(
InputImage.fromMediaImage(image.image!!, image.imageInfo.rotationDegrees),
graphicOverlay,
/* originalCameraImage= */ bitmap,
/* shouldShowFps= */ true,
frameStartMs
)
// When the image is from CameraX analysis use case, must call image.close() on received
// images when finished using them. Otherwise, new images may not be received or the camera
// may stall.
.addOnCompleteListener { image.close() }
}
// -----------------Common processing logic-------------------------------------------------------
private fun requestDetectInImage(
image: InputImage,
graphicOverlay: GraphicOverlay,
originalCameraImage: Bitmap?,
shouldShowFps: Boolean,
frameStartMs: Long
): Task<T> {
return setUpListener(
detectInImage(image),
graphicOverlay,
originalCameraImage,
shouldShowFps,
frameStartMs
)
}
private fun requestDetectInImage(
image: MlImage,
graphicOverlay: GraphicOverlay,
originalCameraImage: Bitmap?,
shouldShowFps: Boolean,
frameStartMs: Long
): Task<T> {
return setUpListener(
detectInImage(image),
graphicOverlay,
originalCameraImage,
shouldShowFps,
frameStartMs
)
}
private fun setUpListener(
task: Task<T>,
graphicOverlay: GraphicOverlay,
originalCameraImage: Bitmap?,
shouldShowFps: Boolean,
frameStartMs: Long
): Task<T> {
val detectorStartMs = SystemClock.elapsedRealtime()
return task
.addOnSuccessListener(
executor,
OnSuccessListener { results: T ->
val endMs = SystemClock.elapsedRealtime()
val currentFrameLatencyMs = endMs - frameStartMs
val currentDetectorLatencyMs = endMs - detectorStartMs
if (numRuns >= 500) {
resetLatencyStats()
}
numRuns++
frameProcessedInOneSecondInterval++
totalFrameMs += currentFrameLatencyMs
maxFrameMs = max(currentFrameLatencyMs, maxFrameMs)
minFrameMs = min(currentFrameLatencyMs, minFrameMs)
totalDetectorMs += currentDetectorLatencyMs
maxDetectorMs = max(currentDetectorLatencyMs, maxDetectorMs)
minDetectorMs = min(currentDetectorLatencyMs, minDetectorMs)
// Only log inference info once per second. When frameProcessedInOneSecondInterval is
// equal to 1, it means this is the first frame processed during the current second.
if (frameProcessedInOneSecondInterval == 1) {
Log.d(TAG, "Num of Runs: $numRuns")
Log.d(
TAG,
"Frame latency: max=" +
maxFrameMs +
", min=" +
minFrameMs +
", avg=" +
totalFrameMs / numRuns
)
Log.d(
TAG,
"Detector latency: max=" +
maxDetectorMs +
", min=" +
minDetectorMs +
", avg=" +
totalDetectorMs / numRuns
)
val mi = ActivityManager.MemoryInfo()
activityManager.getMemoryInfo(mi)
val availableMegs: Long = mi.availMem / 0x100000L
Log.d(TAG, "Memory available in system: $availableMegs MB")
}
graphicOverlay.clear()
if (originalCameraImage != null) {
graphicOverlay.add(CameraImageGraphic(graphicOverlay, originalCameraImage))
}
this@VisionProcessorBase.onSuccess(results, graphicOverlay)
if (!PreferenceUtils.shouldHideDetectionInfo(graphicOverlay.context)) {
graphicOverlay.add(
InferenceInfoGraphic(
graphicOverlay,
currentFrameLatencyMs,
currentDetectorLatencyMs,
if (shouldShowFps) framesPerSecond else null
)
)
}
graphicOverlay.postInvalidate()
}
)
.addOnFailureListener(
executor,
OnFailureListener { e: Exception ->
graphicOverlay.clear()
graphicOverlay.postInvalidate()
val error = "Failed to process. Error: " + e.localizedMessage
Toast.makeText(
graphicOverlay.context,
"""
$error
Cause: ${e.cause}
""".trimIndent(),
Toast.LENGTH_SHORT
)
.show()
Log.d(TAG, error)
e.printStackTrace()
this@VisionProcessorBase.onFailure(e)
}
)
}
override fun stop() {
executor.shutdown()
isShutdown = true
resetLatencyStats()
fpsTimer.cancel()
}
private fun resetLatencyStats() {
numRuns = 0
totalFrameMs = 0
maxFrameMs = 0
minFrameMs = Long.MAX_VALUE
totalDetectorMs = 0
maxDetectorMs = 0
minDetectorMs = Long.MAX_VALUE
}
protected abstract fun detectInImage(image: InputImage): Task<T>
protected open fun detectInImage(image: MlImage): Task<T> {
return Tasks.forException(
MlKitException(
"MlImage is currently not demonstrated for this feature",
MlKitException.INVALID_ARGUMENT
)
)
}
protected abstract fun onSuccess(results: T, graphicOverlay: GraphicOverlay)
protected abstract fun onFailure(e: Exception)
protected open fun isMlImageEnabled(context: Context?): Boolean {
return false
}
}