-
-
Notifications
You must be signed in to change notification settings - Fork 84
/
MainActivity.kt
370 lines (318 loc) · 15.5 KB
/
MainActivity.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
/*
* Copyright 2023 Shubham Panchal
* 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:https://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.ml.quaterion.facenetdetection
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.media.ExifInterface
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.DocumentsContract
import android.text.method.ScrollingMovementMethod
import android.util.Size
import android.view.View
import android.view.WindowInsets
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.documentfile.provider.DocumentFile
import androidx.lifecycle.LifecycleOwner
import com.google.common.util.concurrent.ListenableFuture
import com.ml.quaterion.facenetdetection.databinding.ActivityMainBinding
import com.ml.quaterion.facenetdetection.model.FaceNetModel
import com.ml.quaterion.facenetdetection.model.Models
import java.io.*
import java.util.concurrent.Executors
class MainActivity : AppCompatActivity() {
private var isSerializedDataStored = false
// Serialized data will be stored ( in app's private storage ) with this filename.
private val SERIALIZED_DATA_FILENAME = "image_data"
// Shared Pref key to check if the data was stored.
private val SHARED_PREF_IS_DATA_STORED_KEY = "is_data_stored"
private lateinit var activityMainBinding : ActivityMainBinding
private lateinit var previewView : PreviewView
private lateinit var frameAnalyser : FrameAnalyser
private lateinit var faceNetModel : FaceNetModel
private lateinit var fileReader : FileReader
private lateinit var cameraProviderFuture : ListenableFuture<ProcessCameraProvider>
private lateinit var sharedPreferences: SharedPreferences
// <----------------------- User controls --------------------------->
// Use the device's GPU to perform faster computations.
// Refer https://www.tensorflow.org/lite/performance/gpu
private val useGpu = true
// Use XNNPack to accelerate inference.
// Refer https://blog.tensorflow.org/2020/07/accelerating-tensorflow-lite-xnnpack-integration.html
private val useXNNPack = true
// You may the change the models here.
// Use the model configs in Models.kt
// Default is Models.FACENET ; Quantized models are faster
private val modelInfo = Models.FACENET
// Camera Facing
private val cameraFacing = CameraSelector.LENS_FACING_BACK
// <---------------------------------------------------------------->
companion object {
lateinit var logTextView : TextView
fun setMessage( message : String ) {
logTextView.text = message
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Remove the status bar to have a full screen experience
// See this answer on SO -> https://stackoverflow.com/a/68152688/10878733
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.decorView.windowInsetsController!!
.hide( WindowInsets.Type.statusBars() or WindowInsets.Type.navigationBars())
}
else {
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
}
activityMainBinding = ActivityMainBinding.inflate( layoutInflater )
setContentView( activityMainBinding.root )
previewView = activityMainBinding.previewView
logTextView = activityMainBinding.logTextview
logTextView.movementMethod = ScrollingMovementMethod()
// Necessary to keep the Overlay above the PreviewView so that the boxes are visible.
val boundingBoxOverlay = activityMainBinding.bboxOverlay
boundingBoxOverlay.cameraFacing = cameraFacing
boundingBoxOverlay.setWillNotDraw( false )
boundingBoxOverlay.setZOrderOnTop( true )
faceNetModel = FaceNetModel( this , modelInfo , useGpu , useXNNPack )
frameAnalyser = FrameAnalyser( this , boundingBoxOverlay , faceNetModel )
fileReader = FileReader( faceNetModel )
// We'll only require the CAMERA permission from the user.
// For scoped storage, particularly for accessing documents, we won't require WRITE_EXTERNAL_STORAGE or
// READ_EXTERNAL_STORAGE permissions. See https://developer.android.com/training/data-storage
if ( ActivityCompat.checkSelfPermission( this , Manifest.permission.CAMERA ) != PackageManager.PERMISSION_GRANTED ) {
requestCameraPermission()
}
else {
startCameraPreview()
}
sharedPreferences = getSharedPreferences( getString( R.string.app_name ) , Context.MODE_PRIVATE )
isSerializedDataStored = sharedPreferences.getBoolean( SHARED_PREF_IS_DATA_STORED_KEY , false )
if ( !isSerializedDataStored ) {
Logger.log( "No serialized data was found. Select the images directory.")
showSelectDirectoryDialog()
}
else {
val alertDialog = AlertDialog.Builder( this ).apply {
setTitle( "Serialized Data")
setMessage( "Existing image data was found on this device. Would you like to load it?" )
setCancelable( false )
setNegativeButton( "LOAD") { dialog, which ->
dialog.dismiss()
frameAnalyser.faceList = loadSerializedImageData()
Logger.log( "Serialized data loaded.")
}
setPositiveButton( "RESCAN") { dialog, which ->
dialog.dismiss()
launchChooseDirectoryIntent()
}
create()
}
alertDialog.show()
}
}
// ---------------------------------------------- //
// Attach the camera stream to the PreviewView.
private fun startCameraPreview() {
cameraProviderFuture = ProcessCameraProvider.getInstance( this )
cameraProviderFuture.addListener({
val cameraProvider = cameraProviderFuture.get()
bindPreview(cameraProvider) },
ContextCompat.getMainExecutor(this) )
}
private fun bindPreview(cameraProvider : ProcessCameraProvider) {
val preview : Preview = Preview.Builder().build()
val cameraSelector : CameraSelector = CameraSelector.Builder()
.requireLensFacing( cameraFacing )
.build()
preview.setSurfaceProvider( previewView.surfaceProvider )
val imageFrameAnalysis = ImageAnalysis.Builder()
.setTargetResolution(Size( 480, 640 ) )
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_RGBA_8888)
.build()
imageFrameAnalysis.setAnalyzer(Executors.newSingleThreadExecutor(), frameAnalyser )
cameraProvider.bindToLifecycle(this as LifecycleOwner, cameraSelector, preview , imageFrameAnalysis )
}
// We let the system handle the requestCode. This doesn't require onRequestPermissionsResult and
// hence makes the code cleaner.
// See the official docs -> https://developer.android.com/training/permissions/requesting#request-permission
private fun requestCameraPermission() {
cameraPermissionLauncher.launch( Manifest.permission.CAMERA )
}
private val cameraPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission() ) {
isGranted ->
if ( isGranted ) {
startCameraPreview()
}
else {
val alertDialog = AlertDialog.Builder( this ).apply {
setTitle( "Camera Permission")
setMessage( "The app couldn't function without the camera permission." )
setCancelable( false )
setPositiveButton( "ALLOW" ) { dialog, which ->
dialog.dismiss()
requestCameraPermission()
}
setNegativeButton( "CLOSE" ) { dialog, which ->
dialog.dismiss()
finish()
}
create()
}
alertDialog.show()
}
}
// ---------------------------------------------- //
// Open File chooser to choose the images directory.
private fun showSelectDirectoryDialog() {
val alertDialog = AlertDialog.Builder( this ).apply {
setTitle( "Select Images Directory")
setMessage( "As mentioned in the project\'s README file, please select a directory which contains the images." )
setCancelable( false )
setPositiveButton( "SELECT") { dialog, which ->
dialog.dismiss()
launchChooseDirectoryIntent()
}
create()
}
alertDialog.show()
}
private fun launchChooseDirectoryIntent() {
val intent = Intent( Intent.ACTION_OPEN_DOCUMENT_TREE )
// startForActivityResult is deprecated.
// See this SO thread -> https://stackoverflow.com/questions/62671106/onactivityresult-method-is-deprecated-what-is-the-alternative
directoryAccessLauncher.launch( intent )
}
// Read the contents of the select directory here.
// The system handles the request code here as well.
// See this SO question -> https://stackoverflow.com/questions/47941357/how-to-access-files-in-a-directory-given-a-content-uri
private val directoryAccessLauncher = registerForActivityResult( ActivityResultContracts.StartActivityForResult() ) {
val dirUri = it.data?.data ?: return@registerForActivityResult
val childrenUri =
DocumentsContract.buildChildDocumentsUriUsingTree(
dirUri,
DocumentsContract.getTreeDocumentId( dirUri )
)
val tree = DocumentFile.fromTreeUri(this, childrenUri)
val images = ArrayList<Pair<String,Bitmap>>()
var errorFound = false
if ( tree!!.listFiles().isNotEmpty()) {
for ( doc in tree.listFiles() ) {
if ( doc.isDirectory && !errorFound ) {
val name = doc.name!!
for ( imageDocFile in doc.listFiles() ) {
try {
images.add( Pair( name , getFixedBitmap( imageDocFile.uri ) ) )
}
catch ( e : Exception ) {
errorFound = true
Logger.log( "Could not parse an image in $name directory. Make sure that the file structure is " +
"as described in the README of the project and then restart the app." )
break
}
}
Logger.log( "Found ${doc.listFiles().size} images in $name directory" )
}
else {
errorFound = true
Logger.log( "The selected folder should contain only directories. Make sure that the file structure is " +
"as described in the README of the project and then restart the app." )
}
}
}
else {
errorFound = true
Logger.log( "The selected folder doesn't contain any directories. Make sure that the file structure is " +
"as described in the README of the project and then restart the app." )
}
if ( !errorFound ) {
fileReader.run( images , fileReaderCallback )
Logger.log( "Detecting faces in ${images.size} images ..." )
}
else {
val alertDialog = AlertDialog.Builder( this ).apply {
setTitle( "Error while parsing directory")
setMessage( "There were some errors while parsing the directory. Please see the log below. Make sure that the file structure is " +
"as described in the README of the project and then tap RESELECT" )
setCancelable( false )
setPositiveButton( "RESELECT") { dialog, which ->
dialog.dismiss()
launchChooseDirectoryIntent()
}
setNegativeButton( "CANCEL" ){ dialog , which ->
dialog.dismiss()
finish()
}
create()
}
alertDialog.show()
}
}
// Get the image as a Bitmap from given Uri and fix the rotation using the Exif interface
// Source -> https://stackoverflow.com/questions/14066038/why-does-an-image-captured-using-camera-intent-gets-rotated-on-some-devices-on-a
private fun getFixedBitmap( imageFileUri : Uri ) : Bitmap {
var imageBitmap = BitmapUtils.getBitmapFromUri( contentResolver , imageFileUri )
val exifInterface = ExifInterface( contentResolver.openInputStream( imageFileUri )!! )
imageBitmap =
when (exifInterface.getAttributeInt( ExifInterface.TAG_ORIENTATION ,
ExifInterface.ORIENTATION_UNDEFINED )) {
ExifInterface.ORIENTATION_ROTATE_90 -> BitmapUtils.rotateBitmap( imageBitmap , 90f )
ExifInterface.ORIENTATION_ROTATE_180 -> BitmapUtils.rotateBitmap( imageBitmap , 180f )
ExifInterface.ORIENTATION_ROTATE_270 -> BitmapUtils.rotateBitmap( imageBitmap , 270f )
else -> imageBitmap
}
return imageBitmap
}
// ---------------------------------------------- //
private val fileReaderCallback = object : FileReader.ProcessCallback {
override fun onProcessCompleted(data: ArrayList<Pair<String, FloatArray>>, numImagesWithNoFaces: Int) {
frameAnalyser.faceList = data
saveSerializedImageData( data )
Logger.log( "Images parsed. Found $numImagesWithNoFaces images with no faces." )
}
}
private fun saveSerializedImageData(data : ArrayList<Pair<String,FloatArray>> ) {
val serializedDataFile = File( filesDir , SERIALIZED_DATA_FILENAME )
ObjectOutputStream( FileOutputStream( serializedDataFile ) ).apply {
writeObject( data )
flush()
close()
}
sharedPreferences.edit().putBoolean( SHARED_PREF_IS_DATA_STORED_KEY , true ).apply()
}
private fun loadSerializedImageData() : ArrayList<Pair<String,FloatArray>> {
val serializedDataFile = File( filesDir , SERIALIZED_DATA_FILENAME )
val objectInputStream = ObjectInputStream( FileInputStream( serializedDataFile ) )
val data = objectInputStream.readObject() as ArrayList<Pair<String,FloatArray>>
objectInputStream.close()
return data
}
}