Views
No views yet
1import numpy as np
2import tensorflow as tf
3from PIL import Image
4
5# Load label file
6with open('imagenet_classes.txt', 'r') as file:
7 lines = file.readlines()
8
9index_to_label = {index: line.strip() for index, line in enumerate(lines)}
10
11# Initialize interpreter and IO details
12tfl_model = tf.lite.Interpreter(model_path=tf_model_path)
13tfl_model.allocate_tensors()
14input_details = tfl_model.get_input_details()
15output_details = tfl_model.get_output_details()
16
17# Load and preprocess the image
18image = Image.open(image_path).resize((384, 384), Image.BICUBIC)
19
20image = np.array(image, dtype=np.float32)
21mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)
22std = np.array([0.229, 0.224, 0.225], dtype=np.float32)
23image = (image / 255.0 - mean) / std
24
25image = np.expand_dims(image, axis=-1)
26image = np.rollaxis(image, 3)
27
28# Inference and postprocessing
29input = input_details[0]
30tfl_model.set_tensor(input["index"], image)
31tfl_model.invoke()
32
33tfl_output = tfl_model.get_tensor(output_details[0]["index"])
34tfl_output_tensor = tf.convert_to_tensor(tfl_output)
35tfl_softmax_output = tf.nn.softmax(tfl_output_tensor, axis=1)
36
37tfl_top5_probs, tfl_top5_indices = tf.math.top_k(tfl_softmax_output, k=5)
38
39# Get the top5 class labels and probabilities
40tfl_probs_list = tfl_top5_probs[0].numpy().tolist()
41tfl_index_list = tfl_top5_indices[0].numpy().tolist()
42
43for index, prob in zip(tfl_index_list, tfl_probs_list):
44 print(f"{index_to_label[index]}: {round(prob*100, 2)}%")1@article{qin2024mobilenetv4,
2 title={MobileNetV4-Universal Models for the Mobile Ecosystem},
3 author={Qin, Danfeng and Leichner, Chas and Delakis, Manolis and Fornoni, Marco and Luo, Shixin and Yang, Fan and Wang, Weijun and Banbury, Colby and Ye, Chengxi and Akin, Berkin and others},
4 journal={arXiv preprint arXiv:2404.10518},
5 year={2024}
6}1@misc{rw2019timm,
2 author = {Ross Wightman},
3 title = {PyTorch Image Models},
4 year = {2019},
5 publisher = {GitHub},
6 journal = {GitHub repository},
7 doi = {10.5281/zenodo.4414861},
8 howpublished = {\url{https://github.com/huggingface/pytorch-image-models}}
9}