I have following code in place which pass camera taken image as Bitmap
to be feeded in to Machine learning model.
CameraFragment.kt
private lateinit var photo: Bitmap
private fun takePhoto() {
val imageCapture = imageCapture ?: return
imageCapture.takePicture(cameraExecutor, object :
ImageCapture.OnImageCapturedCallback() {
override fun onCaptureSuccess(image: ImageProxy) {
super.onCaptureSuccess(image)
photo = imageProxyToBitmap(image)
}
})
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
...
val ml = MachineLearning()
ml.downloadModel()
val prediction = ml.predict(photo)
...
}
MachineLearning.kt
fun predict(photo: Bitmap): Boolean {
// image pre-processing
...
}
private fun downloadeModel() {
val conditions = CustomModelDownloadConditions.Builder()
.requireWifi()
.build()
FirebaseModelDownloader.getInstance()
.getModel("model-name", DownloadType.LOCAL_MODEL_UPDATE_IN_BACKGROUND, conditions)
.addOnCompleteListener { customModel ->
customModel.addOnSuccessListener { model: CustomModel? ->
modelFile = model?.file!!
interpreter = Interpreter(modelFile)
}
}
.addOnFailureListener {
Log.d(TAG, "Internet is necessary to download the model!")
}
}
But I am not sure how to do the image pre-processing. According to this codelab ImageProcessor
class should be used for this. But I am not sure how to do this?
Given below is analogous Python code to test the model using single image
def testing_tflite_model(sample_type, quantized):
converted_model = "models/converted/model.tflite"
if quantized:
converted_model = "models/converted/model-quantized.tflite"
bad_image_path = "..."
good_image_path = "..."
img = io.imread(bad)
if sample_type == "good":
img = io.imread(good_image_path)
resized = resize(img, (106, 106)).astype('float32')
test_image = np.expand_dims(resized, axis=0)
normalized_image = test_image - 0.5
prediction = run_tflite_model(converted_model, normalized_image)
if prediction == 1:
print("Bad")
else:
print("Good")
My try so far:
val imageProcessor = ImageProcessor.Builder()
.add(ResizeOp(106, 106, ResizeOp.ResizeMethod.NEAREST_NEIGHBOR))
.build()
But how to normalize the image as in python code?