├── Find Social Distancing Using Deep Learning and OpenCV.ipynb
├── Images
├── image_box1.png
├── image_box2.png
├── image_box3.png
├── image_box4.png
└── peaky_blinders.png
├── LICENSE
├── README.md
├── darknet.py
└── utils.py
/Find Social Distancing Using Deep Learning and OpenCV.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "metadata": {},
7 | "outputs": [],
8 | "source": [
9 | "from darknet import Darknet\n",
10 | "import cv2\n",
11 | "import matplotlib.pyplot as plt\n",
12 | "from utils import *\n",
13 | "import imutils\n",
14 | "from imutils import perspective\n",
15 | "from imutils import contours\n",
16 | "import numpy as np\n",
17 | "from scipy.spatial import distance as dist\n",
18 | "from collections import defaultdict"
19 | ]
20 | },
21 | {
22 | "cell_type": "code",
23 | "execution_count": null,
24 | "metadata": {},
25 | "outputs": [],
26 | "source": [
27 | "# Set the location and name of the cfg file\n",
28 | "cfg_file = '/Users/mayurjain/darknet/cfg/yolov3.cfg'\n",
29 | "\n",
30 | "# Set the location and name of the pre-trained weights file\n",
31 | "weight_file = '/Users/mayurjain/darknet/yolov3.weights'\n",
32 | "\n",
33 | "# Set the location and name of the COCO object classes file\n",
34 | "namesfile = '/Users/mayurjain/darknet/data/coco.names'\n",
35 | "\n",
36 | "# Load the network architecture\n",
37 | "m = Darknet(cfg_file)\n",
38 | "\n",
39 | "# Load the pre-trained weights\n",
40 | "m.load_weights(weight_file)\n",
41 | "\n",
42 | "# Load the COCO object classes\n",
43 | "class_names = load_class_names(namesfile)"
44 | ]
45 | },
46 | {
47 | "cell_type": "code",
48 | "execution_count": null,
49 | "metadata": {},
50 | "outputs": [],
51 | "source": [
52 | "# Set the default figure size\n",
53 | "plt.rcParams['figure.figsize'] = [24.0, 14.0]\n",
54 | "IMAGE = '/Users/mayurjain/Computer VIsion Nanodegree/Social DIstancing Using Deep Learning and OpenCV/peaky_blinders.png'\n",
55 | "# Load the image\n",
56 | "img = cv2.imread(IMAGE)\n",
57 | "\n",
58 | "# Convert the image to RGB\n",
59 | "original_image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n",
60 | "\n",
61 | "# We resize the image to the input width and height of the first layer of the network. \n",
62 | "resized_image = cv2.resize(original_image, (m.width, m.height))\n",
63 | "\n",
64 | "# Display the images\n",
65 | "plt.subplot(121)\n",
66 | "plt.title('Original Image')\n",
67 | "plt.imshow(original_image)\n",
68 | "plt.subplot(122)\n",
69 | "plt.title('Resized Image')\n",
70 | "plt.imshow(resized_image)\n",
71 | "plt.show()"
72 | ]
73 | },
74 | {
75 | "cell_type": "code",
76 | "execution_count": null,
77 | "metadata": {},
78 | "outputs": [],
79 | "source": [
80 | "nms_thresh = 0.6\n",
81 | "iou_thresh = 0.4"
82 | ]
83 | },
84 | {
85 | "cell_type": "code",
86 | "execution_count": null,
87 | "metadata": {},
88 | "outputs": [],
89 | "source": [
90 | "# Set the default figure size\n",
91 | "plt.rcParams['figure.figsize'] = [15.0, 7.0]\n",
92 | "\n",
93 | "# Load the image\n",
94 | "img = cv2.imread(IMAGE)\n",
95 | "\n",
96 | "# Convert the image to RGB\n",
97 | "original_image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n",
98 | "\n",
99 | "# We resize the image to the input width and height of the first layer of the network. \n",
100 | "resized_image = cv2.resize(original_image, (m.width, m.height))\n",
101 | "\n",
102 | "# Set the IOU threshold. Default value is 0.4\n",
103 | "iou_thresh = 0.4\n",
104 | "\n",
105 | "# Set the NMS threshold. Default value is 0.6\n",
106 | "nms_thresh = 0.6\n",
107 | "\n",
108 | "# Detect objects in the image\n",
109 | "boxes = detect_objects(m, resized_image, iou_thresh, nms_thresh)\n",
110 | "\n",
111 | "# Print the objects found and the confidence level\n",
112 | "print_objects(boxes, class_names)\n",
113 | "\n",
114 | "#Plot the image with bounding boxes and corresponding object class labels\n",
115 | "plot_boxes(original_image, boxes, class_names, plot_labels = True)"
116 | ]
117 | },
118 | {
119 | "cell_type": "code",
120 | "execution_count": null,
121 | "metadata": {},
122 | "outputs": [],
123 | "source": [
124 | "def midpoint(ptA, ptB):\n",
125 | " return ((ptA[0] + ptB[0]) * 0.5, (ptA[1] + ptB[1]) * 0.5)"
126 | ]
127 | },
128 | {
129 | "cell_type": "code",
130 | "execution_count": null,
131 | "metadata": {
132 | "scrolled": false
133 | },
134 | "outputs": [],
135 | "source": [
136 | "#Detected_BB = \"/Users/mayurjain/Computer VIsion Nanodegree/Social DIstancing Using Deep Learning and OpenCV/pea.png\"\n",
137 | "image = cv2.imread(IMAGE)\n",
138 | "box_measures = defaultdict(dict)\n",
139 | "width = img.shape[1]\n",
140 | "height = img.shape[0]\n",
141 | "colors = ((0, 0, 255), (240, 0, 159), (0, 165, 255), (255, 255, 0),(255, 0, 255))\n",
142 | "for i, box in enumerate(boxes): \n",
143 | " x1 = int(np.around((box[0] - box[2]/2.0) * width))\n",
144 | " y1 = int(np.around((box[1] - box[3]/2.0) * height))\n",
145 | " x2 = int(np.around((box[0] + box[2]/2.0) * width))\n",
146 | " y2 = int(np.around((box[1] + box[3]/2.0) * height))\n",
147 | "\n",
148 | " if x2-x1 > 50:\n",
149 | " box_measures[\"box\"+str(i)] = {\"top_left\": (x1, y1), \"top_right\": (x2, y1),\"bottom_right\": (x2, y2),\n",
150 | " \"bottom_left\": (x1, y2), \"center\": (int((x1+x2)/2),int((y1+y2)/2))}"
151 | ]
152 | },
153 | {
154 | "cell_type": "code",
155 | "execution_count": null,
156 | "metadata": {},
157 | "outputs": [],
158 | "source": [
159 | "center = []\n",
160 | "count = 0\n",
161 | "box_array = np.zeros((4,2),dtype=int)\n",
162 | "for key,v in box_measures.items():\n",
163 | " for i, (k,v) in enumerate(box_measures[key].items()):\n",
164 | " if i ==4:\n",
165 | " center.append((np.average(box_array[:, 0]), np.average(box_array[:, 1])))\n",
166 | " break\n",
167 | " box_array[i,count], box_array[i, count+1] = v[0],v[1] "
168 | ]
169 | },
170 | {
171 | "cell_type": "code",
172 | "execution_count": null,
173 | "metadata": {},
174 | "outputs": [],
175 | "source": [
176 | "colors = ((0, 0, 255), (240, 0, 159), (0, 165, 255), (255, 255, 0),(255, 0, 255))\n",
177 | "box0_array = np.zeros((4,2),dtype=int)\n",
178 | "count = 0\n",
179 | "refObj = None\n",
180 | "for key,v in box_measures.items():\n",
181 | " for i, (k,v) in enumerate(box_measures[key].items()):\n",
182 | " if i ==4:\n",
183 | " break\n",
184 | " box0_array[i,count], box0_array[i, count+1] = v[0],v[1]\n",
185 | " \n",
186 | " cX = np.average(box0_array[:, 0])\n",
187 | " cY = np.average(box0_array[:, 1])\n",
188 | " if refObj is None:\n",
189 | " # unpack the ordered bounding box, then compute the\n",
190 | " # midpoint between the top-left and top-right points,\n",
191 | " # followed by the midpoint between the top-right and\n",
192 | " # bottom-right\n",
193 | " (tl, tr, br, bl) = box0_array\n",
194 | " (tlblX, tlblY) = midpoint(tl, bl)\n",
195 | " (trbrX, trbrY) = midpoint(tr, br)\n",
196 | " # compute the Euclidean distance between the midpoints,\n",
197 | " # then construct the reference object\n",
198 | " D = dist.euclidean((tlblX, tlblY), (trbrX, trbrY))\n",
199 | " refObj = (box0_array, (cX, cY), D / 0.70)\n",
200 | " continue\n",
201 | " # draw the contours on the image\n",
202 | " orig = image.copy()\n",
203 | " \n",
204 | " # stack the reference coordinates and the object coordinates\n",
205 | " # to include the object center\n",
206 | " refCoords = np.vstack([refObj[0], refObj[1]])\n",
207 | " objCoords = np.vstack([box0_array, (cX, cY)])\n",
208 | " cv2.rectangle(orig, (refObj[0][0][0], refObj[0][0][1]),\n",
209 | " (refObj[0][2][0], refObj[0][2][1]), (0, 255, 0), 2) \n",
210 | " cv2.circle(orig, (int(refObj[1][0]), int(refObj[1][1])), 5, colors[0], -1)\n",
211 | " cv2.circle(orig, (int(cX), int(cY)), 5, colors[0], -1)\n",
212 | " cv2.line(orig, (int(refObj[1][0]), int(refObj[1][1])), (int(cX), int(cY)), colors[0], 2)\n",
213 | "\n",
214 | " \n",
215 | " D = dist.euclidean((refObj[1][0], refObj[1][1]), (cX, cY)) / refObj[2]\n",
216 | " (mX, mY) = midpoint((refObj[1][0], refObj[1][1]), (cX, cY))\n",
217 | " \n",
218 | " if D > 1.8: #Success\n",
219 | " cv2.putText(orig, \"{:.1f}m\".format(D), (int(mX), int(mY - 15)),\n",
220 | " cv2.FONT_HERSHEY_SIMPLEX, 0.55, colors[1], 2)\n",
221 | " \n",
222 | " cv2.putText(orig, \"Social Distance Maintained\", (int(mX), int(mY + 15)),\n",
223 | " cv2.FONT_HERSHEY_SIMPLEX, 0.55, colors[1], 2)\n",
224 | " else:\n",
225 | " cv2.putText(orig, \"{:.1f}m\".format(D), (int(mX), int(mY - 15)),\n",
226 | " cv2.FONT_HERSHEY_SIMPLEX, 0.55, colors[0], 2)\n",
227 | " \n",
228 | " cv2.putText(orig, \"No Social Distance Maintained\", (int(mX), int(mY + 15)),\n",
229 | " cv2.FONT_HERSHEY_SIMPLEX, 0.55, colors[0], 2)\n",
230 | " \n",
231 | " # show the output image\n",
232 | " cv2.rectangle(orig, box_measures[key][\"top_left\"], box_measures[key][\"bottom_right\"],(255,0,0), 2)\n",
233 | " cv2.imshow(\"Image\", orig)\n",
234 | " cv2.imwrite(\"image_\"+key+\".png\", orig)\n",
235 | " cv2.waitKey(0)"
236 | ]
237 | },
238 | {
239 | "cell_type": "code",
240 | "execution_count": null,
241 | "metadata": {},
242 | "outputs": [],
243 | "source": [
244 | "import glob\n",
245 | "import re\n",
246 | " \n",
247 | "img_array = []\n",
248 | "each_image_duration = 30\n",
249 | "filenames = [ filename for filename in glob.glob(\"/Users/mayurjain/Computer Vision Nanodegree/Social_Distancing/images/*.png\")]\n",
250 | "filenames.sort(key=lambda f: int(re.sub('\\D', '', f)))\n",
251 | "\n",
252 | "for filename in filenames:\n",
253 | " img = cv2.imread(filename)\n",
254 | " height, width, layers = img.shape\n",
255 | " size = (width,height)\n",
256 | " img_array.append(img)\n",
257 | " \n",
258 | " \n",
259 | "out = cv2.VideoWriter('Social_Distancing.mp4',cv2.VideoWriter_fourcc(*'DIVX'), 15, size)\n",
260 | " \n",
261 | "for i in range(len(img_array)):\n",
262 | " for _ in range(each_image_duration):\n",
263 | " out.write(img_array[i])\n",
264 | "out.release()"
265 | ]
266 | },
267 | {
268 | "cell_type": "code",
269 | "execution_count": null,
270 | "metadata": {},
271 | "outputs": [],
272 | "source": []
273 | }
274 | ],
275 | "metadata": {
276 | "kernelspec": {
277 | "display_name": "Python 3",
278 | "language": "python",
279 | "name": "python3"
280 | },
281 | "language_info": {
282 | "codemirror_mode": {
283 | "name": "ipython",
284 | "version": 3
285 | },
286 | "file_extension": ".py",
287 | "mimetype": "text/x-python",
288 | "name": "python",
289 | "nbconvert_exporter": "python",
290 | "pygments_lexer": "ipython3",
291 | "version": "3.7.3"
292 | }
293 | },
294 | "nbformat": 4,
295 | "nbformat_minor": 2
296 | }
297 |
--------------------------------------------------------------------------------
/Images/image_box1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mayurji/Social-DIstancing-Using-Deep-Learning-and-OpenCV/2c24a220947d1bee6f28e83958e7f3e95d436f84/Images/image_box1.png
--------------------------------------------------------------------------------
/Images/image_box2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mayurji/Social-DIstancing-Using-Deep-Learning-and-OpenCV/2c24a220947d1bee6f28e83958e7f3e95d436f84/Images/image_box2.png
--------------------------------------------------------------------------------
/Images/image_box3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mayurji/Social-DIstancing-Using-Deep-Learning-and-OpenCV/2c24a220947d1bee6f28e83958e7f3e95d436f84/Images/image_box3.png
--------------------------------------------------------------------------------
/Images/image_box4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mayurji/Social-DIstancing-Using-Deep-Learning-and-OpenCV/2c24a220947d1bee6f28e83958e7f3e95d436f84/Images/image_box4.png
--------------------------------------------------------------------------------
/Images/peaky_blinders.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Mayurji/Social-DIstancing-Using-Deep-Learning-and-OpenCV/2c24a220947d1bee6f28e83958e7f3e95d436f84/Images/peaky_blinders.png
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Social Distancing Using Deep Learning and OpenCV
2 |
3 | ## Objective
4 | Today's unfortunate circumstances due to COVID-19, keeping distance among people is crucial.
5 | The goal is to detect people using Deep Learning and find the distance between people to check
6 | whether a norm social distance of 6feet or 1.8m is maintained by people.
7 |
8 | 
9 |
10 | ## Tool and Libraries
11 |
12 | * Python
13 | * OpenCV
14 | * YoloV3
15 |
16 | ## Description
17 |
18 | * Step 1: Find the number of people in the frame/Image.
19 | * Step 2: Creating Bounding Box over the people identified using YOLO.
20 | * Step 3: A width threshold is set for object among which the distance is measured i.e. the width of the people. I am setting width as 27inch or 0.70 meter. Try other values if required.
21 | * Step 4: Mapping the pixels to metric (meter or inches).
22 | * Step 5: Find the distance between, the center point of one person to another person in meters.
23 |
24 | ## Result
25 |
26 | 
27 |
--------------------------------------------------------------------------------
/darknet.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import numpy as np
4 |
5 |
6 | class YoloLayer(nn.Module):
7 | def __init__(self, anchor_mask=[], num_classes=0, anchors=[], num_anchors=1):
8 | super(YoloLayer, self).__init__()
9 | self.anchor_mask = anchor_mask
10 | self.num_classes = num_classes
11 | self.anchors = anchors
12 | self.num_anchors = num_anchors
13 | self.anchor_step = len(anchors)/num_anchors
14 | self.coord_scale = 1
15 | self.noobject_scale = 1
16 | self.object_scale = 5
17 | self.class_scale = 1
18 | self.thresh = 0.6
19 | self.stride = 32
20 | self.seen = 0
21 |
22 | def forward(self, output, nms_thresh):
23 | self.thresh = nms_thresh
24 | masked_anchors = []
25 |
26 | for m in self.anchor_mask:
27 | masked_anchors += self.anchors[m *
28 | self.anchor_step:(m+1)*self.anchor_step]
29 |
30 | masked_anchors = [anchor/self.stride for anchor in masked_anchors]
31 | boxes = get_region_boxes(
32 | output.data, self.thresh, self.num_classes, masked_anchors, len(self.anchor_mask))
33 |
34 | return boxes
35 |
36 |
37 | class Upsample(nn.Module):
38 | def __init__(self, stride=2):
39 | super(Upsample, self).__init__()
40 | self.stride = stride
41 |
42 | def forward(self, x):
43 | stride = self.stride
44 | assert(x.data.dim() == 4)
45 | B = x.data.size(0)
46 | C = x.data.size(1)
47 | H = x.data.size(2)
48 | W = x.data.size(3)
49 | ws = stride
50 | hs = stride
51 | x = x.view(B, C, H, 1, W, 1).expand(B, C, H, stride, W,
52 | stride).contiguous().view(B, C, H*stride, W*stride)
53 | return x
54 |
55 |
56 | #for route and shortcut
57 | class EmptyModule(nn.Module):
58 | def __init__(self):
59 | super(EmptyModule, self).__init__()
60 |
61 | def forward(self, x):
62 | return x
63 |
64 | # support route shortcut
65 |
66 |
67 | class Darknet(nn.Module):
68 | def __init__(self, cfgfile):
69 | super(Darknet, self).__init__()
70 | self.blocks = parse_cfg(cfgfile)
71 | self.models = self.create_network(self.blocks) # merge conv, bn,leaky
72 | self.loss = self.models[len(self.models)-1]
73 |
74 | self.width = int(self.blocks[0]['width'])
75 | self.height = int(self.blocks[0]['height'])
76 |
77 | self.header = torch.IntTensor([0, 0, 0, 0])
78 | self.seen = 0
79 |
80 | def forward(self, x, nms_thresh):
81 | ind = -2
82 | self.loss = None
83 | outputs = dict()
84 | out_boxes = []
85 |
86 | for block in self.blocks:
87 | ind = ind + 1
88 | if block['type'] == 'net':
89 | continue
90 | elif block['type'] in ['convolutional', 'upsample']:
91 | x = self.models[ind](x)
92 | outputs[ind] = x
93 | elif block['type'] == 'route':
94 | layers = block['layers'].split(',')
95 | layers = [int(i) if int(i) > 0 else int(i)+ind for i in layers]
96 | if len(layers) == 1:
97 | x = outputs[layers[0]]
98 | outputs[ind] = x
99 | elif len(layers) == 2:
100 | x1 = outputs[layers[0]]
101 | x2 = outputs[layers[1]]
102 | x = torch.cat((x1, x2), 1)
103 | outputs[ind] = x
104 | elif block['type'] == 'shortcut':
105 | from_layer = int(block['from'])
106 | activation = block['activation']
107 | from_layer = from_layer if from_layer > 0 else from_layer + ind
108 | x1 = outputs[from_layer]
109 | x2 = outputs[ind-1]
110 | x = x1 + x2
111 | outputs[ind] = x
112 | elif block['type'] == 'yolo':
113 | boxes = self.models[ind](x, nms_thresh)
114 | out_boxes.append(boxes)
115 | else:
116 | print('unknown type %s' % (block['type']))
117 |
118 | return out_boxes
119 |
120 | def print_network(self):
121 | print_cfg(self.blocks)
122 |
123 | def create_network(self, blocks):
124 | models = nn.ModuleList()
125 |
126 | prev_filters = 3
127 | out_filters = []
128 | prev_stride = 1
129 | out_strides = []
130 | conv_id = 0
131 | for block in blocks:
132 | if block['type'] == 'net':
133 | prev_filters = int(block['channels'])
134 | continue
135 | elif block['type'] == 'convolutional':
136 | conv_id = conv_id + 1
137 | batch_normalize = int(block['batch_normalize'])
138 | filters = int(block['filters'])
139 | kernel_size = int(block['size'])
140 | stride = int(block['stride'])
141 | is_pad = int(block['pad'])
142 | pad = (kernel_size-1)//2 if is_pad else 0
143 | activation = block['activation']
144 | model = nn.Sequential()
145 | if batch_normalize:
146 | model.add_module('conv{0}'.format(conv_id), nn.Conv2d(
147 | prev_filters, filters, kernel_size, stride, pad, bias=False))
148 | model.add_module('bn{0}'.format(
149 | conv_id), nn.BatchNorm2d(filters))
150 | else:
151 | model.add_module('conv{0}'.format(conv_id), nn.Conv2d(
152 | prev_filters, filters, kernel_size, stride, pad))
153 | if activation == 'leaky':
154 | model.add_module('leaky{0}'.format(
155 | conv_id), nn.LeakyReLU(0.1, inplace=True))
156 | prev_filters = filters
157 | out_filters.append(prev_filters)
158 | prev_stride = stride * prev_stride
159 | out_strides.append(prev_stride)
160 | models.append(model)
161 | elif block['type'] == 'upsample':
162 | stride = int(block['stride'])
163 | out_filters.append(prev_filters)
164 | prev_stride = prev_stride // stride
165 | out_strides.append(prev_stride)
166 | models.append(Upsample(stride))
167 | elif block['type'] == 'route':
168 | layers = block['layers'].split(',')
169 | ind = len(models)
170 | layers = [int(i) if int(i) > 0 else int(i)+ind for i in layers]
171 | if len(layers) == 1:
172 | prev_filters = out_filters[layers[0]]
173 | prev_stride = out_strides[layers[0]]
174 | elif len(layers) == 2:
175 | assert(layers[0] == ind - 1)
176 | prev_filters = out_filters[layers[0]
177 | ] + out_filters[layers[1]]
178 | prev_stride = out_strides[layers[0]]
179 | out_filters.append(prev_filters)
180 | out_strides.append(prev_stride)
181 | models.append(EmptyModule())
182 | elif block['type'] == 'shortcut':
183 | ind = len(models)
184 | prev_filters = out_filters[ind-1]
185 | out_filters.append(prev_filters)
186 | prev_stride = out_strides[ind-1]
187 | out_strides.append(prev_stride)
188 | models.append(EmptyModule())
189 | elif block['type'] == 'yolo':
190 | yolo_layer = YoloLayer()
191 | anchors = block['anchors'].split(',')
192 | anchor_mask = block['mask'].split(',')
193 | yolo_layer.anchor_mask = [int(i) for i in anchor_mask]
194 | yolo_layer.anchors = [float(i) for i in anchors]
195 | yolo_layer.num_classes = int(block['classes'])
196 | yolo_layer.num_anchors = int(block['num'])
197 | yolo_layer.anchor_step = len(
198 | yolo_layer.anchors)//yolo_layer.num_anchors
199 | yolo_layer.stride = prev_stride
200 | out_filters.append(prev_filters)
201 | out_strides.append(prev_stride)
202 | models.append(yolo_layer)
203 | else:
204 | print('unknown type %s' % (block['type']))
205 |
206 | return models
207 |
208 | def load_weights(self, weightfile):
209 | print()
210 | fp = open(weightfile, 'rb')
211 | header = np.fromfile(fp, count=5, dtype=np.int32)
212 | self.header = torch.from_numpy(header)
213 | self.seen = self.header[3]
214 | buf = np.fromfile(fp, dtype=np.float32)
215 | fp.close()
216 |
217 | start = 0
218 | ind = -2
219 | counter = 3
220 | for block in self.blocks:
221 | if start >= buf.size:
222 | break
223 | ind = ind + 1
224 | if block['type'] == 'net':
225 | continue
226 | elif block['type'] == 'convolutional':
227 | model = self.models[ind]
228 | batch_normalize = int(block['batch_normalize'])
229 | if batch_normalize:
230 | start = load_conv_bn(buf, start, model[0], model[1])
231 | else:
232 | start = load_conv(buf, start, model[0])
233 | elif block['type'] == 'upsample':
234 | pass
235 | elif block['type'] == 'route':
236 | pass
237 | elif block['type'] == 'shortcut':
238 | pass
239 | elif block['type'] == 'yolo':
240 | pass
241 | else:
242 | print('unknown type %s' % (block['type']))
243 |
244 | percent_comp = (counter / len(self.blocks)) * 100
245 |
246 | print('Loading weights. Please Wait...{:.2f}% Complete'.format(
247 | percent_comp), end='\r', flush=True)
248 |
249 | counter += 1
250 |
251 |
252 | def convert2cpu(gpu_matrix):
253 | return torch.FloatTensor(gpu_matrix.size()).copy_(gpu_matrix)
254 |
255 |
256 | def convert2cpu_long(gpu_matrix):
257 | return torch.LongTensor(gpu_matrix.size()).copy_(gpu_matrix)
258 |
259 |
260 | def get_region_boxes(output, conf_thresh, num_classes, anchors, num_anchors, only_objectness=1, validation=False):
261 | anchor_step = len(anchors)//num_anchors
262 | if output.dim() == 3:
263 | output = output.unsqueeze(0)
264 | batch = output.size(0)
265 | assert(output.size(1) == (5+num_classes)*num_anchors)
266 | h = output.size(2)
267 | w = output.size(3)
268 |
269 | all_boxes = []
270 | output = output.view(batch*num_anchors, 5+num_classes, h*w).transpose(0,
271 | 1).contiguous().view(5+num_classes, batch*num_anchors*h*w)
272 |
273 | grid_x = torch.linspace(0, w-1, w).repeat(h, 1).repeat(batch*num_anchors,
274 | 1, 1).view(batch*num_anchors*h*w).type_as(output) # cuda()
275 | grid_y = torch.linspace(0, h-1, h).repeat(w, 1).t().repeat(
276 | batch*num_anchors, 1, 1).view(batch*num_anchors*h*w).type_as(output) # cuda()
277 | xs = torch.sigmoid(output[0]) + grid_x
278 | ys = torch.sigmoid(output[1]) + grid_y
279 |
280 | anchor_w = torch.Tensor(anchors).view(
281 | num_anchors, anchor_step).index_select(1, torch.LongTensor([0]))
282 | anchor_h = torch.Tensor(anchors).view(
283 | num_anchors, anchor_step).index_select(1, torch.LongTensor([1]))
284 | anchor_w = anchor_w.repeat(batch, 1).repeat(
285 | 1, 1, h*w).view(batch*num_anchors*h*w).type_as(output) # cuda()
286 | anchor_h = anchor_h.repeat(batch, 1).repeat(
287 | 1, 1, h*w).view(batch*num_anchors*h*w).type_as(output) # cuda()
288 | ws = torch.exp(output[2]) * anchor_w
289 | hs = torch.exp(output[3]) * anchor_h
290 |
291 | det_confs = torch.sigmoid(output[4])
292 | cls_confs = torch.nn.Softmax(dim=1)(
293 | output[5:5+num_classes].transpose(0, 1)).detach()
294 | cls_max_confs, cls_max_ids = torch.max(cls_confs, 1)
295 | cls_max_confs = cls_max_confs.view(-1)
296 | cls_max_ids = cls_max_ids.view(-1)
297 |
298 | sz_hw = h*w
299 | sz_hwa = sz_hw*num_anchors
300 | det_confs = convert2cpu(det_confs)
301 | cls_max_confs = convert2cpu(cls_max_confs)
302 | cls_max_ids = convert2cpu_long(cls_max_ids)
303 | xs = convert2cpu(xs)
304 | ys = convert2cpu(ys)
305 | ws = convert2cpu(ws)
306 | hs = convert2cpu(hs)
307 | if validation:
308 | cls_confs = convert2cpu(cls_confs.view(-1, num_classes))
309 |
310 | for b in range(batch):
311 | boxes = []
312 | for cy in range(h):
313 | for cx in range(w):
314 | for i in range(num_anchors):
315 | ind = b*sz_hwa + i*sz_hw + cy*w + cx
316 | det_conf = det_confs[ind]
317 | if only_objectness:
318 | conf = det_confs[ind]
319 | else:
320 | conf = det_confs[ind] * cls_max_confs[ind]
321 |
322 | if conf > conf_thresh:
323 | bcx = xs[ind]
324 | bcy = ys[ind]
325 | bw = ws[ind]
326 | bh = hs[ind]
327 | cls_max_conf = cls_max_confs[ind]
328 | cls_max_id = cls_max_ids[ind]
329 | box = [bcx/w, bcy/h, bw/w, bh/h,
330 | det_conf, cls_max_conf, cls_max_id]
331 | if (not only_objectness) and validation:
332 | for c in range(num_classes):
333 | tmp_conf = cls_confs[ind][c]
334 | if c != cls_max_id and det_confs[ind]*tmp_conf > conf_thresh:
335 | box.append(tmp_conf)
336 | box.append(c)
337 | boxes.append(box)
338 | all_boxes.append(boxes)
339 |
340 | return all_boxes
341 |
342 |
343 | def parse_cfg(cfgfile):
344 | blocks = []
345 | fp = open(cfgfile, 'r')
346 | block = None
347 | line = fp.readline()
348 | while line != '':
349 | line = line.rstrip()
350 | if line == '' or line[0] == '#':
351 | line = fp.readline()
352 | continue
353 | elif line[0] == '[':
354 | if block:
355 | blocks.append(block)
356 | block = dict()
357 | block['type'] = line.lstrip('[').rstrip(']')
358 | # set default value
359 | if block['type'] == 'convolutional':
360 | block['batch_normalize'] = 0
361 | else:
362 | key, value = line.split('=')
363 | key = key.strip()
364 | if key == 'type':
365 | key = '_type'
366 | value = value.strip()
367 | block[key] = value
368 | line = fp.readline()
369 |
370 | if block:
371 | blocks.append(block)
372 | fp.close()
373 | return blocks
374 |
375 |
376 | def print_cfg(blocks):
377 | print('layer filters size input output')
378 | prev_width = 416
379 | prev_height = 416
380 | prev_filters = 3
381 | out_filters = []
382 | out_widths = []
383 | out_heights = []
384 | ind = -2
385 | for block in blocks:
386 | ind = ind + 1
387 | if block['type'] == 'net':
388 | prev_width = int(block['width'])
389 | prev_height = int(block['height'])
390 | continue
391 | elif block['type'] == 'convolutional':
392 | filters = int(block['filters'])
393 | kernel_size = int(block['size'])
394 | stride = int(block['stride'])
395 | is_pad = int(block['pad'])
396 | pad = (kernel_size-1)//2 if is_pad else 0
397 | width = (prev_width + 2*pad - kernel_size)//stride + 1
398 | height = (prev_height + 2*pad - kernel_size)//stride + 1
399 | print('%5d %-6s %4d %d x %d / %d %3d x %3d x%4d -> %3d x %3d x%4d' % (ind, 'conv', filters,
400 | kernel_size, kernel_size, stride, prev_width, prev_height, prev_filters, width, height, filters))
401 | prev_width = width
402 | prev_height = height
403 | prev_filters = filters
404 | out_widths.append(prev_width)
405 | out_heights.append(prev_height)
406 | out_filters.append(prev_filters)
407 | elif block['type'] == 'upsample':
408 | stride = int(block['stride'])
409 | filters = prev_filters
410 | width = prev_width*stride
411 | height = prev_height*stride
412 | print('%5d %-6s * %d %3d x %3d x%4d -> %3d x %3d x%4d' %
413 | (ind, 'upsample', stride, prev_width, prev_height, prev_filters, width, height, filters))
414 | prev_width = width
415 | prev_height = height
416 | prev_filters = filters
417 | out_widths.append(prev_width)
418 | out_heights.append(prev_height)
419 | out_filters.append(prev_filters)
420 | elif block['type'] == 'route':
421 | layers = block['layers'].split(',')
422 | layers = [int(i) if int(i) > 0 else int(i)+ind for i in layers]
423 | if len(layers) == 1:
424 | print('%5d %-6s %d' % (ind, 'route', layers[0]))
425 | prev_width = out_widths[layers[0]]
426 | prev_height = out_heights[layers[0]]
427 | prev_filters = out_filters[layers[0]]
428 | elif len(layers) == 2:
429 | print('%5d %-6s %d %d' % (ind, 'route', layers[0], layers[1]))
430 | prev_width = out_widths[layers[0]]
431 | prev_height = out_heights[layers[0]]
432 | assert(prev_width == out_widths[layers[1]])
433 | assert(prev_height == out_heights[layers[1]])
434 | prev_filters = out_filters[layers[0]] + out_filters[layers[1]]
435 | out_widths.append(prev_width)
436 | out_heights.append(prev_height)
437 | out_filters.append(prev_filters)
438 | elif block['type'] in ['region', 'yolo']:
439 | print('%5d %-6s' % (ind, 'detection'))
440 | out_widths.append(prev_width)
441 | out_heights.append(prev_height)
442 | out_filters.append(prev_filters)
443 | elif block['type'] == 'shortcut':
444 | from_id = int(block['from'])
445 | from_id = from_id if from_id > 0 else from_id+ind
446 | print('%5d %-6s %d' % (ind, 'shortcut', from_id))
447 | prev_width = out_widths[from_id]
448 | prev_height = out_heights[from_id]
449 | prev_filters = out_filters[from_id]
450 | out_widths.append(prev_width)
451 | out_heights.append(prev_height)
452 | out_filters.append(prev_filters)
453 | else:
454 | print('unknown type %s' % (block['type']))
455 |
456 |
457 | def load_conv(buf, start, conv_model):
458 | num_w = conv_model.weight.numel()
459 | num_b = conv_model.bias.numel()
460 | conv_model.bias.data.copy_(torch.from_numpy(buf[start:start+num_b]))
461 | start = start + num_b
462 | conv_model.weight.data.copy_(torch.from_numpy(
463 | buf[start:start+num_w]).view_as(conv_model.weight.data))
464 | start = start + num_w
465 | return start
466 |
467 |
468 | def load_conv_bn(buf, start, conv_model, bn_model):
469 | num_w = conv_model.weight.numel()
470 | num_b = bn_model.bias.numel()
471 | bn_model.bias.data.copy_(torch.from_numpy(buf[start:start+num_b]))
472 | start = start + num_b
473 | bn_model.weight.data.copy_(torch.from_numpy(buf[start:start+num_b]))
474 | start = start + num_b
475 | bn_model.running_mean.copy_(torch.from_numpy(buf[start:start+num_b]))
476 | start = start + num_b
477 | bn_model.running_var.copy_(torch.from_numpy(buf[start:start+num_b]))
478 | start = start + num_b
479 | conv_model.weight.data.copy_(torch.from_numpy(
480 | buf[start:start+num_w]).view_as(conv_model.weight.data))
481 | start = start + num_w
482 | return start
483 |
--------------------------------------------------------------------------------
/utils.py:
--------------------------------------------------------------------------------
1 | import time
2 | import torch
3 | import numpy as np
4 | import matplotlib.pyplot as plt
5 | import matplotlib.patches as patches
6 | import cv2
7 |
8 |
9 | def boxes_iou(box1, box2):
10 |
11 | # Get the Width and Height of each bounding box
12 | width_box1 = box1[2]
13 | height_box1 = box1[3]
14 | width_box2 = box2[2]
15 | height_box2 = box2[3]
16 |
17 | # Calculate the area of the each bounding box
18 | area_box1 = width_box1 * height_box1
19 | area_box2 = width_box2 * height_box2
20 |
21 | # Find the vertical edges of the union of the two bounding boxes
22 | mx = min(box1[0] - width_box1/2.0, box2[0] - width_box2/2.0)
23 | Mx = max(box1[0] + width_box1/2.0, box2[0] + width_box2/2.0)
24 |
25 | # Calculate the width of the union of the two bounding boxes
26 | union_width = Mx - mx
27 |
28 | # Find the horizontal edges of the union of the two bounding boxes
29 | my = min(box1[1] - height_box1/2.0, box2[1] - height_box2/2.0)
30 | My = max(box1[1] + height_box1/2.0, box2[1] + height_box2/2.0)
31 |
32 | # Calculate the height of the union of the two bounding boxes
33 | union_height = My - my
34 |
35 | # Calculate the width and height of the area of intersection of the two bounding boxes
36 | intersection_width = width_box1 + width_box2 - union_width
37 | intersection_height = height_box1 + height_box2 - union_height
38 |
39 | # If the the boxes don't overlap then their IOU is zero
40 | if intersection_width <= 0 or intersection_height <= 0:
41 | return 0.0
42 |
43 | # Calculate the area of intersection of the two bounding boxes
44 | intersection_area = intersection_width * intersection_height
45 |
46 | # Calculate the area of the union of the two bounding boxes
47 | union_area = area_box1 + area_box2 - intersection_area
48 |
49 | # Calculate the IOU
50 | iou = intersection_area/union_area
51 |
52 | return iou
53 |
54 |
55 | def nms(boxes, iou_thresh):
56 |
57 | # If there are no bounding boxes do nothing
58 | if len(boxes) == 0:
59 | return boxes
60 |
61 | # Create a PyTorch Tensor to keep track of the detection confidence
62 | # of each predicted bounding box
63 | det_confs = torch.zeros(len(boxes))
64 |
65 | # Get the detection confidence of each predicted bounding box
66 | for i in range(len(boxes)):
67 | det_confs[i] = boxes[i][4]
68 |
69 | # Sort the indices of the bounding boxes by detection confidence value in descending order.
70 | # We ignore the first returned element since we are only interested in the sorted indices
71 | _,sortIds = torch.sort(det_confs, descending = True)
72 |
73 | # Create an empty list to hold the best bounding boxes after
74 | # Non-Maximal Suppression (NMS) is performed
75 | best_boxes = []
76 |
77 | # Perform Non-Maximal Suppression
78 | for i in range(len(boxes)):
79 |
80 | # Get the bounding box with the highest detection confidence first
81 | box_i = boxes[sortIds[i]]
82 |
83 | # Check that the detection confidence is not zero
84 | if box_i[4] > 0:
85 |
86 | # Save the bounding box
87 | best_boxes.append(box_i)
88 |
89 | # Go through the rest of the bounding boxes in the list and calculate their IOU with
90 | # respect to the previous selected box_i.
91 | for j in range(i + 1, len(boxes)):
92 | box_j = boxes[sortIds[j]]
93 |
94 | # If the IOU of box_i and box_j is higher than the given IOU threshold set
95 | # box_j's detection confidence to zero.
96 | if boxes_iou(box_i, box_j) > iou_thresh:
97 | box_j[4] = 0
98 |
99 | return best_boxes
100 |
101 |
102 | def detect_objects(model, img, iou_thresh, nms_thresh):
103 |
104 | # Start the time. This is done to calculate how long the detection takes.
105 | start = time.time()
106 |
107 | # Set the model to evaluation mode.
108 | model.eval()
109 |
110 | # Convert the image from a NumPy ndarray to a PyTorch Tensor of the correct shape.
111 | # The image is transposed, then converted to a FloatTensor of dtype float32, then
112 | # Normalized to values between 0 and 1, and finally unsqueezed to have the correct
113 | # shape of 1 x 3 x 416 x 416
114 | img = torch.from_numpy(img.transpose(2,0,1)).float().div(255.0).unsqueeze(0)
115 |
116 | # Feed the image to the neural network with the corresponding NMS threshold.
117 | # The first step in NMS is to remove all bounding boxes that have a very low
118 | # probability of detection. All predicted bounding boxes with a value less than
119 | # the given NMS threshold will be removed.
120 | list_boxes = model(img, nms_thresh)
121 | #print(list_boxes)
122 |
123 | # Make a new list with all the bounding boxes returned by the neural network
124 | boxes = list_boxes[0][0] + list_boxes[1][0] + list_boxes[2][0]
125 |
126 | # Perform the second step of NMS on the bounding boxes returned by the neural network.
127 | # In this step, we only keep the best bounding boxes by eliminating all the bounding boxes
128 | # whose IOU value is higher than the given IOU threshold
129 | boxes = nms(boxes, iou_thresh)
130 | #print(boxes)
131 | # Stop the time.
132 | finish = time.time()
133 |
134 | # Print the time it took to detect objects
135 | print('\n\nIt took {:.3f}'.format(finish - start), 'seconds to detect the objects in the image.\n')
136 |
137 | # Print the number of objects detected
138 | print('Number of Objects Detected:', len(boxes), '\n')
139 |
140 | return boxes
141 |
142 |
143 | def load_class_names(namesfile):
144 |
145 | # Create an empty list to hold the object classes
146 | class_names = []
147 |
148 | # Open the file containing the COCO object classes in read-only mode
149 | with open(namesfile, 'r') as fp:
150 |
151 | # The coco.names file contains only one object class per line.
152 | # Read the file line by line and save all the lines in a list.
153 | lines = fp.readlines()
154 |
155 | # Get the object class names
156 | for line in lines:
157 |
158 | # Make a copy of each line with any trailing whitespace removed
159 | line = line.rstrip()
160 |
161 | # Save the object class name into class_names
162 | class_names.append(line)
163 |
164 | return class_names
165 |
166 |
167 | def print_objects(boxes, class_names):
168 | print('Objects Found and Confidence Level:\n')
169 | for i in range(len(boxes)):
170 | box = boxes[i]
171 | if len(box) >= 7 and class_names:
172 | cls_conf = box[5]
173 | cls_id = box[6]
174 | if class_names[cls_id] == 'person':
175 | print('%i. %s: %f' % (i + 1, class_names[cls_id], cls_conf))
176 |
177 |
178 | def plot_boxes(img, boxes, class_names, plot_labels, color = None):
179 |
180 | # Define a tensor used to set the colors of the bounding boxes
181 | colors = torch.FloatTensor([[1,0,1],[0,0,1],[0,1,1],[0,1,0],[1,1,0],[1,0,0]])
182 |
183 | # Define a function to set the colors of the bounding boxes
184 | def get_color(c, x, max_val):
185 | ratio = float(x) / max_val * 5
186 | i = int(np.floor(ratio))
187 | j = int(np.ceil(ratio))
188 |
189 | ratio = ratio - i
190 | r = (1 - ratio) * colors[i][c] + ratio * colors[j][c]
191 |
192 | return int(r * 255)
193 |
194 | # Get the width and height of the image
195 | width = img.shape[1]
196 | height = img.shape[0]
197 |
198 | # Create a figure and plot the image
199 | fig, a = plt.subplots(1,1)
200 | a.imshow(img)
201 |
202 | # Plot the bounding boxes and corresponding labels on top of the image
203 | for i in range(len(boxes)):
204 |
205 | # Get the ith bounding box
206 | box = boxes[i]
207 |
208 | # Get the (x,y) pixel coordinates of the lower-left and lower-right corners
209 | # of the bounding box relative to the size of the image.
210 | x1 = int(np.around((box[0] - box[2]/2.0) * width))
211 | y1 = int(np.around((box[1] - box[3]/2.0) * height))
212 | x2 = int(np.around((box[0] + box[2]/2.0) * width))
213 | y2 = int(np.around((box[1] + box[3]/2.0) * height))
214 | #print("x1, y1",str(x1)+","+str(y1))
215 | #print("x2, y2",str(x2)+","+str(y2))
216 | # Set the default rgb value to red
217 | rgb = (1, 0, 0)
218 | cls_id = box[6]
219 | if class_names[cls_id] == 'person':
220 | # Use the same color to plot the bounding boxes of the same object class
221 | if len(box) >= 7 and class_names:
222 | cls_conf = box[5]
223 | cls_id = box[6]
224 | classes = len(class_names)
225 | offset = cls_id * 123457 % classes
226 | red = get_color(2, offset, classes) / 255
227 | green = get_color(1, offset, classes) / 255
228 | blue = get_color(0, offset, classes) / 255
229 |
230 | # If a color is given then set rgb to the given color instead
231 | if color is None:
232 | rgb = (red, green, blue)
233 | else:
234 | rgb = color
235 |
236 | # Calculate the width and height of the bounding box relative to the size of the image.
237 | width_x = x2 - x1
238 | width_y = y1 - y2
239 |
240 | # Set the postion and size of the bounding box. (x1, y2) is the pixel coordinate of the
241 | # lower-left corner of the bounding box relative to the size of the image.
242 | rect = patches.Rectangle((x1, y2),
243 | width_x, width_y,
244 | linewidth = 2,
245 | edgecolor = rgb,
246 | facecolor = 'none')
247 |
248 | # Draw the bounding box on top of the image
249 | a.add_patch(rect)
250 |
251 | # If plot_labels = True then plot the corresponding label
252 | if plot_labels:
253 |
254 | # Create a string with the object class name and the corresponding object class probability
255 | conf_tx = class_names[cls_id] + ': {:.1f}'.format(cls_conf)
256 |
257 | # Define x and y offsets for the labels
258 | lxc = (img.shape[1] * 0.266) / 100
259 | lyc = (img.shape[0] * 1.180) / 100
260 |
261 | # Draw the labels on top of the image
262 | a.text(x1 + lxc, y1 - lyc, conf_tx, fontsize = 24, color = 'k',
263 | bbox = dict(facecolor = rgb, edgecolor = rgb, alpha = 0.8))
264 | plt.show()
265 |
266 |
267 |
268 |
--------------------------------------------------------------------------------