pushpinder06 commited on
Commit
203b6f8
·
verified ·
1 Parent(s): f261fe1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -11
app.py CHANGED
@@ -3,28 +3,43 @@ from tensorflow.keras.models import load_model
3
  from tensorflow.keras.preprocessing.image import img_to_array
4
  import numpy as np
5
  from PIL import Image
 
6
 
7
- # Load model
8
  model = load_model("waste_classification(Mobilenetv2).h5")
9
  class_names = ['cardboard', 'glass', 'metal', 'paper', 'plastic', 'trash']
10
 
11
- # Prediction function
12
- def predict_from_webcam(image):
13
  image = image.resize((224, 224))
14
  img_array = img_to_array(image) / 255.0
15
  img_array = np.expand_dims(img_array, axis=0)
16
 
17
  prediction = model.predict(img_array)[0]
18
- predicted_class = class_names[np.argmax(prediction)]
 
19
  confidence = float(np.max(prediction))
20
 
21
- return f"{predicted_class} ({confidence*100:.1f}%)"
 
 
 
 
 
 
 
22
 
23
- # Use gr.Camera() for webcam input (Gradio 4.x)
 
 
24
  gr.Interface(
25
- fn=predict_from_webcam,
26
- inputs=gr.Camera(type="pil"), # webcam input as PIL image
27
- outputs="text",
28
- title="Live Waste Classifier",
29
- description="Point your webcam at waste material. The model will classify it live."
 
 
 
 
30
  ).launch()
 
3
  from tensorflow.keras.preprocessing.image import img_to_array
4
  import numpy as np
5
  from PIL import Image
6
+ import matplotlib.pyplot as plt
7
 
8
+ # Load your trained model
9
  model = load_model("waste_classification(Mobilenetv2).h5")
10
  class_names = ['cardboard', 'glass', 'metal', 'paper', 'plastic', 'trash']
11
 
12
+ # Prediction function: returns label + chart
13
+ def predict_with_chart(image):
14
  image = image.resize((224, 224))
15
  img_array = img_to_array(image) / 255.0
16
  img_array = np.expand_dims(img_array, axis=0)
17
 
18
  prediction = model.predict(img_array)[0]
19
+ pred_index = np.argmax(prediction)
20
+ pred_label = class_names[pred_index]
21
  confidence = float(np.max(prediction))
22
 
23
+ # Plot bar chart
24
+ fig, ax = plt.subplots(figsize=(6, 4))
25
+ ax.bar(class_names, prediction, color='skyblue')
26
+ ax.set_ylabel('Probability')
27
+ ax.set_ylim(0, 1)
28
+ ax.set_title('Class Probabilities')
29
+ plt.xticks(rotation=45)
30
+ plt.tight_layout()
31
 
32
+ return f"Prediction: {pred_label} ({confidence*100:.1f}%)", fig
33
+
34
+ # Gradio interface: webcam + upload
35
  gr.Interface(
36
+ fn=predict_with_chart,
37
+ inputs=gr.Image(type="pil", label="Upload or Capture Waste Image", source="upload"),
38
+ outputs=[
39
+ gr.Textbox(label="Predicted Class"),
40
+ gr.Plot(label="Class Probability Chart")
41
+ ],
42
+ title="Waste Classifier - Upload or Webcam",
43
+ description="Upload a waste image or capture using webcam. The model shows predicted class and probability chart.",
44
+ live=True
45
  ).launch()