AmirKaseb commited on
Commit
64ea6aa
·
verified ·
1 Parent(s): 6d56071

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +57 -0
main.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import torch
3
+ from PIL import Image
4
+ from torchvision.transforms import functional as F
5
+ from yolov5.utils.general import non_max_suppression, scale_coords
6
+ from yolov5.models.experimental import attempt_load
7
+ from yolov5.utils.plots import plot_one_box
8
+ import cv2
9
+
10
+ @st.cache(allow_output_mutation=True)
11
+ def load_model():
12
+ # Load your pre-trained YOLOv5 model
13
+ model = attempt_load('best.pt', map_location=torch.device('cpu'))
14
+ return model
15
+
16
+ def detect_objects(image, model, confidence=0.4, iou=0.5):
17
+ img = Image.fromarray(image.astype('uint8')).convert('RGB')
18
+ img_tensor = F.to_tensor(img)
19
+ img_tensor, _ = model.preprocess(img_tensor, None, None)
20
+ pred = model(img_tensor)[0]
21
+ pred = non_max_suppression(pred, confidence, iou)[0]
22
+
23
+ if pred is not None and len(pred):
24
+ pred[:, :4] = scale_coords(img_tensor.shape[2:], pred[:, :4], img.size).round()
25
+
26
+ return pred
27
+
28
+ def main():
29
+ st.title("Real-time Object Detection with YOLOv5")
30
+
31
+ # Choose between image upload or video stream
32
+ option = st.radio("Choose Input Type:", ("Image Upload", "Video Stream"))
33
+
34
+ if option == "Image Upload":
35
+ uploaded_image = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
36
+
37
+ if uploaded_image is not None:
38
+ image = Image.open(uploaded_image)
39
+ st.image(image, caption="Uploaded Image", use_column_width=True)
40
+ st.write("")
41
+
42
+ if st.button("Detect Objects"):
43
+ st.write("Detecting...")
44
+ model = load_model()
45
+ with st.spinner('Wait for it...'):
46
+ pred = detect_objects(image, model)
47
+ if pred is not None and len(pred):
48
+ for *xyxy, conf, cls in pred:
49
+ label = f'{model.names[int(cls)]} {conf:.2f}'
50
+ plot_one_box(xyxy, image, label=label, color=(255, 0, 0), line_thickness=2)
51
+ st.image(image, caption="Result", use_column_width=True)
52
+
53
+ elif option == "Video Stream":
54
+ st.write("Video stream functionality is not implemented yet.")
55
+
56
+ if __name__ == '__main__':
57
+ main()