Update food_identification.py
Browse files- food_identification.py +21 -25
food_identification.py
CHANGED
|
@@ -1,33 +1,29 @@
|
|
| 1 |
-
|
| 2 |
-
|
|
|
|
| 3 |
import numpy as np
|
| 4 |
|
| 5 |
-
# Load
|
| 6 |
-
|
| 7 |
-
model = hub.load(MODEL_URL)
|
| 8 |
|
| 9 |
-
|
| 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 |
-
|
| 21 |
"""
|
| 22 |
-
#
|
| 23 |
-
|
| 24 |
-
image_array =
|
| 25 |
image_array = np.expand_dims(image_array, axis=0) # Add batch dimension
|
|
|
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
-
#
|
| 32 |
-
|
| 33 |
-
return
|
|
|
|
| 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"]
|