File size: 1,758 Bytes
b2e5bfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# Copyright 2022-2024,2026 NXP
# SPDX-License-Identifier: MIT

import argparse
import time

import cv2
import numpy as np
import tensorflow as tf

LABELS = ['angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral']

parser = argparse.ArgumentParser(description="Deepface emotion inference example")
parser.add_argument("-m", "--model",
                    default="original_model/emotion_uint8_float32.tflite",
                    type=str,
                    help="Path to the TFLite model file.")
parser.add_argument("-i", "--input", default="example_input.jpg", type=str,
                    help="Path to a grayscale face crop image (48x48).")
args = parser.parse_args()

interpreter = tf.lite.Interpreter(args.model)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
print("Loaded model:", args.model)

# Load grayscale image and resize to 48x48.
im = cv2.imread(args.input, cv2.IMREAD_GRAYSCALE)
if im is None:
    raise FileNotFoundError(f"Could not open image: {args.input}")

start = time.time()

im = cv2.resize(im, (48, 48))
# Shape: (1, 48, 48, 1), normalized to [0, 1].
im = im[None, ..., None].astype(np.float32) / 255.0

# Quantize input: scale from float to uint8 using model quantization params.
input_scale, input_zero_point = input_details[0]["quantization"]
im_q = im / input_scale + input_zero_point
im_q = im_q.astype(np.uint8)

interpreter.set_tensor(input_details[0]['index'], im_q)
interpreter.invoke()
out = interpreter.get_tensor(output_details[0]['index'])

end = time.time()

print("Output tensor:", out)
print("Recognized emotion:", LABELS[int(out.argmax())])
print(f"Inference time: {(end - start) * 1000:.2f} ms")