Senasu commited on
Commit
822dfb7
·
verified ·
1 Parent(s): f4d9211

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -20
app.py CHANGED
@@ -1,14 +1,12 @@
1
  import numpy as np
2
- import cvlib as cv
3
- from cvlib.object_detection import draw_bbox
4
  import streamlit as st
5
  from PIL import Image
6
  from collections import Counter
7
- import cv2 # OpenCV for loading the YOLO model
8
 
9
  # Streamlit app title
10
  st.set_page_config(page_title="Object Detection App", page_icon="🖼️", layout="centered")
11
- st.title("Object Detection with cvlib 🖼️")
12
 
13
  # Custom header and instructions
14
  st.markdown("""
@@ -21,48 +19,80 @@ The application will display the image with bounding boxes around the objects.
21
  st.markdown("### Step 1: Upload an Image for Object Detection")
22
  uploaded_file = st.file_uploader("Choose an image...", type=["png", "jpg", "jpeg"])
23
 
24
- # Function to skip download and use local files for the model
25
- def detect_common_objects_skip_progress(image, model='yolov3'):
 
26
  model_config = 'yolov3.cfg' # Path to your downloaded .cfg file
27
  model_weights = 'yolov3.weights' # Path to your downloaded .weights file
28
-
29
- # Load the YOLO model manually using OpenCV
30
  net = cv2.dnn.readNet(model_weights, model_config)
31
 
32
- # Perform object detection using cvlib (cvlib internally uses the loaded model)
33
- box, label, count = cv.detect_common_objects(image, model='yolov3', net=net)
34
- return box, label, count
 
 
 
 
 
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  if uploaded_file is not None:
37
  # Convert image file to OpenCV format
38
  image = np.array(Image.open(uploaded_file))
 
39
 
40
- # Perform object detection with manually provided paths
41
- box, label, count = detect_common_objects_skip_progress(image)
42
 
43
  # Draw bounding boxes on the image
44
- output_image = draw_bbox(image, box, label, count)
 
 
 
 
 
45
 
46
  # Step 2: Display image with bounding boxes
47
  st.markdown("### Step 2: Detected Objects in the Image")
48
- st.image(output_image, channels="BGR", use_column_width=True)
49
 
50
  # Step 3: Display the count of detected objects dynamically
51
  st.markdown("### Step 3: Detected Objects Count")
52
-
53
- # Count each label in the image using Counter
54
- label_counts = Counter(label)
55
 
56
  # Display counts in a well-formatted table
57
  for obj, count in label_counts.items():
58
- st.markdown(f"**{obj.capitalize()}s**: {count}")
59
 
60
  st.markdown("""
61
  ---
62
  ### Tips:
63
  - You can upload different images to see how the object detection model works.
64
  - Supported formats: PNG, JPG, JPEG.
65
- - The app uses cvlib to detect common objects in the images, such as people, cars, trucks, and more.
66
  """)
67
 
68
  # Display a footer
 
1
  import numpy as np
2
+ import cv2 # OpenCV for loading the YOLO model
 
3
  import streamlit as st
4
  from PIL import Image
5
  from collections import Counter
 
6
 
7
  # Streamlit app title
8
  st.set_page_config(page_title="Object Detection App", page_icon="🖼️", layout="centered")
9
+ st.title("Object Detection with OpenCV and YOLO 🖼️")
10
 
11
  # Custom header and instructions
12
  st.markdown("""
 
19
  st.markdown("### Step 1: Upload an Image for Object Detection")
20
  uploaded_file = st.file_uploader("Choose an image...", type=["png", "jpg", "jpeg"])
21
 
22
+ # Function to detect objects using OpenCV's YOLO
23
+ def detect_objects_with_yolo(image):
24
+ # Load YOLO model configuration and weights
25
  model_config = 'yolov3.cfg' # Path to your downloaded .cfg file
26
  model_weights = 'yolov3.weights' # Path to your downloaded .weights file
 
 
27
  net = cv2.dnn.readNet(model_weights, model_config)
28
 
29
+ # Get the names of the output layers
30
+ layer_names = net.getLayerNames()
31
+ output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]
32
+
33
+ # Prepare the image for YOLO
34
+ blob = cv2.dnn.blobFromImage(image, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
35
+ net.setInput(blob)
36
+ outs = net.forward(output_layers)
37
 
38
+ # Process YOLO outputs
39
+ boxes = []
40
+ labels = []
41
+ confidences = []
42
+
43
+ for out in outs:
44
+ for detection in out:
45
+ scores = detection[5:]
46
+ class_id = np.argmax(scores)
47
+ confidence = scores[class_id]
48
+ if confidence > 0.5: # Confidence threshold
49
+ center_x = int(detection[0] * image.shape[1])
50
+ center_y = int(detection[1] * image.shape[0])
51
+ w = int(detection[2] * image.shape[1])
52
+ h = int(detection[3] * image.shape[0])
53
+ x = int(center_x - w / 2)
54
+ y = int(center_y - h / 2)
55
+ boxes.append([x, y, w, h])
56
+ confidences.append(float(confidence))
57
+ labels.append(class_id)
58
+
59
+ return boxes, labels, confidences
60
+
61
+ # Display the uploaded image and detect objects
62
  if uploaded_file is not None:
63
  # Convert image file to OpenCV format
64
  image = np.array(Image.open(uploaded_file))
65
+ image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # Convert from RGB to BGR for OpenCV
66
 
67
+ # Perform object detection with YOLO
68
+ boxes, labels, confidences = detect_objects_with_yolo(image)
69
 
70
  # Draw bounding boxes on the image
71
+ for i, box in enumerate(boxes):
72
+ x, y, w, h = box
73
+ label = labels[i]
74
+ confidence = confidences[i]
75
+ cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
76
+ cv2.putText(image, f"{label} {confidence:.2f}", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
77
 
78
  # Step 2: Display image with bounding boxes
79
  st.markdown("### Step 2: Detected Objects in the Image")
80
+ st.image(image, channels="BGR", use_column_width=True)
81
 
82
  # Step 3: Display the count of detected objects dynamically
83
  st.markdown("### Step 3: Detected Objects Count")
84
+ label_counts = Counter(labels)
 
 
85
 
86
  # Display counts in a well-formatted table
87
  for obj, count in label_counts.items():
88
+ st.markdown(f"**Object ID {obj}**: {count}")
89
 
90
  st.markdown("""
91
  ---
92
  ### Tips:
93
  - You can upload different images to see how the object detection model works.
94
  - Supported formats: PNG, JPG, JPEG.
95
+ - The app uses OpenCV with YOLO for detecting common objects.
96
  """)
97
 
98
  # Display a footer