Spaces:
Build error
Build error
Create app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647from ultralytics import YOLOimport gradio as grimport numpy as npimport cv2
# Load the trained modelmodel = YOLO('/content/drive/MyDrive/MS-Thesis/Multi-Class Classification/runs/classify/train4/weights/best.pt') # Replace with the path to your trained model
# Prediction functiondef predict_image(image): try: # Convert the input image to the format expected by the model image = np.array(image) image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
# Make prediction results = model.predict(image_bgr) # Get the predicted class and confidence using the correct attributes predicted_class = results[0].names[results[0].probs.top1] confidence = results[0].probs.top1conf # Annotate image with predicted class and confidence annotated_image = image.copy() cv2.putText(annotated_image, f"{predicted_class}: {confidence:.2f}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2, cv2.LINE_AA) # Convert the annotated image back to RGB for display annotated_image_rgb = cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB) return annotated_image_rgb, f"Predicted: {predicted_class} with {confidence:.2f} confidence" except Exception as e: # Return an error message if something goes wrong return None, f"Error: {str(e)}"
# Define the Gradio interfaceinterface = gr.Interface( fn=predict_image, inputs=gr.Image(label="Upload an Image"), outputs=[gr.Image(label="Annotated Image"), gr.Text(label="Prediction")], title="Fruit Freshness Classifier", description="Upload an image of a fruit, and the model will predict whether it is Fresh, Mild, or Rotten, and display the result on the image.")
# Launch the interfaceinterface.launch()app.pyAdded+47