ridoo14 commited on
Commit
4674250
·
verified ·
1 Parent(s): c86179a

Upload 6 files

Browse files
Files changed (6) hide show
  1. .gitignore +162 -0
  2. Model/yolov8l.pt +3 -0
  3. main.py +99 -0
  4. requirements.txt +0 -0
  5. src/run.ipynb +0 -0
  6. src/sample.jpeg +0 -0
.gitignore ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110
+ .pdm.toml
111
+ .pdm-python
112
+ .pdm-build/
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ #.idea/
Model/yolov8l.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:64c9115303f6a25575f82200d1b22ec409fa6bd7d08d0313884fc20d919478cd
3
+ size 87792836
main.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import base64
3
+ import numpy as np
4
+ import cv2
5
+ from PIL import Image as PILImage
6
+ from ultralytics import YOLO
7
+ from fastapi import FastAPI, HTTPException
8
+ from pydantic import BaseModel
9
+ from typing import Optional
10
+ from matplotlib import cm
11
+
12
+ from fastapi.middleware.cors import CORSMiddleware
13
+
14
+ app = FastAPI()
15
+
16
+ # Add CORS middleware to allow requests from anywhere
17
+ app.add_middleware(
18
+ CORSMiddleware,
19
+ allow_origins=["*"], # Allow all origins
20
+ allow_credentials=True,
21
+ allow_methods=["*"], # Allow all HTTP methods
22
+ allow_headers=["*"], # Allow all headers
23
+ )
24
+
25
+ class ImageRequest(BaseModel):
26
+ image: str # Base64-encoded image string
27
+
28
+ class ObjectDetectionSystem:
29
+ def __init__(self, model_path='Model/yolov8l.pt'):
30
+ self.yolo_model = YOLO(model_path)
31
+ self.color_map = cm.get_cmap("tab20", len(self.yolo_model.names)) # Generate distinct colors
32
+
33
+ def detect_objects(self, image_base64: str, confidence_threshold: float = 0.5):
34
+ try:
35
+ # Decode Base64 and convert to NumPy array
36
+ image_data = base64.b64decode(image_base64)
37
+ pil_image = PILImage.open(io.BytesIO(image_data)).convert("RGB")
38
+ image_np = np.array(pil_image)
39
+
40
+ # Resize image for consistent processing
41
+ input_size = 640 # Example size for YOLO models
42
+ height, width, _ = image_np.shape
43
+ scale = input_size / max(height, width)
44
+ resized_image = cv2.resize(image_np, (int(width * scale), int(height * scale)))
45
+
46
+ # Perform object detection
47
+ results = self.yolo_model(resized_image)
48
+
49
+ # Draw results on image
50
+ output_image = resized_image.copy()
51
+ for result in results:
52
+ boxes = result.boxes
53
+ for box in boxes:
54
+ x1, y1, x2, y2 = box.xyxy[0].cpu().numpy()
55
+ x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
56
+ confidence = float(box.conf[0])
57
+ class_id = int(box.cls[0])
58
+ class_name = self.yolo_model.names[class_id]
59
+
60
+ if confidence > confidence_threshold:
61
+ # Generate color for this class
62
+ color = tuple(int(c * 255) for c in self.color_map(class_id)[:3])
63
+
64
+ # Draw bounding box
65
+ cv2.rectangle(output_image, (x1, y1), (x2, y2), color, 2)
66
+
67
+ # Add label with confidence
68
+ label = f'{class_name} ({confidence:.2f})'
69
+ label_size, baseline = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
70
+ label_y = max(y1, label_size[1] + 10)
71
+ cv2.rectangle(output_image, (x1, label_y - label_size[1] - 10),
72
+ (x1 + label_size[0], label_y + baseline - 10), color, -1)
73
+ cv2.putText(output_image, label, (x1, label_y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
74
+
75
+ # Convert back to Base64
76
+ output_pil = PILImage.fromarray(output_image)
77
+ buffered = io.BytesIO()
78
+ output_pil.save(buffered, format="PNG")
79
+ encoded_image = base64.b64encode(buffered.getvalue()).decode("utf-8")
80
+
81
+ return encoded_image
82
+
83
+ except Exception as e:
84
+ raise HTTPException(status_code=500, detail=str(e))
85
+
86
+ # Initialize the detector with a more advanced model
87
+ detector = ObjectDetectionSystem('Model/yolov8l.pt')
88
+
89
+ @app.post("/detect")
90
+ async def detect_objects(request: ImageRequest):
91
+ try:
92
+ result_image = detector.detect_objects(request.image)
93
+ return {"processed_image": result_image}
94
+ except Exception as e:
95
+ raise HTTPException(status_code=500, detail=str(e))
96
+
97
+ @app.get("/")
98
+ async def root():
99
+ return {"message": "Object Detection API is running"}
requirements.txt ADDED
Binary file (544 Bytes). View file
 
src/run.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
src/sample.jpeg ADDED