Surya152002 commited on
Commit
1ef41c2
·
verified ·
1 Parent(s): 6ac54bd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -55
app.py CHANGED
@@ -1,68 +1,48 @@
 
 
1
  import streamlit as st
 
2
  import numpy as np
3
- import cv2
4
- from PIL import Image
5
-
6
- # Function to process the image and count coins
7
- def count_coins(image):
8
- # Convert PIL Image to OpenCV format
9
- img = np.array(image)
10
- img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
11
-
12
- # Resize image
13
- img = cv2.resize(img, (640, 800))
14
- image_copy = img.copy()
15
 
16
- # Apply Gaussian Blur
17
- img = cv2.GaussianBlur(img, (7, 7), 3)
 
 
18
 
19
- # Convert to grayscale
20
- gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
21
 
22
- # Apply thresholding
23
- ret, thresh = cv2.threshold(gray, 170, 255, cv2.THRESH_BINARY)
24
-
25
- # Find contours
26
- contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
27
-
28
- # Calculate contour areas
29
- area = {}
30
- for i in range(len(contours)):
31
- cnt = contours[i]
32
- ar = cv2.contourArea(cnt)
33
- area[i] = ar
34
-
35
- # Sort contours by area
36
- srt = sorted(area.items(), key=lambda x: x[1], reverse=True)
37
- results = np.array(srt).astype("int")
38
 
39
- # Count coins (objects with area greater than a threshold)
40
- num = np.argwhere(results[:, 1] > 500).shape[0]
 
 
 
 
 
 
41
 
42
- # Draw contours around coins
43
- for i in range(1, num):
44
- image_copy = cv2.drawContours(image_copy, contours, results[i, 0], (0, 255, 0), 3)
45
 
46
- return image_copy, num - 1 # Return processed image and the count of coins
 
47
 
48
- # Streamlit app
49
- def main():
50
- st.title("Coin Detection and Counting")
51
- st.write("Upload an image to detect and count coins.")
52
 
53
- # File uploader for image
54
- uploaded_file = st.file_uploader("Upload Image", type=["jpg", "png", "jpeg"])
55
- if uploaded_file is not None:
56
- # Open the uploaded image with PIL
57
- image = Image.open(uploaded_file)
58
- st.image(image, caption="Uploaded Image", use_column_width=True)
59
 
60
- # Count coins
61
- processed_image, coin_count = count_coins(image)
62
 
63
- # Display processed image and the result
64
- st.image(cv2.cvtColor(processed_image, cv2.COLOR_BGR2RGB), caption=f"Processed Image - Coins Counted: {coin_count}", use_column_width=True)
65
- st.success(f"Number of coins detected: {coin_count}")
 
66
 
67
- if __name__ == "__main__":
68
- main()
 
1
+ import cv2
2
+ import torch
3
  import streamlit as st
4
+ from matplotlib import pyplot as plt
5
  import numpy as np
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ # Function to detect circular objects in the image
8
+ def detect_circles(image_path):
9
+ # Load pre-trained YOLOv5 model
10
+ model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # using a smaller model for faster inference
11
 
12
+ # Read the image
13
+ img = cv2.imread(image_path)
14
 
15
+ # Run the YOLOv5 model on the image
16
+ results = model(img)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
+ # Filter out circular objects (based on class label, you may adjust this depending on what YOLO detects)
19
+ circles = 0
20
+ for det in results.xywh[0]:
21
+ # Class 44 is for "circular" items like wheels, stop signs, etc. (may vary by model and training)
22
+ if int(det[5]) == 44: # Replace 44 with the appropriate class ID for circular objects
23
+ circles += 1
24
+
25
+ return circles, results
26
 
27
+ # Streamlit UI
28
+ st.title("Circular Object Detection with YOLOv5")
 
29
 
30
+ # Upload image file
31
+ image_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
32
 
33
+ if image_file is not None:
34
+ # Open the uploaded image using PIL (Pillow)
35
+ st.image(image_file, caption="Uploaded Image", use_column_width=True)
 
36
 
37
+ # Process the image
38
+ circles_count, results = detect_circles(image_file)
 
 
 
 
39
 
40
+ # Display result
41
+ st.write(f"Number of circular objects detected: {circles_count}")
42
 
43
+ # Display detection output
44
+ fig, ax = plt.subplots(1, 1, figsize=(10, 6))
45
+ ax.imshow(results.render()[0])
46
+ plt.show()
47
 
48
+ st.pyplot(fig)