fahrnphi commited on
Commit
2dec43a
·
verified ·
1 Parent(s): b272b12

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -58
app.py CHANGED
@@ -9,69 +9,49 @@ import cv2
9
  model_path = "fahrnphi_exam_project.keras"
10
  model = tf.keras.models.load_model(model_path)
11
 
12
- # Set image dimensions
13
- img_height, img_width = 150, 150 # Input size for the model
14
-
15
- # Define a function for prediction and returning labels and probabilities
16
- def predict_labels_and_probabilities(image_path):
17
- # Load the image using OpenCV
18
- img = cv2.imdecode(np.frombuffer(image_path.read(), np.uint8), cv2.IMREAD_COLOR)
19
- img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
 
 
20
 
21
- # Scan the image in a grid-like fashion
22
- step_size = 50 # Step size for the grid
23
- predictions = []
24
 
25
- for y in range(0, img_rgb.shape[0] - img_height + 1, step_size):
26
- for x in range(0, img_rgb.shape[1] - img_width + 1, step_size):
27
- patch = img_rgb[y:y+img_height, x:x+img_width]
28
- patch_resized = cv2.resize(patch, (img_height, img_width))
29
- patch_array = image.img_to_array(patch_resized)
30
- patch_array = np.expand_dims(patch_array, axis=0)
31
- patch_array /= 255. # Scale pixel values
32
-
33
- preds = model.predict(patch_array)
34
- class_idx = np.argmax(preds[0])
35
-
36
- # Map class indices to class names
37
- class_labels = {
38
- 0: 'Bell Pepper', 1: 'Carrot', 2: 'Garlic', 3: 'Ginger',
39
- 4: 'Jalapeno', 5: 'Onion', 6: 'Potato', 7: 'Sweetpotato', 8: 'Tomato'
40
- }
41
- predicted_class = class_labels[class_idx]
42
- probability = preds[0][class_idx]
43
-
44
- if probability > 0.5: # Threshold to filter out low confidence predictions
45
- predictions.append((predicted_class, probability, x, y, x+img_width, y+img_height))
46
- # Draw rectangle around detected ingredients
47
- cv2.rectangle(img_rgb, (x, y), (x+img_width, y+img_height), (255, 0, 0), 2)
48
 
49
- return predictions, img_rgb
50
 
51
- # Streamlit App
52
- st.title("Intelligent Recipe Finder Classification")
 
53
 
54
- uploaded_file = st.file_uploader("Choose an ingredients image...", type="jpg")
 
55
 
56
- if uploaded_file is not None:
57
- # Display the uploaded image
58
- st.image(uploaded_file, caption='Uploaded Ingredient Image.', use_column_width=True)
 
 
59
 
60
- # Perform the prediction and display the results
61
- predictions, img_with_boxes = predict_labels_and_probabilities(uploaded_file)
62
- st.write("Predictions for detected ingredients in the image:")
63
-
64
- for i, (label, probability, x1, y1, x2, y2) in enumerate(predictions):
65
- st.write(f"Ingredient {i+1}:")
66
- st.write(f"Prediction: {label}")
67
- st.write(f"Probability: {probability}")
68
- st.write(f"Location: ({x1}, {y1}) to ({x2}, {y2})")
69
-
70
- # Display the image with rectangles
71
- st.image(img_with_boxes, caption='Detected Ingredients', use_column_width=True)
72
 
73
- # Debugging information
74
- if not predictions:
75
- st.write("No ingredients detected with probability above the threshold.")
76
- else:
77
- st.write(f"Total detected patches: {len(predictions)}")
 
 
 
 
 
 
 
9
  model_path = "fahrnphi_exam_project.keras"
10
  model = tf.keras.models.load_model(model_path)
11
 
12
+ # Define the core prediction function
13
+ def predict_ingredient(image):
14
+ # Preprocess image
15
+ image = image.resize((150, 150)) # Resize the image to 150x150
16
+ image = image.convert('RGB') # Ensure image has 3 channels
17
+ image = np.array(image)
18
+ image = np.expand_dims(image, axis=0) # Add batch dimension
19
+
20
+ # Predict
21
+ prediction = model.predict(image)
22
 
23
+ # Apply softmax to get probabilities for each class
24
+ probabilities = tf.nn.softmax(prediction, axis=1)
 
25
 
26
+ # Map probabilities to ingredient classes
27
+ class_names = ['Peperoni', 'Carrot', 'Garlic', 'Ginger', 'Jalapeno', 'Onion', 'Potato', 'Sweetpotato', 'Tomato']
28
+ probabilities_dict = {ingredient_class: round(float(probability), 2) for ingredient_class, probability in zip(class_names, probabilities.numpy()[0])}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
+ return probabilities_dict
31
 
32
+ # Streamlit interface
33
+ st.title("Ingredient Classifier")
34
+ st.write("A simple MLP classification model for image classification using a pretrained model.")
35
 
36
+ # Upload image
37
+ uploaded_image = st.file_uploader("Choose an image...", type=["jpg", "png"])
38
 
39
+ if uploaded_image is not None:
40
+ image = Image.open(uploaded_image)
41
+ st.image(image, caption='Uploaded Image.', use_column_width=True)
42
+ st.write("")
43
+ st.write("Classifying...")
44
 
45
+ predictions = predict_ingredient(image)
 
 
 
 
 
 
 
 
 
 
 
46
 
47
+ # Display predictions as a DataFrame
48
+ st.write("### Prediction Probabilities")
49
+ df = pd.DataFrame(predictions.items(), columns=["ingredient", "Probability"])
50
+ st.dataframe(df)
51
+
52
+ # Display predictions as a pie chart
53
+ st.write("### Prediction Chart")
54
+ fig, ax = plt.subplots()
55
+ ax.pie(df["Probability"], labels=df["ingredient"], autopct='%1.1f%%', colors=plt.cm.Paired.colors)
56
+ ax.set_title('Prediction Probabilities')
57
+ st.pyplot(fig)