mingyang91 commited on
Commit
f977726
·
verified ·
0 Parent(s):

init commit

Browse files
.idea/detector.iml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="PYTHON_MODULE" version="4">
3
+ <component name="NewModuleRootManager">
4
+ <content url="file://$MODULE_DIR$">
5
+ <excludeFolder url="file://$MODULE_DIR$/.venv" />
6
+ </content>
7
+ <orderEntry type="inheritedJdk" />
8
+ <orderEntry type="sourceFolder" forTests="false" />
9
+ </component>
10
+ </module>
.idea/inspectionProfiles/profiles_settings.xml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ <component name="InspectionProjectProfileManager">
2
+ <settings>
3
+ <option name="USE_PROJECT_PROFILE" value="false" />
4
+ <version value="1.0" />
5
+ </settings>
6
+ </component>
.idea/misc.xml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="Black">
4
+ <option name="sdkName" value="Python 3.9 (detector)" />
5
+ </component>
6
+ <component name="ProjectRootManager" version="2" project-jdk-name="Python 3.9 (detector)" project-jdk-type="Python SDK" />
7
+ </project>
.idea/modules.xml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/detector.iml" filepath="$PROJECT_DIR$/.idea/detector.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
.idea/vcs.xml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="VcsDirectoryMappings">
4
+ <mapping directory="$PROJECT_DIR$" vcs="Git" />
5
+ </component>
6
+ </project>
.idea/workspace.xml ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="AutoImportSettings">
4
+ <option name="autoReloadType" value="SELECTIVE" />
5
+ </component>
6
+ <component name="ChangeListManager">
7
+ <list default="true" id="d7806539-b6d6-42e7-bb45-1565f5d54891" name="Changes" comment="">
8
+ <change afterPath="$PROJECT_DIR$/.idea/detector.iml" afterDir="false" />
9
+ <change afterPath="$PROJECT_DIR$/.idea/inspectionProfiles/profiles_settings.xml" afterDir="false" />
10
+ <change afterPath="$PROJECT_DIR$/.idea/misc.xml" afterDir="false" />
11
+ <change afterPath="$PROJECT_DIR$/.idea/modules.xml" afterDir="false" />
12
+ <change afterPath="$PROJECT_DIR$/.idea/vcs.xml" afterDir="false" />
13
+ <change afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
14
+ <change afterPath="$PROJECT_DIR$/Dockerfile" afterDir="false" />
15
+ <change afterPath="$PROJECT_DIR$/README.md" afterDir="false" />
16
+ <change afterPath="$PROJECT_DIR$/demo.py" afterDir="false" />
17
+ <change afterPath="$PROJECT_DIR$/main.py" afterDir="false" />
18
+ <change afterPath="$PROJECT_DIR$/model.py" afterDir="false" />
19
+ </list>
20
+ <option name="SHOW_DIALOG" value="false" />
21
+ <option name="HIGHLIGHT_CONFLICTS" value="true" />
22
+ <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
23
+ <option name="LAST_RESOLUTION" value="IGNORE" />
24
+ </component>
25
+ <component name="FileTemplateManagerImpl">
26
+ <option name="RECENT_TEMPLATES">
27
+ <list>
28
+ <option value="FastAPI main" />
29
+ <option value="FastAPI test_main" />
30
+ <option value="Python Script" />
31
+ </list>
32
+ </option>
33
+ </component>
34
+ <component name="Git.Settings">
35
+ <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
36
+ </component>
37
+ <component name="MarkdownSettingsMigration">
38
+ <option name="stateVersion" value="1" />
39
+ </component>
40
+ <component name="ProjectColorInfo">{
41
+ &quot;associatedIndex&quot;: 6
42
+ }</component>
43
+ <component name="ProjectId" id="2ZOmY7Vu9MEYYgni7zMjwPlz52O" />
44
+ <component name="ProjectLevelVcsManager" settingsEditedManually="true" />
45
+ <component name="ProjectViewState">
46
+ <option name="hideEmptyMiddlePackages" value="true" />
47
+ <option name="showLibraryContents" value="true" />
48
+ </component>
49
+ <component name="PropertiesComponent">{
50
+ &quot;keyToString&quot;: {
51
+ &quot;Python.demo.executor&quot;: &quot;Run&quot;,
52
+ &quot;RunOnceActivity.OpenProjectViewOnStart&quot;: &quot;true&quot;,
53
+ &quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
54
+ &quot;git-widget-placeholder&quot;: &quot;master&quot;,
55
+ &quot;last_opened_file_path&quot;: &quot;/Users/famer.me/PycharmProjects/detector&quot;,
56
+ &quot;node.js.detected.package.eslint&quot;: &quot;true&quot;,
57
+ &quot;node.js.detected.package.tslint&quot;: &quot;true&quot;,
58
+ &quot;node.js.selected.package.eslint&quot;: &quot;(autodetect)&quot;,
59
+ &quot;node.js.selected.package.tslint&quot;: &quot;(autodetect)&quot;,
60
+ &quot;nodejs_package_manager_path&quot;: &quot;npm&quot;,
61
+ &quot;vue.rearranger.settings.migration&quot;: &quot;true&quot;
62
+ }
63
+ }</component>
64
+ <component name="RecentsManager">
65
+ <key name="CopyFile.RECENT_KEYS">
66
+ <recent name="$PROJECT_DIR$" />
67
+ </key>
68
+ </component>
69
+ <component name="RunManager" selected="Python.demo">
70
+ <configuration name="demo" type="PythonConfigurationType" factoryName="Python" temporary="true" nameIsGenerated="true">
71
+ <module name="detector" />
72
+ <option name="ENV_FILES" value="" />
73
+ <option name="INTERPRETER_OPTIONS" value="" />
74
+ <option name="PARENT_ENVS" value="true" />
75
+ <envs>
76
+ <env name="PYTHONUNBUFFERED" value="1" />
77
+ </envs>
78
+ <option name="SDK_HOME" value="" />
79
+ <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
80
+ <option name="IS_MODULE_SDK" value="true" />
81
+ <option name="ADD_CONTENT_ROOTS" value="true" />
82
+ <option name="ADD_SOURCE_ROOTS" value="true" />
83
+ <EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
84
+ <option name="SCRIPT_NAME" value="$PROJECT_DIR$/demo.py" />
85
+ <option name="PARAMETERS" value="" />
86
+ <option name="SHOW_COMMAND_LINE" value="false" />
87
+ <option name="EMULATE_TERMINAL" value="false" />
88
+ <option name="MODULE_MODE" value="false" />
89
+ <option name="REDIRECT_INPUT" value="false" />
90
+ <option name="INPUT_FILE" value="" />
91
+ <method v="2" />
92
+ </configuration>
93
+ <configuration name="detector" type="Python.FastAPI">
94
+ <option name="file" value="$PROJECT_DIR$/main.py" />
95
+ <module name="detector" />
96
+ <option name="ENV_FILES" value="" />
97
+ <option name="INTERPRETER_OPTIONS" value="" />
98
+ <option name="PARENT_ENVS" value="true" />
99
+ <option name="SDK_HOME" value="" />
100
+ <option name="WORKING_DIRECTORY" value="" />
101
+ <option name="IS_MODULE_SDK" value="false" />
102
+ <option name="ADD_CONTENT_ROOTS" value="true" />
103
+ <option name="ADD_SOURCE_ROOTS" value="true" />
104
+ <EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
105
+ <option name="launchJavascriptDebuger" value="false" />
106
+ <method v="2" />
107
+ </configuration>
108
+ <recent_temporary>
109
+ <list>
110
+ <item itemvalue="Python.demo" />
111
+ </list>
112
+ </recent_temporary>
113
+ </component>
114
+ <component name="SharedIndexes">
115
+ <attachedChunks>
116
+ <set>
117
+ <option value="bundled-python-sdk-7a29c1521ef0-c986f194a52a-com.jetbrains.pycharm.pro.sharedIndexes.bundled-PY-233.11799.298" />
118
+ </set>
119
+ </attachedChunks>
120
+ </component>
121
+ <component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
122
+ <component name="TaskManager">
123
+ <task active="true" id="Default" summary="Default task">
124
+ <changelist id="d7806539-b6d6-42e7-bb45-1565f5d54891" name="Changes" comment="" />
125
+ <created>1702301546100</created>
126
+ <option name="number" value="Default" />
127
+ <option name="presentableId" value="Default" />
128
+ <updated>1702301546100</updated>
129
+ <workItem from="1702301554378" duration="4025000" />
130
+ <workItem from="1702450051021" duration="586000" />
131
+ </task>
132
+ <servers />
133
+ </component>
134
+ <component name="TypeScriptGeneratedFilesManager">
135
+ <option name="version" value="3" />
136
+ </component>
137
+ <component name="com.intellij.coverage.CoverageDataManagerImpl">
138
+ <SUITE FILE_PATH="coverage/detector$demo.coverage" NAME="demo Coverage Results" MODIFIED="1702302380580" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="true" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$" />
139
+ </component>
140
+ </project>
Dockerfile ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ FROM python:bookworm
2
+
3
+ WORKDIR /app
4
+ COPY . /app
5
+ RUN pip install -r requirements.txt
6
+ ENTRYPOINT ["streamlit", "run", "demo.py"]
README.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Object Detector
3
+ emoji: 🚀
4
+ colorFrom: yellow
5
+ colorTo: yellow
6
+ sdk: docker
7
+ pinned: false
8
+ license: apache-2.0
9
+ app_port: 8501
10
+ ---
demo.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import time
3
+ from PIL import Image
4
+ import streamlit as st
5
+
6
+ from model import detect
7
+
8
+
9
+ def main():
10
+ # Header & Page Config.
11
+ st.set_page_config(
12
+ page_title="Parth - Detr",
13
+ layout="centered")
14
+ st.title("Object Detection using DETR:")
15
+
16
+ # This will let you upload PNG, JPG & JPEG File
17
+ buffer = st.file_uploader("Upload your Image here", type=["jpg", "png", "jpeg"])
18
+
19
+ if buffer:
20
+ # Object Detecting
21
+ with st.spinner('Wait for it...'):
22
+ # Slider for changing confidence
23
+ confidence = st.slider('Confidence Threshold', 0, 100, 90)
24
+
25
+ # Calculating time for detection
26
+ t1 = time.time()
27
+ im = Image.open(buffer)
28
+ # im.save("saved_images/image.jpg")
29
+ res_img = detect(im, confidence)
30
+ t2 = time.time()
31
+
32
+ # Displaying the image
33
+ st.image(res_img, use_column_width=True)
34
+
35
+ # Printing Time
36
+ st.write("\n")
37
+ st.write("Time taken: ", t2 - t1, "sec.")
38
+
39
+
40
+ if __name__ == '__main__':
41
+ main()
main.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+
3
+ app = FastAPI()
4
+
5
+
6
+ @app.get("/")
7
+ async def root():
8
+ return {"message": "Hello World"}
9
+
10
+
11
+ @app.get("/hello/{name}")
12
+ async def say_hello(name: str):
13
+ return {"message": f"Hello {name}"}
model.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import cv2
3
+ import torch
4
+ import random
5
+ from PIL import ImageDraw
6
+ import torchvision.transforms as T
7
+
8
+ # COCO Classes
9
+ CLASSES = [
10
+ 'N/A', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
11
+ 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A',
12
+ 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse',
13
+ 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack',
14
+ 'umbrella', 'N/A', 'N/A', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis',
15
+ 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove',
16
+ 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'N/A', 'wine glass',
17
+ 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich',
18
+ 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake',
19
+ 'chair', 'couch', 'potted plant', 'bed', 'N/A', 'dining table', 'N/A',
20
+ 'N/A', 'toilet', 'N/A', 'tv', 'laptop', 'mouse', 'remote', 'keyboard',
21
+ 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A',
22
+ 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier',
23
+ 'toothbrush'
24
+ ]
25
+
26
+ # Standard PyTorch mean-std Input Image Normalization
27
+ transform = T.Compose([
28
+ T.Resize(500),
29
+ T.ToTensor(),
30
+ T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
31
+ ])
32
+
33
+
34
+ # For Output Bounding Box Post-processing
35
+ def box_cxcywh_to_xyxy(x):
36
+ x_c, y_c, w, h = x.unbind(1)
37
+ b = [(x_c - 0.5 * w), (y_c - 0.5 * h),
38
+ (x_c + 0.5 * w), (y_c + 0.5 * h)]
39
+ return torch.stack(b, dim=1)
40
+
41
+
42
+ def rescale_bboxes(out_bbox, size):
43
+ img_w, img_h = size
44
+ b = box_cxcywh_to_xyxy(out_bbox)
45
+ b = b * torch.tensor([img_w, img_h, img_w, img_h], dtype=torch.float32)
46
+ return b
47
+
48
+
49
+ # Pre-processing on Image
50
+ def image_processing(im, model, transform, confidence=0.9):
51
+ # im = Image.open(image_path)
52
+ img = transform(im).unsqueeze(0)
53
+
54
+ outputs = model(img)
55
+ probas = outputs['pred_logits'].softmax(-1)[0, :, :-1]
56
+ keep = probas.max(-1).values > confidence
57
+ bboxes_scaled = rescale_bboxes(outputs['pred_boxes'][0, keep], im.size)
58
+
59
+ return probas[keep], bboxes_scaled
60
+
61
+
62
+ # Helper Functions for Plotting BBoxes
63
+ def plot_one_box(x, img, color=None, label=None, line_thickness=None):
64
+ width, height = img.size
65
+ tl = line_thickness or round(0.002 * (width + height) / 2) + 1 # line/font thickness
66
+ color = color or (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
67
+ c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
68
+ img_draw = ImageDraw.Draw(img)
69
+ img_draw.rectangle((c1[0], c1[1], c2[0], c2[1]), outline=color, width=tl)
70
+ if label:
71
+ tf = max(tl - 1, 1) # font thickness
72
+ t_size = cv2.getTextSize(label, 0, fontScale=tl / 5, thickness=tf)[0]
73
+ c2 = c1[0] + t_size[0], c1[1] + t_size[1] - 3
74
+ img_draw.rectangle((c1, c2), fill=color)
75
+ img_draw.text((c1[0], c1[1] - 2), label, fill=(255, 255, 255))
76
+
77
+
78
+ # Ploting Bounding Box on img
79
+ def add_bboxes(pil_img, prob, bboxes):
80
+ for p, coord in zip(prob, bboxes.tolist()):
81
+ cl = p.argmax()
82
+ text = f'{CLASSES[cl]}: {p[cl]: 0.2f}'
83
+ plot_one_box(x=coord, img=pil_img, label=text)
84
+
85
+ return pil_img
86
+
87
+
88
+ def detect(im, confidence):
89
+ # Load model
90
+ model = torch.hub.load('facebookresearch/detr', 'detr_resnet101', pretrained=True)
91
+ model.eval()
92
+
93
+ scores, boxes = image_processing(im, model, transform, confidence / 100)
94
+ # im = cv2.imread(image_path)
95
+ # im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
96
+ im = add_bboxes(im, scores, boxes)
97
+
98
+ return im
requirements.txt ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ altair==5.2.0
2
+ annotated-types==0.6.0
3
+ anyio==3.7.1
4
+ attrs==23.1.0
5
+ blinker==1.7.0
6
+ cachetools==5.3.2
7
+ certifi==2023.11.17
8
+ charset-normalizer==3.3.2
9
+ click==8.1.7
10
+ exceptiongroup==1.2.0
11
+ fastapi==0.104.1
12
+ filelock==3.13.1
13
+ fsspec==2023.12.1
14
+ gitdb==4.0.11
15
+ GitPython==3.1.40
16
+ h11==0.14.0
17
+ httptools==0.6.1
18
+ idna==3.6
19
+ importlib-metadata==6.11.0
20
+ Jinja2==3.1.2
21
+ jsonschema==4.20.0
22
+ jsonschema-specifications==2023.11.2
23
+ markdown-it-py==3.0.0
24
+ MarkupSafe==2.1.3
25
+ mdurl==0.1.2
26
+ mpmath==1.3.0
27
+ networkx==3.2.1
28
+ numpy==1.26.2
29
+ opencv-python==4.8.1.78
30
+ packaging==23.2
31
+ pandas==2.1.4
32
+ Pillow==10.1.0
33
+ protobuf==4.25.1
34
+ pyarrow==14.0.1
35
+ pydantic==2.5.2
36
+ pydantic_core==2.14.5
37
+ pydeck==0.8.1b0
38
+ Pygments==2.17.2
39
+ python-dateutil==2.8.2
40
+ python-dotenv==1.0.0
41
+ pytz==2023.3.post1
42
+ PyYAML==6.0.1
43
+ referencing==0.32.0
44
+ requests==2.31.0
45
+ rich==13.7.0
46
+ rpds-py==0.13.2
47
+ scipy==1.11.4
48
+ six==1.16.0
49
+ smmap==5.0.1
50
+ sniffio==1.3.0
51
+ starlette==0.27.0
52
+ streamlit==1.29.0
53
+ sympy==1.12
54
+ tenacity==8.2.3
55
+ toml==0.10.2
56
+ toolz==0.12.0
57
+ torch==2.1.0
58
+ torchaudio==2.1.0
59
+ torchvision==0.16.1
60
+ tornado==6.4
61
+ typing_extensions==4.9.0
62
+ tzdata==2023.3
63
+ tzlocal==5.2
64
+ urllib3==2.1.0
65
+ uvicorn==0.24.0.post1
66
+ uvloop==0.19.0
67
+ validators==0.22.0
68
+ watchfiles==0.21.0
69
+ websockets==12.0
70
+ zipp==3.17.0
saved_images/image.jpg ADDED