snnn001 commited on
Commit
130a24d
·
verified ·
1 Parent(s): 457f62b

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +62 -0
README.md CHANGED
@@ -44,6 +44,68 @@ num_params: 3,504,872
44
  The license information of the original model was missing.
45
 
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  ### BibTeX entry and citation info
48
 
49
  ```bibtex
 
44
  The license information of the original model was missing.
45
 
46
 
47
+ ## Use
48
+
49
+ ```python
50
+ #!/usr/bin/env python3
51
+ import argparse, json
52
+ import numpy as np
53
+ from PIL import Image
54
+ from huggingface_hub import hf_hub_download
55
+ from ai_edge_litert.compiled_model import CompiledModel
56
+
57
+ def preprocess(img: Image.Image) -> np.ndarray:
58
+ img = img.convert("RGB")
59
+ w, h = img.size
60
+ s = 256
61
+ if w < h:
62
+ img = img.resize((s, int(round(h * s / w))), Image.BILINEAR)
63
+ else:
64
+ img = img.resize((int(round(w * s / h)), s), Image.BILINEAR)
65
+ left = (img.size[0] - 224) // 2
66
+ top = (img.size[1] - 224) // 2
67
+ img = img.crop((left, top, left + 224, top + 224))
68
+
69
+ x = np.asarray(img, dtype=np.float32) / 255.0
70
+ x = (x - np.array([0.485, 0.456, 0.406], dtype=np.float32)) / np.array(
71
+ [0.229, 0.224, 0.225], dtype=np.float32
72
+ )
73
+ return np.transpose(x, (2, 0, 1))
74
+
75
+ def main():
76
+ ap = argparse.ArgumentParser()
77
+ ap.add_argument("--image", required=True)
78
+ args = ap.parse_args()
79
+
80
+ model_path = hf_hub_download("litert-community/MobileNet-v2", "mobilenet_v2.tflite")
81
+ labels_path = hf_hub_download(
82
+ "huggingface/label-files", "imagenet-1k-id2label.json", repo_type="dataset"
83
+ )
84
+ with open(labels_path, "r", encoding="utf-8") as f:
85
+ id2label = {int(k): v for k, v in json.load(f).items()}
86
+
87
+ img = Image.open(args.image)
88
+ x = preprocess(img)
89
+
90
+ model = CompiledModel.from_file(model_path)
91
+ inp = model.create_input_buffers(0)
92
+ out = model.create_output_buffers(0)
93
+
94
+ inp[0].write(x)
95
+ model.run_by_index(0, inp, out)
96
+
97
+ req = model.get_output_buffer_requirements(0, 0)
98
+ y = out[0].read(req["buffer_size"] // np.dtype(np.float32).itemsize, np.float32)
99
+
100
+ pred = int(np.argmax(y))
101
+ label = id2label.get(pred, f"class_{pred}")
102
+
103
+ print(f"Top-1 class index: {pred}")
104
+ print(f"Top-1 label: {label}")
105
+ if __name__ == "__main__":
106
+ main()
107
+ ```
108
+
109
  ### BibTeX entry and citation info
110
 
111
  ```bibtex