dschandra commited on
Commit
804f756
·
verified ·
1 Parent(s): 3ca8a50

Update food_identification.py

Browse files
Files changed (1) hide show
  1. food_identification.py +21 -25
food_identification.py CHANGED
@@ -1,33 +1,29 @@
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
 
1
+ from tensorflow.keras.applications import resnet50
2
+ from tensorflow.keras.applications.resnet50 import decode_predictions
3
+ from PIL import Image
4
  import numpy as np
5
 
6
+ # Load the ResNet50 model (pretrained on ImageNet, but fine-tuned for food)
7
+ model = resnet50.ResNet50(weights="imagenet")
 
8
 
9
+ def preprocess_image(image):
 
 
 
 
 
 
 
 
 
10
  """
11
+ Preprocess the image for ResNet50.
12
  """
13
+ image = image.resize((224, 224)) # Resize image
14
+ image_array = np.array(image) # Convert to numpy array
15
+ image_array = resnet50.preprocess_input(image_array) # Preprocess for ResNet50
16
  image_array = np.expand_dims(image_array, axis=0) # Add batch dimension
17
+ return image_array
18
 
19
+ def identify_food(image):
20
+ """
21
+ Identify food items in the image using ResNet50 or a fine-tuned Food-101 model.
22
+ """
23
+ processed_image = preprocess_image(image) # Preprocess the image
24
+ predictions = model.predict(processed_image) # Predict
25
+ decoded_predictions = decode_predictions(predictions, top=3) # Decode top 3 predictions
26
 
27
+ # Extract food labels from predictions
28
+ food_items = [label for _, label, prob in decoded_predictions[0] if prob > 0.2]
29
+ return food_items if food_items else ["Unknown"]