Surya152002 commited on
Commit
7cb0447
·
verified ·
1 Parent(s): 5f84ddc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -37
app.py CHANGED
@@ -1,51 +1,83 @@
1
- import torch
2
- import cv2
3
  import streamlit as st
4
- from matplotlib import pyplot as plt
5
  import numpy as np
6
  from PIL import Image
7
- from io import BytesIO
8
 
9
- # Function to detect circular objects in the image
10
- def detect_circles(image):
11
- # Load pre-trained YOLOv5 model
12
- model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # using a smaller model for faster inference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
- # Convert PIL image to NumPy array
15
- img = np.array(image)
 
 
16
 
17
- # Run the YOLOv5 model on the image
18
- results = model(img)
19
-
20
- # Filter out circular objects (based on class label, you may adjust this depending on what YOLO detects)
21
- circles = 0
22
- for det in results.xywh[0]:
23
- # Class 44 is for "circular" items like wheels, stop signs, etc. (may vary by model and training)
24
- if int(det[5]) == 44: # Replace 44 with the appropriate class ID for circular objects
25
- circles += 1
26
 
27
- return circles, results
 
 
 
 
28
 
29
- # Streamlit UI
30
- st.title("Circular Object Detection with YOLOv5")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
- # Upload image file
33
- image_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
 
34
 
35
- if image_file is not None:
36
- # Open the uploaded image using PIL (Pillow)
37
- image = Image.open(image_file)
38
- st.image(image, caption="Uploaded Image", use_column_width=True)
39
 
40
- # Process the image
41
- circles_count, results = detect_circles(image)
 
42
 
43
- # Display result
44
- st.write(f"Number of circular objects detected: {circles_count}")
45
 
46
- # Display detection output
47
- fig, ax = plt.subplots(1, 1, figsize=(10, 6))
48
- ax.imshow(results.render()[0])
49
- plt.show()
50
 
51
- st.pyplot(fig)
 
 
 
 
1
  import streamlit as st
2
+ import cv2
3
  import numpy as np
4
  from PIL import Image
 
5
 
6
+ # Function to count circles in an image frame
7
+ def count_circles(frame):
8
+ # Convert to grayscale and blur to remove noise
9
+ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
10
+ gray = cv2.medianBlur(gray, 5)
11
+
12
+ # Hough Circle Transform to detect circles
13
+ circles = cv2.HoughCircles(
14
+ gray, cv2.HOUGH_GRADIENT, dp=1.2, minDist=50,
15
+ param1=50, param2=30, minRadius=10, maxRadius=100
16
+ )
17
+
18
+ circle_count = 0
19
+ if circles is not None:
20
+ circles = np.uint16(np.around(circles))
21
+ for i in circles[0, :]:
22
+ # Draw the circle
23
+ cv2.circle(frame, (i[0], i[1]), i[2], (0, 255, 0), 3)
24
+ circle_count += 1
25
+
26
+ return frame, circle_count
27
 
28
+ # Streamlit UI
29
+ def main():
30
+ st.title("Circle Counter with Camera Input")
31
+ st.write("Use your device camera to count and highlight circles in real-time or upload an image.")
32
 
33
+ # Option to choose between Camera and Image upload
34
+ option = st.radio("Choose Input Method:", ["Camera", "Upload Image"])
 
 
 
 
 
 
 
35
 
36
+ # If user selects Camera
37
+ if option == "Camera":
38
+ st.write("Starting Camera Stream...")
39
+ camera_stream = st.empty() # Stream placeholder
40
+ stop_button = st.button("Stop Camera")
41
 
42
+ # Access camera using OpenCV
43
+ cap = cv2.VideoCapture(0) # 0 is the default camera
44
+
45
+ while cap.isOpened() and not stop_button:
46
+ ret, frame = cap.read()
47
+ if not ret:
48
+ st.error("Failed to capture video!")
49
+ break
50
+
51
+ # Count circles in the frame
52
+ processed_frame, circle_count = count_circles(frame)
53
+
54
+ # Convert the frame for display in Streamlit
55
+ frame_rgb = cv2.cvtColor(processed_frame, cv2.COLOR_BGR2RGB)
56
+ camera_stream.image(frame_rgb, caption=f"Circles Detected: {circle_count}", use_column_width=True)
57
+
58
+ cap.release()
59
+ st.write("Camera Stopped.")
60
 
61
+ # If user selects Upload Image
62
+ elif option == "Upload Image":
63
+ uploaded_file = st.file_uploader("Upload an image...", type=["jpg", "jpeg", "png"])
64
 
65
+ if uploaded_file is not None:
66
+ # Display uploaded image
67
+ image = Image.open(uploaded_file)
68
+ st.image(image, caption="Uploaded Image", use_column_width=True)
69
 
70
+ # Convert to OpenCV format
71
+ frame = np.array(image)
72
+ frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
73
 
74
+ # Count circles
75
+ processed_image, circle_count = count_circles(frame)
76
 
77
+ # Display processed image
78
+ processed_image_rgb = cv2.cvtColor(processed_image, cv2.COLOR_BGR2RGB)
79
+ st.image(processed_image_rgb, caption=f"Circles Detected: {circle_count}", use_column_width=True)
80
+ st.success(f"Number of circles detected: {circle_count}")
81
 
82
+ if __name__ == "__main__":
83
+ main()