Spaces:
Runtime error
Runtime error
Update src/streamlit_app.py
Browse files1231234567896789101112131410111213141516171819161720212223242526272829303132333435363719202138394023244142432627282930314445464748495051525354555657585960333435363738394061626364656667686970import altair as altimport numpy as npimport pandas as pdimport streamlit as stimport torchimport numpy as npimport cv2from PIL import Imagefrom detectron2.engine import DefaultPredictorfrom detectron2.config import get_cfgfrom detectron2 import model_zoo
"""# Welcome to Streamlit!
Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [communityforums](https://discuss.streamlit.io).
In the meantime, below is an example of what you can do with just a few lines of code:"""# Function to load the modeldef load_model(model_path): # Initialize the configuration cfg = get_cfg() cfg.merge_from_file(model_zoo.get_config_file("COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml")) cfg.MODEL.WEIGHTS = model_path # Path to your trained model cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # Threshold for prediction predictor = DefaultPredictor(cfg) return predictor
num_points = st.slider("Number of points in spiral", 1, 10000, 1100)num_turns = st.slider("Number of turns in spiral", 1, 300, 31)# Function to make predictionsdef predict_fn(image, model_path): # Convert image to numpy array image = np.array(image) # Load model predictor = load_model(model_path) # Make predictions outputs = predictor(image) # Extract predicted bounding boxes and class labels instances = outputs["instances"] pred_classes = instances.pred_classes.to("cpu").numpy() pred_boxes = instances.pred_boxes.tensor.to("cpu").numpy() return pred_classes, pred_boxes
indices = np.linspace(0, 1, num_points)theta = 2 * np.pi * num_turns * indicesradius = indices# Streamlit UI elementsst.title("Wildlife Detection with Your Model")
x = radius * np.cos(theta)y = radius * np.sin(theta)# Upload an image for testinguploaded_image = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
df = pd.DataFrame({ "x": x, "y": y, "idx": indices, "rand": np.random.randn(num_points),})if uploaded_image is not None: # Open the uploaded image using PIL image = Image.open(uploaded_image) # Display the uploaded image st.image(image, caption="Uploaded Image", use_column_width=True) # Set model path model_path = "sandbox338/wild-life-model" # Your model path on Hugging Face # Make predictions pred_classes, pred_boxes = predict_fn(image, model_path) # Display predictions st.write(f"Predicted classes: {pred_classes}") st.write(f"Predicted bounding boxes: {pred_boxes}")
st.altair_chart(alt.Chart(df, height=700, width=700) .mark_point(filled=True) .encode( x=alt.X("x", axis=None), y=alt.Y("y", axis=None), color=alt.Color("idx", legend=None, scale=alt.Scale()), size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])), )) # Optionally, visualize predictions on the image img_array = np.array(image) for i, box in enumerate(pred_boxes): start_point = (int(box[0]), int(box[1])) end_point = (int(box[2]), int(box[3])) img_array = cv2.rectangle(img_array, start_point, end_point, (0, 255, 0), 2) st.image(img_array, caption="Predicted Image with Bounding Boxes", use_column_width=True)else: st.write("Please upload an image to detect wildlife!")src/streamlit_app.py+63-33