dschandra commited on
Commit
86ac6c1
·
verified ·
1 Parent(s): 32394fd

Update food_identification.py

Browse files
Files changed (1) hide show
  1. food_identification.py +10 -10
food_identification.py CHANGED
@@ -1,33 +1,33 @@
1
  import tensorflow as tf
2
  import tensorflow_hub as hub
3
- import json
4
  import numpy as np
5
 
6
- # Load the Food101 model from TensorFlow Hub
7
  MODEL_URL = "https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/classification/5"
8
  model = hub.load(MODEL_URL)
9
 
10
- # Download and load ImageNet labels
11
  LABELS_URL = "https://storage.googleapis.com/download.tensorflow.org/data/imagenet_class_index.json"
12
  labels_path = tf.keras.utils.get_file("imagenet_labels.json", LABELS_URL)
13
 
14
- # Properly parse the JSON file to load labels
 
15
  with open(labels_path, "r") as f:
16
  food_labels = json.load(f)
17
 
18
  def identify_food(image):
19
  """
20
- Identify food items in the image using the TensorFlow Food101 model.
21
  """
22
- # Preprocess image
23
  image = image.resize((224, 224)) # Resize for model compatibility
24
- image_array = np.array(image, dtype=np.float32) / 255.0 # Normalize and convert to float32
25
  image_array = np.expand_dims(image_array, axis=0) # Add batch dimension
26
 
27
- # Predict using the model
28
  predictions = model(image_array)
29
  predicted_class = np.argmax(predictions[0])
30
 
31
- # Get the top prediction label
32
  food_item = food_labels.get(str(predicted_class), ["Unknown"])[1]
33
- return [food_item]
 
1
  import tensorflow as tf
2
  import tensorflow_hub as hub
 
3
  import numpy as np
4
 
5
+ # Load a pretrained food recognition model from TensorFlow Hub
6
  MODEL_URL = "https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/classification/5"
7
  model = hub.load(MODEL_URL)
8
 
9
+ # Food-101 labels (customized or from FoodAI)
10
  LABELS_URL = "https://storage.googleapis.com/download.tensorflow.org/data/imagenet_class_index.json"
11
  labels_path = tf.keras.utils.get_file("imagenet_labels.json", LABELS_URL)
12
 
13
+ # Load labels
14
+ import json
15
  with open(labels_path, "r") as f:
16
  food_labels = json.load(f)
17
 
18
  def identify_food(image):
19
  """
20
+ Dynamically detect food items from the image using a pretrained model.
21
  """
22
+ # Preprocess the image
23
  image = image.resize((224, 224)) # Resize for model compatibility
24
+ image_array = np.array(image, dtype=np.float32) / 255.0 # Normalize pixel values
25
  image_array = np.expand_dims(image_array, axis=0) # Add batch dimension
26
 
27
+ # Predict the class using the model
28
  predictions = model(image_array)
29
  predicted_class = np.argmax(predictions[0])
30
 
31
+ # Get the food label for the top prediction
32
  food_item = food_labels.get(str(predicted_class), ["Unknown"])[1]
33
+ return food_item