├── Images
└── README.md
├── METADATA
├── camera_placement.txt
├── flrpln.png
└── trackfile.txt
├── VIDEOS
└── README.md
├── algorithm-chart.pdf
├── DEPENDENCIES
└── README.md
├── CODE
├── clothingRecognition.py
├── config.py
├── time_analyze.py
├── splicer.py
├── initial_detect.py
├── track_logger.py
├── enter_camera_data.py
├── main.py
└── deep_reid.py
├── .gitignore
├── README.md
└── LICENSE
/Images/README.md:
--------------------------------------------------------------------------------
1 | Stores images for repo description.
2 |
--------------------------------------------------------------------------------
/METADATA/camera_placement.txt:
--------------------------------------------------------------------------------
1 | (84, 20)
2 | (149, 22)
3 | (149, 62)
4 | (84, 62)
5 |
--------------------------------------------------------------------------------
/VIDEOS/README.md:
--------------------------------------------------------------------------------
1 | Add security footage Files here in the form of:
2 |
3 | `cam_X.avi`
4 |
--------------------------------------------------------------------------------
/METADATA/flrpln.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/arvganesh/Multi-Camera-Object-Tracking/HEAD/METADATA/flrpln.png
--------------------------------------------------------------------------------
/algorithm-chart.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/arvganesh/Multi-Camera-Object-Tracking/HEAD/algorithm-chart.pdf
--------------------------------------------------------------------------------
/DEPENDENCIES/README.md:
--------------------------------------------------------------------------------
1 | # Dependencies
2 |
3 |
4 | In this folder, clone into: Within this folder, clone into:
5 | - [deeppersonreid](https://github.com/KaiyangZhou/deep-person-reid)
6 | - [ssd.pytorch](https://github.com/amdegroot/ssd.pytorch)
7 |
8 |
--------------------------------------------------------------------------------
/CODE/clothingRecognition.py:
--------------------------------------------------------------------------------
1 | from config import *
2 |
3 | def detect_clothes(img): # Detects clothing in an image
4 | clth_model = load_model(PATH_TO_MODEL) # Load Model
5 | img = transform(img)
6 | pred = clth_model.predict(img)
7 | return pred
8 |
9 | def transform(img): # image path
10 | im = keras_image.load_img(img, target_size=(200, 200))
11 | im = keras_image.img_to_array(im)
12 | im = np.expand_dims(im, axis=0)
13 | # (1, height, width, channels), add a dimension because the model expects this shape: (batch_size, height, width, channels)
14 | im /= 255.
15 | return im
16 |
17 | print (detect_clothes("jeans.jpeg"))
--------------------------------------------------------------------------------
/CODE/config.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import math
3 | import os
4 | import time
5 | import cv2
6 | import numpy as np
7 | from collections import namedtuple
8 | import torch
9 | import torch.nn as nn
10 | import torch.backends.cudnn as cudnn
11 | from torch.autograd import Variable
12 | from PIL import Image
13 | import torchvision.transforms as torch_trans
14 |
15 |
16 |
17 | WORK_DIR = os.path.normpath(os.getcwd() + os.sep + os.pardir) + "/"
18 | SSD_PATH = WORK_DIR + "DEPENDENCIES/SSD"
19 | REID_PATH = WORK_DIR + "DEPENDENCIES/deeppersonreid"
20 | VIDEO_PATH = WORK_DIR + "VIDEOS"
21 | PATH_TO_WEIGHTS = SSD_PATH + "/weights/ssd300_mAP_77.43_v2.pth"
22 | CAM_PLACEMENT_PATH = WORK_DIR + "METADATA/camera_placement.txt"
23 | TRACKFILE_PATH = WORK_DIR + "/METADATA/" + "trackfile.txt"
24 | DIST_THRESHOLD = 260
25 | MAX_REID_TIME = 30
26 | REID_NUM_SKIP_FRAMES = 5
27 | REID_DIM_X = 128
28 | REID_DIM_Y = 256
29 | SEM_DIM_X = 1
30 | SEM_DIM_Y = 1
31 | MAX_TRACK_FRAMES = 150
32 | MAX_TRACK_ERROR_FRAMES = 5
33 |
34 | sys.path.append(SSD_PATH)
35 | sys.path.insert(0, (WORK_DIR + 'DEPENDENCIES/deeppersonreid'))
36 |
37 | from ssd import build_ssd
38 | from torchreid import models
39 |
40 | # print ("WD", WORK_DIR)
41 | # print ("SP", SSD_PATH)
42 | # print ("RP", REID_PATH)
43 | # print ("VP", VIDEO_PATH)
44 | # print ("WP", PATH_TO_WEIGHTS)
45 | # print ("CAM", CAM_PLACEMENT_PATH)
--------------------------------------------------------------------------------
/CODE/time_analyze.py:
--------------------------------------------------------------------------------
1 | import time
2 | class Analyzer:
3 | def __init__(self):
4 | self.info = {}
5 | def start(self,timer_name):
6 | if(timer_name in self.info):
7 | self.info[timer_name][0] = time.time()
8 | else:
9 | #[start time,logged times]
10 | self.info[timer_name] = [time.time(),[]]
11 | def stop(self, timer_name):
12 | if(timer_name in self.info):
13 | if(self.info[timer_name][0] != -1):
14 | self.info[timer_name][1].append(time.time()-self.info[timer_name][0])
15 | self.info[timer_name][0] = -1
16 | else:
17 | print("Time Analyzer timer ("+str(timer_name)+" has not been started.")
18 | else:
19 | print("Time Analyzer timer ("+str(timer_name)+") does not exist.")
20 | def show_timer(self,timer_name,verbose=False):
21 | if(timer_name in self.info):
22 | ttl = sum(self.info[timer_name][1])
23 | avg = ttl/float(len(self.info[timer_name][1]))
24 | print("Timer ("+str(timer_name)+"):")
25 | print(" Average: "+str(avg))
26 | print(" Total Time: "+str(ttl))
27 | if(verbose):
28 | print(" Recorded Values: "+str(self.info[timer_name][1]))
29 | else:
30 | print("Time Analyzer timer ("+str(timer_name)+") does not exist.")
31 | def show_times(self,verbose=False):
32 | for key, value in self.info.items():
33 | ttl = sum(value[1])
34 | avg = ttl/float(len(value[1]))
35 | print("Timer ("+str(key)+"):")
36 | print(" Average: "+str(avg))
37 | print(" Total Time: "+str(ttl))
38 | print(" Times Executed: "+str(len(value[1])))
39 | if(verbose):
40 | print(" Recorded Values: "+str(value[1]))
41 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Don't track these folders:
2 | VIDEOS/
3 | DEPENDENCIES/
4 | METADATA/
5 |
6 | # Byte-compiled / optimized / DLL files
7 | __pycache__/
8 | *.py[cod]
9 | *$py.class
10 |
11 | # C extensions
12 | *.so
13 |
14 | # Distribution / packaging
15 | .Python
16 | build/
17 | develop-eggs/
18 | dist/
19 | downloads/
20 | eggs/
21 | .eggs/
22 | lib/
23 | lib64/
24 | parts/
25 | sdist/
26 | var/
27 | wheels/
28 | *.egg-info/
29 | .installed.cfg
30 | *.egg
31 | MANIFEST
32 |
33 | # PyInstaller
34 | # Usually these files are written by a python script from a template
35 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
36 | *.manifest
37 | *.spec
38 |
39 | # Installer logs
40 | pip-log.txt
41 | pip-delete-this-directory.txt
42 |
43 | # Unit test / coverage reports
44 | htmlcov/
45 | .tox/
46 | .coverage
47 | .coverage.*
48 | .cache
49 | nosetests.xml
50 | coverage.xml
51 | *.cover
52 | .hypothesis/
53 | .pytest_cache/
54 |
55 | # Translations
56 | *.mo
57 | *.pot
58 |
59 | # Django stuff:
60 | *.log
61 | local_settings.py
62 | db.sqlite3
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # pyenv
81 | .python-version
82 |
83 | # celery beat schedule file
84 | celerybeat-schedule
85 |
86 | # SageMath parsed files
87 | *.sage.py
88 |
89 | # Environments
90 | .env
91 | .venv
92 | env/
93 | venv/
94 | ENV/
95 | env.bak/
96 | venv.bak/
97 |
98 | # Spyder project settings
99 | .spyderproject
100 | .spyproject
101 |
102 | # Rope project settings
103 | .ropeproject
104 |
105 | # mkdocs documentation
106 | /site
107 |
108 | # mypy
109 | .mypy_cache/
110 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # CCTVTracker
2 | Track an object across a CCTV Network with non-overlapping camera views.
3 |
4 | 
5 |
6 | *Chopiness is due to a low framerate camera being used to record CCTV Footage*
7 |
8 | [FULL DEMO](https://youtu.be/8q7Zv_42oH0)
9 |
10 | ### Table of Contents
11 | - Dependencies
12 | - Thought Process
13 | - Flowchart
14 | - Output
15 | - Authors
16 |
17 |
18 |
19 |
20 |
21 |
22 | ## Dependencies
23 | + Directions in /DEPENDENCIES folder
24 | + opencv and opencv_contrib
25 | + numpy
26 | + PyTorch
27 | + matplotlib
28 |
29 | ## How it works
30 |
31 | When a tracking subject is selected by the user, they are "remembered" by the algorithm. While in the view of a single camera, the subject is tracked using a general object tracking algorithm from OpenCV. When the subject has left the view of a given camera, the surrounding cameras are searched for the tracking subject using the user's initial selection as a reference. Once the algorithm identifies the tracking subject in new camera, single camera tracking resumes.
32 |
33 | ## Algorithm Flowchart
34 | 
35 |
36 | ## Output
37 | The algorithm outputs a video of the tracking subject travelling through the network with a bounding box around them. Below, are still frames from the output video produced on our sample footage.
38 |
39 | 
40 |
41 | 
42 |
43 | ### Inputting information about the Camera Network
44 | The algorithm relies on a user-inputted "map" of the camera network (showing relative location and camera adjacency) entered here:
45 |
46 |
47 |
48 | The user can "place" cameras in placement mode, then indicate the adjacency through the "connections" in connection mode.
49 |
50 | ## Authors
51 |
52 | - [Arvind Ganesh](github.com/arvganesh)
53 | - [Colin Hurley](github.com/colHur)
54 |
--------------------------------------------------------------------------------
/CODE/splicer.py:
--------------------------------------------------------------------------------
1 | from config import *
2 |
3 | Camera_info = namedtuple('Camera_info', ['frame_rate', 'start_frame', 'connections', 'file_name'])
4 | #cam_files as array of all video files from cameras
5 | #data_frame_increment is number of frames skipped between each data point
6 |
7 | #splicer.splicer(camera_video_files,TRACKFILE_PATH,data_inc)
8 | def splicer(camera_video_files, TRACKFILE_PATH, data_inc):
9 | f = open(TRACKFILE_PATH, "r")
10 | caps = []
11 | for x in range(len(camera_video_files)):
12 | # print ("camfiles:", x)
13 | caps.append(cv2.VideoCapture(camera_video_files[x].file_name))
14 | # print (VIDEO_PATH + "/" + camera_video_files[x].file_name)
15 | caps[len(caps)-1].set(cv2.CAP_PROP_FPS, camera_video_files[x].frame_rate)
16 | #caps[x] = (cv2.VideoCapture(cam_files[x]))
17 | #caps[x].set(cv2.CAP_PROP_FPS, frame_rate)
18 |
19 | bbox_w = 0
20 | bbox_h = 0
21 | for x in f:
22 | x = x.rstrip("\n")
23 | if(x == ""): continue
24 | elif(x[0]=="!"):
25 | vals = x[2:len(x)-1].split(",")
26 | cam_ID_to_use = int(vals[0])
27 | print("Using Cam_"+str(cam_ID_to_use))
28 | caps[cam_ID_to_use].set(cv2.CAP_PROP_POS_FRAMES,int(vals[1]))
29 | # print("startfrm: ",int(vals[1]))
30 | bbox_w = int(vals[2])
31 | bbox_h = int(vals[3])
32 | elif(x[0] == "["):
33 | bbox = x[1:len(x)-1].split(",")
34 | p1 = (int(float(bbox[0])), int(float(bbox[1])))
35 | p2 = (int(float(bbox[0]) + bbox_w), int(float(bbox[1]) + bbox_h))
36 | for z in range(data_inc):
37 | #time.sleep(0.1)
38 | ok, frame = caps[cam_ID_to_use].read()
39 |
40 | if not ok:
41 | print ("not ok. SPLICER")
42 | break
43 | #return False
44 | else:
45 | cv2.rectangle(frame, p1, p2, (255,0,0), 2, 1)
46 | cv2.imshow("Frame",frame)
47 | k = cv2.waitKey(30) & 0xff
48 | if k == 27 : break
49 | # Exit if ESC pressed
50 |
51 | f.close()
52 |
53 | #uncomment to use as stand-alone file
54 |
55 | # camera_video_files = [0]*4
56 |
57 | # cons = [0]*4
58 |
59 | # camera_video_files[0] = Camera_info(frame_rate = 8,start_frame = 10*8,file_name = VIDEO_PATH+"/cam_8.avi",connections = cons[0])
60 | # camera_video_files[1] = Camera_info(frame_rate = 9,start_frame = 2*9,file_name = VIDEO_PATH+"/cam_30.avi",connections = cons[1])
61 | # camera_video_files[2] = Camera_info(frame_rate = 30,start_frame = 3*10,file_name = VIDEO_PATH+"/cam_23.avi",connections = cons[2])
62 | # camera_video_files[3] = Camera_info(frame_rate = 21,start_frame = 44*21,file_name = VIDEO_PATH+"/cam_10.avi",connections = cons[3])
63 |
64 | # splicer(camera_video_files,WORK_DIR + "METADATA/" + "trackfile.txt", 2)
--------------------------------------------------------------------------------
/CODE/initial_detect.py:
--------------------------------------------------------------------------------
1 | from config import *
2 | # if torch.cuda.is_available():
3 | # torch.set_default_tensor_type('torch.cuda.FloatTensor')
4 |
5 |
6 | def init_det(frame, net):
7 | # st = time.time()
8 | # net = build_ssd('test', 300, 21) # initialize SSD
9 | # net.load_weights(weights)
10 | # et = time.time()
11 | # print ("ssd time", et - st)
12 |
13 | # print (type(net))
14 | # cv2.imread(frame, cv2.IMREAD_COLOR) # uncomment if dataset not downloaded
15 | image = frame
16 | # from data import VOCDetection, VOC_ROOT, VOCAnnotationTransform
17 | # here we specify year (07 or 12) and dataset ('test', 'val', 'train')
18 | # testset = VOCDetection(VOC_ROOT, [('2007', 'val')], None, VOCAnnotationTransform())
19 | # image = testset.pull_image(img_id)
20 | rgb_image = frame
21 | # View the sampled input image before transform
22 | # plt.figure(figsize=(10,10))
23 | # plt.imshow(rgb_image)
24 | x = cv2.resize(image, (300, 300)).astype(np.float32)
25 | x -= (104.0, 117.0, 123.0)
26 | x = x.astype(np.float32)
27 | x = x[:, :, ::-1].copy()
28 | #splt.imshow(x)
29 | x = torch.from_numpy(x).permute(2, 0, 1)
30 |
31 | xx = Variable(x.unsqueeze(0)) # wrap tensor in Variable
32 | if torch.cuda.is_available():
33 | xx = xx.cuda()
34 | y = net(xx)
35 |
36 | from data import VOC_CLASSES as labels
37 | top_k=10
38 |
39 | #plt.figure(figsize=(10,10))
40 | # colors = plt.cm.hsv(np.linspace(0, 1, 21)).tolist()
41 | #plt.imshow(rgb_image) # plot the image for matplotlib
42 | # currentAxis = plt.gca()
43 |
44 | detections = y.data
45 | # scale each detection back up to the image
46 | scale = torch.Tensor(rgb_image.shape[1::-1]).repeat(2)
47 | big_coords = []
48 | for i in range(detections.size(1)):
49 | j = 0
50 | while detections[0,i,j,0] >= 0.6:
51 | score = detections[0,i,j,0]
52 | label_name = labels[i-1]
53 | if (label_name == "person"):
54 | display_txt = '%s: %.2f'%(label_name, score)
55 | pt = (detections[0,i,j,1:]*scale).cpu().numpy()
56 | coords = [int(pt[0]), int(pt[1]), int(pt[2]-pt[0]+1), int(pt[3]-pt[1]+1)]
57 | big_coords.append(coords)
58 | # print (coords)
59 | # color = colors[i]
60 | # currentAxis.add_patch(plt.Rectangle(*coords, fill=False, edgecolor=color, linewidth=2))
61 | # currentAxis.text(pt[0], pt[1], display_txt, bbox={'facecolor':color, 'alpha':0.5})
62 | j+=1
63 | # plt.show()
64 | return big_coords
65 |
66 | """
67 | USAGE:
68 | init_det('frame.jpg', 'path-to-weights.pth' [OPTIONAL])
69 | """
70 |
71 | # init_det(SSD_PATH + '/lw.jpg')
72 |
73 |
74 |
--------------------------------------------------------------------------------
/METADATA/trackfile.txt:
--------------------------------------------------------------------------------
1 |
2 | !(0,25,105,250)
3 | (296,229)
4 | (294,215)
5 | (297,204)
6 | (299,185)
7 | (310,182)
8 | (314,173)
9 | (321,163)
10 | (326,148)
11 | (334,138)
12 | (341,144)
13 | (341,135)
14 | (341,135)
15 | (343,126)
16 | (341,121)
17 | (337,112)
18 | (338,110)
19 | (338,105)
20 | (338,98)
21 | (339,100)
22 | (337,90)
23 | (337,87)
24 | (338,84)
25 | (339,83)
26 | (339,80)
27 | (339,79)
28 | (340,78)
29 | (342,74)
30 | (341,72)
31 | (341,69)
32 | (340,69)
33 | (339,59)
34 | (337,58)
35 | (335,52)
36 | (334,51)
37 | (337,50)
38 | (335,50)
39 | (333,46)
40 | (333,45)
41 | (333,43)
42 | (336,44)
43 | (336,43)
44 | (334,41)
45 | (337,41)
46 | (337,39)
47 | (339,40)
48 | (339,37)
49 | (339,37)
50 | (342,36)
51 | (345,37)
52 | (346,37)
53 | (346,35)
54 | (347,36)
55 | (351,33)
56 | (351,33)
57 | (351,25)
58 | (353,29)
59 | (358,27)
60 | (357,28)
61 | (356,21)
62 | (355,20)
63 | (355,15)
64 | (356,15)
65 | (356,19)
66 | (355,14)
67 | (354,13)
68 | (355,13)
69 | (356,13)
70 | (354,13)
71 | (356,13)
72 | (357,14)
73 | (358,15)
74 | (359,15)
75 | (360,16)
76 | (361,17)
77 | (362,18)
78 | (361,17)
79 |
80 | !(1,715,105,250)
81 | (296,229)
82 | (296,228)
83 | (296,228)
84 | (302,240)
85 | (308,245)
86 | (313,243)
87 | (308,240)
88 | (313,246)
89 | (310,244)
90 | (310,243)
91 | (310,241)
92 | (311,242)
93 | (309,243)
94 | (310,242)
95 | (312,245)
96 | (311,245)
97 | (311,240)
98 | (313,241)
99 | (308,239)
100 | (308,239)
101 | (309,238)
102 | (309,238)
103 | (309,238)
104 | (309,240)
105 | (308,238)
106 | (309,238)
107 | (307,239)
108 | (309,238)
109 | (307,238)
110 | (308,237)
111 | (308,237)
112 | (309,237)
113 | (309,237)
114 | (310,240)
115 | (311,239)
116 | (311,241)
117 | (314,242)
118 | (313,242)
119 | (314,241)
120 | (313,242)
121 | (313,243)
122 | (314,240)
123 | (314,240)
124 | (313,238)
125 | (314,239)
126 | (313,239)
127 | (314,239)
128 | (313,239)
129 | (312,239)
130 | (312,239)
131 | (312,239)
132 | (313,239)
133 | (313,239)
134 | (312,234)
135 | (312,238)
136 | (312,236)
137 | (312,237)
138 | (312,238)
139 | (313,239)
140 | (313,239)
141 | (314,238)
142 | (314,238)
143 | (313,238)
144 | (313,237)
145 | (313,237)
146 | (313,237)
147 | (313,238)
148 | (313,237)
149 | (312,235)
150 | (314,234)
151 | (314,237)
152 | (313,234)
153 | (312,234)
154 | (313,237)
155 | (313,237)
156 | (313,236)
157 |
158 | !(2,49,105,250)
159 | (296,229)
160 | (294,229)
161 | (295,231)
162 | (294,229)
163 | (294,229)
164 | (293,229)
165 | (295,231)
166 | (296,228)
167 | (294,228)
168 | (294,229)
169 | (294,228)
170 | (293,228)
171 | (294,228)
172 | (293,228)
173 | (293,231)
174 | (294,228)
175 | (294,229)
176 | (294,229)
177 | (293,229)
178 | (293,229)
179 | (293,228)
180 | (293,229)
181 | (295,229)
182 | (298,231)
183 | (299,230)
184 | (301,230)
185 | (299,229)
186 | (351,234)
187 | (350,230)
188 | (348,231)
189 | (350,233)
190 | (355,234)
191 | (359,232)
192 | (399,239)
193 | (398,240)
194 | (395,241)
195 | (395,242)
196 | (401,242)
197 | (404,242)
198 | (403,242)
199 | (403,243)
200 | (406,243)
201 | (402,242)
202 | (404,242)
203 | (404,242)
204 | (405,242)
205 | (406,241)
206 | (403,241)
207 | (406,243)
208 | (405,242)
209 | (406,242)
210 | (403,242)
211 | (405,241)
212 | (408,242)
213 | (409,243)
214 | (411,243)
215 | (412,244)
216 | (413,243)
217 | (413,243)
218 | (413,243)
219 | (413,243)
220 | (417,244)
221 | (418,244)
222 | (418,244)
223 | (418,244)
224 | (418,244)
225 | (418,244)
226 | (417,244)
227 | (418,244)
228 | (417,244)
229 | (417,244)
230 | (416,243)
231 | (415,244)
232 | (415,243)
233 | (416,243)
234 | (416,243)
235 |
236 | !(3,20,105,250)
237 | (296,229)
238 | (296,229)
239 | (296,231)
240 | (298,232)
241 | (302,239)
242 | (305,244)
243 | (308,254)
244 | (294,243)
245 | (305,257)
246 | (313,262)
247 | (311,256)
248 | (306,249)
249 | (307,253)
250 | (309,257)
251 | (310,253)
252 | (309,255)
253 | (310,253)
254 | (309,252)
255 | (308,251)
256 | (309,253)
257 | (308,250)
258 | (310,253)
259 | (308,250)
260 | (310,254)
261 | (312,257)
262 | (311,257)
263 | (309,254)
264 |
--------------------------------------------------------------------------------
/CODE/track_logger.py:
--------------------------------------------------------------------------------
1 | import cv2
2 | from config import WORK_DIR, MAX_TRACK_FRAMES, MAX_TRACK_ERROR_FRAMES, VIDEO_PATH
3 | from cv2 import selectROI
4 | import numpy as np
5 | import matplotlib.pyplot as plt
6 | import matplotlib.image as mpimg
7 | import sys
8 | import math
9 | import time
10 |
11 | '''
12 | import h5py
13 | with h5py.File('random.hdf5', 'w') as f:
14 | dset = f.create_dataset("default", data=arr)
15 | dset = f.create_dataset("yeet", data=arr[:5])
16 | f.close()
17 |
18 | with h5py.File('random.hdf5', 'r') as f:
19 | deff = f['default']
20 | yeet = f['yeet']
21 | print(deff, yeet)
22 | f.close()
23 | with h5py.File('PreprocessedData.h5', 'w') as hf:
24 | hf.create_dataset("X_train", data=X_train_data, maxshape=(None, 512, 512, 9))
25 |
26 |
27 | '''
28 |
29 | #frames_elapsed, error = track_logger.track(cap = caps[cur_cam_indx], bbox = bbox, data_inc = data_inc)
30 | def track(cam_id, cap, bbox, data_inc, time_analyzer):
31 | f = open((WORK_DIR + "/METADATA/" + "trackfile.txt"),"a+")
32 | track_info = []
33 | frm_cnt = 0
34 | print("Progress Cam_" + str(cam_id) + ": ", end="", flush=True)
35 | #cam, start frame, bbox width, bbox height
36 | f.write("\n"+"!("+str(cam_id)+","+str(int(cap.get(1)))+","+str(bbox[2])+","+str(bbox[3])+")\n")
37 | f.write("("+str(int(bbox[0]))+","+str(int(bbox[1]))+"]")
38 | # track_info.append("\n"+"!("+str(cam_id)+","+str(int(cap.get(1)))+","+str(bbox[2])+","+str(bbox[3])+")\n")
39 | # track_info.append("["+str(int(bbox[0]))+","+str(int(bbox[1]))+"]")
40 |
41 | tracker_type = "CSRT"
42 | # if tracker_type == 'BOOSTING':
43 | # tracker = cv2.TrackerBoosting_create()
44 | # if tracker_type == 'MIL':
45 | # tracker = cv2.TrackerMIL_create()
46 | # if tracker_type == 'KCF':
47 | # tracker = cv2.TrackerKCF_create()
48 | # if tracker_type == 'TLD':
49 | # tracker = cv2.TrackerTLD_create()
50 | # if tracker_type == 'MEDIANFLOW':
51 | # tracker = cv2.TrackerMedianFlow_create()
52 | # if tracker_type == 'GOTURN':
53 | # tracker = cv2.TrackerGOTURN_create()
54 | # if tracker_type == 'MOSSE':
55 | # tracker = cv2.TrackerMOSSE_create()
56 | # if tracker_type == "CSRT":'
57 | # st = time.time()
58 | tracker = cv2.TrackerCSRT_create()
59 | # print ("tracker time", time.time() - st)
60 | """
61 | BOOSTING -> ye
62 | MIL -> H E C K no
63 | KCF -> ehhhhhhhhhhhhhh
64 | TLD -> straight trash lmao
65 | MEDIANFLOW -> see TLD
66 | GOTURN -> nope
67 | MOSSE -> see above and TLD
68 | CSRT -> yeh
69 | """
70 | ok, frame = cap.read()
71 | # st = time.time()
72 |
73 | ok = tracker.init(frame, tuple(bbox))
74 | # print ("tracker time", time.time() - st)
75 | fail_detect_itrs = 0
76 | cycle = 0
77 | while True:
78 | # Read a new frame
79 | time_analyzer.start("reading")
80 | ok, frame = cap.read()
81 | time_analyzer.stop("reading")
82 | frm_cnt += 1
83 | if not ok:
84 | f.close()
85 | # write_to_trackfile(track_info)
86 | #finish out progress bar
87 | numofthing = math.ceil((MAX_TRACK_FRAMES - frm_cnt) / data_inc)
88 | print("#" * numofthing, end="", flush=True)
89 | print("")
90 | # with h5py.File((WORK_DIR + "/METADATA/" + "trackfile.hdf5"), 'w') as f:
91 | # f.create_dataset("tracklog", data=track_info)
92 | # f.close()
93 | return frm_cnt # goes to next cams
94 |
95 | # Update tracker
96 | time_analyzer.start("update")
97 | ok, bbox = tracker.update(frame)
98 | time_analyzer.stop("update")
99 |
100 | #only record at data_inc
101 | if(cycle==data_inc-1):
102 | cycle=0
103 | #record bbox pos
104 | if ok:
105 | # track_info.append([int(bbox[0]),int(bbox[1])])
106 | f.write("("+str(int(bbox[0]))+","+str(int(bbox[1]))+")\n")
107 | else:
108 | # track_info.append([-1,-1])
109 | f.write("-e-\n")
110 | #increment progress bar
111 | print("#", end="", flush=True)
112 | else:
113 | cycle+=1
114 | if(not ok):
115 | fail_detect_itrs+=1
116 | if(fail_detect_itrs > MAX_TRACK_ERROR_FRAMES):
117 | # write_to_trackfile(track_info)
118 | f.close()
119 | print("")
120 | return frm_cnt
121 | if(frm_cnt > MAX_TRACK_FRAMES):
122 | # write_to_trackfile(track_info)
123 | f.close()
124 | print("")
125 | return frm_cnt
126 |
127 |
128 |
129 | def write_to_trackfile(track_info):
130 | # st = time.time()
131 | with open(WORK_DIR + "/METADATA/" + "trackfile.txt", "a+") as f:
132 | for item in track_info:
133 | f.write(str(item) + "\n")
134 | # print(str(item) + "\n")
135 | f.close()
136 | # et = time.time()
137 | # print ("write time:", et - st)
138 | # sys.exit()
139 |
140 | #uncomment to use as stand-alone file
141 | # start_frame = 8*3
142 | # vid = VIDEO_PATH + "/cam_8.avi"
143 | # cap = cv2.VideoCapture(vid)
144 | # cap.set(cv2.CAP_PROP_FPS, 8)
145 | # cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)
146 | # ok, frame = cap.read()
147 | # bbox = selectROI(frame)
148 | # track(0,cap,bbox,2)
149 |
150 |
151 | # cam_id, cap, bbox, data_inc
152 |
153 | """
154 | What we know
155 | - bounding box coords are accurate
156 | - tracker is activated, but for some reason stuck in the same spot.
157 | """
--------------------------------------------------------------------------------
/CODE/enter_camera_data.py:
--------------------------------------------------------------------------------
1 | import cv2
2 | import numpy as np
3 | import math
4 | import sys
5 | from config import WORK_DIR
6 | #from bitarray import bitarray
7 |
8 | cams = []
9 | max_cams = 255
10 | cons = np.zeros((0,0), dtype = np.bool)
11 | max_dist = 10
12 | selected_cam = None
13 | placing = True
14 | invalidInput = True
15 | floorplan_file = WORK_DIR + "METADATA/" + "flrpln.png"
16 | org_img = cv2.imread(floorplan_file)
17 | cam_img = org_img.copy()
18 | conn_img = cam_img.copy()
19 |
20 |
21 | def dist(p1,p2): return (math.sqrt((p1[0]-p2[0])**2+(p1[1]-p2[1])**2))
22 |
23 | def closest_cam(x, y):
24 | closestCam = [-1,math.inf]
25 | for c in range(len(cams)):
26 | d = dist((x,y),(cams[c][0],cams[c][1]))
27 | if(d0):
35 | for row in range(len(cons)):
36 | for c in range(row,len(cons)):
37 | if(cons[row][c]):
38 | cv2.line(conn_img,(cams[row][0],cams[row][1]), (cams[c][0],cams[c][1]), (0,0,0), 4)
39 |
40 | def update_cameras_img():
41 | global cam_img
42 | cam_img = org_img.copy()
43 | for c in cams:
44 | cv2.circle(cam_img, (c[0],c[1]),5,(0,0,255),-1)
45 |
46 | def mouse_evt(event,x,y,flags,param):
47 | global cons,cams, selected_cam
48 | if(event == cv2.EVENT_LBUTTONDOWN):
49 | if(placing):
50 | if(len(cams)0):
78 | indx = closest_cam(x,y)
79 | if(indx != None):
80 | cons = np.delete(cons, indx, axis = 0)
81 | cons = np.delete(cons, indx, axis = 1)
82 | del cams[indx]
83 | update_cameras_img()
84 | cv2.imshow("Floorplan",cam_img)
85 |
86 | while(invalidInput):
87 | inpt = input("Do you want to overwrite any existing information?(y/n) ")
88 | if(inpt == "y"):
89 | #clear files
90 | f = open("camera_placement.txt","w")
91 | f.close()
92 | f = open("connection_info.bin","wb")
93 | f.close()
94 | invalidInput = False
95 | elif(inpt == "n"):
96 | try:
97 | f_cams = open("camera_placement.txt","r")
98 | f_cons = open("connection_info.txt","r")
99 | f_cams.seek(0)
100 | f_cons.seek(0)
101 | for x in f_cams:
102 | x = x.rstrip()
103 | if(x[0] == "("):
104 | vals = (x[1:len(x)-1]).split(",")
105 | for v in range(len(vals)):
106 | vals[v] = int(vals[v])
107 | cams.append(tuple(vals))
108 |
109 | update_cameras_img()
110 |
111 | cons = np.zeros((len(cams),len(cams)),dtype=np.bool)
112 | itr = 0
113 | for x in f_cons:
114 | q = x.rstrip()
115 | for j in range(len(q)):
116 | cons[itr][j] = bool(int(q[j]))
117 | itr += 1
118 | #cons[itr] = list(x)
119 | update_connections_img()
120 | # with f_cons as f:
121 | # first_byte = f.read(1)
122 | # num_cams = int.frombytes(byte,byteorder='big')
123 | # cons = np.array((num_cams,num_cams),dtype=np.bool)
124 | # bytes_per_cam = math.ceil(num_cams/8)
125 | # byte = f.read(bytes_per_cam)
126 | # itr = 0
127 | # while byte:
128 | # a = bitarray()
129 | # a.frombytes(byte)
130 | # cons[itr] = (np.frombuffer(a.unpack(zero=b'\x00',one='\xFF'),dtype=np.bool,count=-1))[:num_cams]
131 | # itr += 1
132 | # byte = f.read(bytes_per_cam)
133 | except: pass
134 | invalidInput = False
135 | print("Number of cameras must be "+str(max_cams)+" or less")
136 | print("Use Esc key to save data and close the window")
137 | print("Use Spacebar to enter Camera Placement mode")
138 | print("Use Enter key to enter Camera Connetion mode")
139 |
140 | cv2.namedWindow("Floorplan")
141 | cv2.setMouseCallback("Floorplan",mouse_evt)
142 | cv2.imshow("Floorplan",cam_img)
143 | while(True):
144 | k = cv2.waitKey(1) & 0xff
145 | if k == 27:
146 | if(len(cams)>0):
147 | f_cams = open(WORK_DIR + "METADATA/" + "camera_placement.txt","w")
148 | for x in range(len(cams)):
149 | f_cams.write(str(cams[x])+"\n")
150 | f_cams.close()
151 | f_cons = open(WORK_DIR + "METADATA/" + "connection_info.txt","w")
152 | for x in range(len(cons)):
153 | for j in range(len(cons[x])):
154 | f_cons.write(str(int(cons[x][j])))
155 | f_cons.write("\n")
156 | f_cons.close()
157 | cv2.destroyAllWindows()
158 | print("Ending...")
159 | sys.exit()
160 | elif k == 32:
161 | if(not placing):
162 | print("Placement Mode")
163 | update_cameras_img()
164 | cv2.imshow("Floorplan",cam_img)
165 | placing = True
166 | elif k == 13:
167 | if(placing):
168 | print("Connection Mode")
169 | update_connections_img()
170 | cv2.imshow("Floorplan",conn_img)
171 | placing = False
172 |
173 |
174 |
175 |
176 |
177 |
--------------------------------------------------------------------------------
/CODE/main.py:
--------------------------------------------------------------------------------
1 | import time
2 | import sys
3 | import cv2
4 | from cv2 import selectROI
5 | from config import *
6 | from collections import namedtuple
7 | from deep_reid import deep_reid
8 | import track_logger as track_logger
9 | from initial_detect import init_det
10 | import splicer
11 | from time_analyze import Analyzer
12 | Camera_info = namedtuple('Camera_info', ['frame_rate', 'start_frame', 'connections', 'file_name'])
13 |
14 | # print("Fix DIM_X and DIM_Y in config. I put place holders but they arent the right values")
15 |
16 | t = Analyzer()
17 |
18 | """ INIT MODELS """
19 | net = build_ssd('test', 300, 21) # init SSD
20 | net.load_weights(PATH_TO_WEIGHTS) # init SSD
21 |
22 | model = models.init_model("resnet50", num_classes=1, loss={'xent'}, use_gpu=False) # init REID
23 |
24 | """ *********** """
25 |
26 | def check_bboxes(frame):
27 | # frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
28 | global subject
29 | bboxes_ppl = init_det(frame=frame, net=net)
30 | for bbox in bboxes_ppl:
31 | bbox_img_org = frame[bbox[1]:bbox[1]+bbox[3],bbox[0]:bbox[0]+bbox[2]]
32 | bbox_img = cv2.resize(bbox_img_org, (SEM_DIM_X,SEM_DIM_Y))
33 | # attrs = semantic_attribute_det(bbox_img)
34 | # if (attrs == subject["attr_id"]):
35 | # #bbox_img = cv2.resize(frame[bbox[1]:bbox[1]+bbox[3],bbox[0]:bbox[0]+bbox[2]], (REID_DIM_X,REID_DIM_Y))
36 |
37 | # while True:
38 | # cv2.imshow("image", bbox_img_org)
39 | # cv2.imshow("img2", subject["img"])
40 | # k = cv2.waitKey(1) & 0xff
41 | # if k == 27:
42 | # cv2.destroyAllWindows()
43 | # break
44 | # # sys.exit()
45 | dist = deep_reid(subject["img"], bbox_img_org, model)
46 | # print ("Distmat", dist)
47 | if(dist < DIST_THRESHOLD):
48 | # print ("bbox",bbox)
49 | return bbox
50 | return None
51 |
52 | #clear trackfile **chnage to hdf5 if necisary
53 | f = open(WORK_DIR + "METADATA/" + "trackfile.txt", "w")
54 | f.close()
55 |
56 | #get inputs
57 | st = time.time()
58 | # start_time = int(input("Start Time: "))
59 | # end_time = int(input("End Time: "))
60 | # data_inc = int(input("Data increment: "))
61 | # start_camera_id = int(input("Start Camera ID: "))
62 |
63 | start_time = 24
64 | end_time = 70
65 | data_inc = 2
66 | start_camera_id = 0
67 |
68 |
69 | #set time diff to check against
70 | #end_time -= start_time
71 | # if(end_time <= 0):
72 | # print("End time is before Start time. MAIN")
73 | # sys.exit()
74 |
75 |
76 | try:
77 | f_cons = open(WORK_DIR + "METADATA/" + "connection_info.txt","r")
78 | f_cons.seek(0)
79 | cons = []
80 | itr = 0
81 | for x in f_cons:
82 | cons.append([])
83 | q = x.rstrip()
84 | for j in range(len(q)):
85 | if(bool(int(q[j]))): cons[itr].append(j)
86 | itr += 1
87 | except:
88 | print("Error opening connection config file. MAIN")
89 | sys.exit()
90 |
91 |
92 | #set camera info
93 | #Unhard code this **
94 | camera_video_files = [0]*len(cons)
95 |
96 | camera_video_files[0] = Camera_info(frame_rate = 8,start_frame = 10*8,file_name = VIDEO_PATH+"/cam_8.avi",connections = cons[0])
97 | camera_video_files[1] = Camera_info(frame_rate = 9,start_frame = 2*9,file_name = VIDEO_PATH+"/cam_30.avi",connections = cons[1])
98 | camera_video_files[2] = Camera_info(frame_rate = 30,start_frame = 3*10,file_name = VIDEO_PATH+"/cam_23.avi",connections = cons[2])
99 | camera_video_files[3] = Camera_info(frame_rate = 21,start_frame = 44*21,file_name = VIDEO_PATH+"/cam_10.avi",connections = cons[3])
100 |
101 | #initialize caps
102 | caps = []
103 | for x in range(len(camera_video_files)):
104 | caps.append(cv2.VideoCapture(camera_video_files[x].file_name))
105 | if(not caps[x].isOpened()):
106 | print("Error opening video. MAIN")
107 | sys.exit()
108 | caps[x].set(5, camera_video_files[x].frame_rate)
109 | caps[x].set(1,max(camera_video_files[x].start_frame-1,0))
110 | ok,frame = caps[x].read()
111 | if not ok:
112 | print("Cannot read video file "+str(camera_video_files[x].file_name)+". MAIN")
113 | sys.exit()
114 |
115 | cur_time = start_time
116 | cur_cam_id = start_camera_id
117 |
118 | ok,frame = caps[start_camera_id].read()
119 |
120 | #bbox = (348, 80, 53, 124)
121 | bbox = selectROI(frame,False)
122 | cv2.destroyAllWindows()
123 |
124 | subject = {}
125 |
126 |
127 | # bbox_img = cv2.resize(frame[bbox[1]:bbox[1]+bbox[3],bbox[0]:bbox[0]+bbox[2]], (REID_DIM_X,REID_DIM_Y))
128 | bbox_img = frame[bbox[1]:bbox[1]+bbox[3],bbox[0]:bbox[0]+bbox[2]]
129 | # print("bbox_img type",type(bbox_img))
130 | subject["img"] = bbox_img
131 | subject["bbox"] = bbox
132 | # subject["attr_id"] = semantic_attribute_det(bbox_img)
133 |
134 | TOTAL_TRACKLOG_TIME = 0
135 | TOTAL_REID_TIME = 0
136 |
137 | while(cur_time < end_time):
138 | print("Now using camera"+str(cur_cam_id))
139 | stt = time.time()
140 | frames_elapsed = track_logger.track(cam_id = cur_cam_id, cap = caps[cur_cam_id], bbox = subject["bbox"], data_inc = data_inc, time_analyzer = t)
141 | ett = time.time()
142 | TOTAL_TRACKLOG_TIME += ett-stt
143 |
144 | cur_time += int(frames_elapsed/camera_video_files[cur_cam_id].frame_rate)
145 | surrounding_cams = camera_video_files[cur_cam_id].connections
146 | if(len(surrounding_cams) == 0):
147 | print("Cam_"+str(cur_cam_id)+" does not have any surrounding cameras. MAIN")
148 | print ("Amount of video analyzed: "+str(cur_time) +" seconds.")
149 | break
150 | begin_search_time = time.time()
151 | found = False
152 | frame_itr = 0
153 | frame_itr_interval = REID_NUM_SKIP_FRAMES
154 | print("Calculating",end="",flush=True)
155 | stt = time.time()
156 | while(not found):
157 | if(time.time()-begin_search_time > MAX_REID_TIME):
158 | print("Could not RE-ID subject within "+str(MAX_REID_TIME)+" seconds. Ending Program. MAIN")
159 | cur_time = end_time+1 #break outer while
160 | break
161 | for cam in surrounding_cams:
162 | ok, frame = caps[cam].read()
163 | if(not ok):
164 | print("Not ok frame. MAIN")
165 | else:
166 | print(".",end="",flush=True)
167 | match_bbox = check_bboxes(frame)
168 | if(match_bbox != None):
169 | subject["bbox"] = match_bbox
170 | cur_cam_id = cam
171 | found = True
172 | print ("")
173 | break
174 |
175 | for _ in range(frame_itr_interval):
176 | caps[cam].read()
177 | frame_itr += frame_itr_interval
178 | ett = time.time()
179 | TOTAL_REID_TIME += ett-stt
180 | if(cur_cam_id == 0): break #0 is last camera so finish search
181 |
182 | et = time.time()
183 | print("TOTAL_TRACKLOG_TIME",TOTAL_TRACKLOG_TIME)
184 | print("TOTAL_REID_TIME",TOTAL_REID_TIME)
185 | print("\n")
186 | print(" **************** Summary ****************")
187 | print(" Total Time: {} ".format(str(et-st)))
188 | print(" Algorithm Completed ")
189 | print(" *****************************************")
190 | print("\n")
191 |
192 | t.show_times()
193 |
194 | invalid_input = True
195 | while(invalid_input):
196 | inpt = input("Would you like to generate the video? [y/n] ")
197 | if(inpt == "y"):
198 | splicer.splicer(camera_video_files,TRACKFILE_PATH,data_inc)
199 | print("Done generating video. Closing Program. MAIN")
200 | invalid_input = False
201 | elif(inpt == "n"):
202 | print("Ok. Closing Program")
203 | invalid_input = False
204 |
--------------------------------------------------------------------------------
/CODE/deep_reid.py:
--------------------------------------------------------------------------------
1 | #from __future__ import #print_function
2 | from __future__ import division
3 |
4 | from config import *
5 | # from PIL import Image
6 | # import torch
7 | # import torch.nn as nn
8 | # import torch.backends.cudnn as cudnn
9 | # from torch.optim import lr_scheduler
10 |
11 | # sys.path.insert(0, (WORK_DIR + 'DEPENDENCIES/deeppersonreid'))
12 |
13 | # from torchreid.data_manager import ImageDataManager
14 | # from torchreid import models
15 | # from torchreid.losses import CrossEntropyLoss, DeepSupervision
16 | # from torchreid.utils.iotools import save_checkpoint, check_isfile
17 | # from torchreid.utils.avgmeter import AverageMeter
18 | # from torchreid.utils.loggers import Logger, RankLogger
19 | # from torchreid.utils.torchtools import count_num_param, open_all_layers, open_specified_layers
20 | # from torchreid.utils.reidtools import visualize_ranked_results
21 | # from torchreid.eval_metrics import evaluate
22 | # from torchreid.optimizers import init_optimizer
23 |
24 | # from torchvision.transforms import *
25 |
26 |
27 | def deep_reid(query_np, gal_np, model):
28 | # print ("reid")
29 | # model params
30 | use_gpus = False
31 | # root = REID_PATH + "/data"
32 | # name = "single_test"
33 | # split_id = 0
34 | # height = 256
35 | # width = 128
36 | # train_batch_size = 32
37 | # test_batch_size = 1
38 | # workers = 4
39 | # train_sampler = ''
40 | # num_instances = 4
41 | # cuhk03_labeled = False
42 | # cuhk03_classic_split = False
43 |
44 | # torch.manual_seed(1)
45 | path_to_weights = REID_PATH + "/weights/resnet50_market_xent/resnet50_market_xent.pth.tar"
46 | save_log_dir = REID_PATH + "/log/eval-resnet50"
47 |
48 | # log_name = 'log_test.txt'
49 | # sys.stdout = Logger(osp.join(save_log_dir, log_name))
50 |
51 | # Initialize Data
52 | # dm = ImageDataManager(use_gpus, [name], [name], root, split_id, height, width, train_batch_size, test_batch_size, workers, train_sampler, num_instances, cuhk03_labeled, cuhk03_classic_split)
53 | # testloader_dict = dm.return_dataloaders()
54 |
55 | # Initialize Model
56 | # st = time.time()
57 | # model = models.init_model("resnet50", num_classes=1, loss={'xent'}, use_gpu=use_gpus)
58 | # et = time.time()
59 | # print("reid time", et-st)
60 | # Initialize and Load Weights
61 | # from functools import partial
62 | # import pickle
63 | # pickle.load = partial(pickle.load, encoding="latin1")
64 | # pickle.Unpickler = partial(pickle.Unpickler, encoding="latin1")
65 | # checkpoint = torch.load(path_to_weights, pickle_module=pickle)
66 | checkpoint = torch.load(path_to_weights, map_location='cpu')
67 | pretrain_dict = checkpoint['state_dict']
68 | model_dict = model.state_dict()
69 | pretrain_dict = {k: v for k, v in pretrain_dict.items() if k in model_dict and model_dict[k].size() == v.size()}
70 | model_dict.update(pretrain_dict)
71 | model.load_state_dict(model_dict)
72 |
73 | # Run Model
74 | # queryloader = testloader_dict[name]['query']
75 | # galleryloader = testloader_dict[name]['gallery']
76 | # distmat = test(model, query_np, gal_np, use_gpus)
77 | #visualize_ranked_results(distmat, dm.return_testdataset_by_name(name), save_log_dir + "/ranked_results/yeet", 1)
78 | #print ("DIST:", distmat)
79 | #gallery = dm.return_testdataset_by_name(name)[1]
80 | return test(model, query_np, gal_np, use_gpus)
81 |
82 | def t1(img): # opencv
83 | st = time.time()
84 | # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
85 | imagenet_mean = [0.485, 0.456, 0.406]
86 | imagenet_std = [0.229, 0.224, 0.225]
87 | normalize = torch_trans.Normalize(mean=imagenet_mean, std=imagenet_std)
88 | transforms = []
89 | transforms += [torch_trans.Resize((256, 128))]
90 | transforms += [torch_trans.ToTensor()]
91 | transforms += [normalize]
92 | transforms = torch_trans.Compose(transforms)
93 | # img = cv2.resize(img, (128, 256), interpolation=cv2.INTER_NEAREST)
94 | img = Image.fromarray(img)
95 | img = transforms(img)
96 | et = time.time()
97 | # print("cv time",et-st)
98 | return img
99 |
100 | def t2(img_path=None): # PIL
101 | st = time.time()
102 | if img_path is not None:
103 | img = Image.open(img_path)
104 | imagenet_mean = [0.485, 0.456, 0.406]
105 | imagenet_std = [0.229, 0.224, 0.225]
106 | normalize = Normalize(mean=imagenet_mean, std=imagenet_std)
107 |
108 | transforms = []
109 | transforms += [Resize((256, 128))]
110 | transforms += [ToTensor()]
111 | transforms += [normalize]
112 |
113 | transforms = Compose(transforms)
114 |
115 | img = transforms(img)
116 | et = time.time()
117 | print("PIL time",et-st)
118 | return img
119 |
120 | # def main_test():
121 | # img = cv2.imread("naturo-monkey-selfie.jpg", cv2.IMREAD_COLOR)
122 | # a = t1(img)
123 | # b = t2("naturo-monkey-selfie.jpg")
124 | # print ("opencv",a)
125 | # print ("PIL", b)
126 | # return torch.eq(a, b).all()
127 |
128 | def test(model, query_np, gal_np, use_gpu, ranks=[1, 5, 15, 20], return_distmat=True): # !!!!!!
129 | # batch_time = AverageMeter()
130 |
131 | model.eval()
132 | # imgs -> queryloader / galleryloader -> testloader_dict[q/g] -> dm.return_dataloaders() -> imagedatamanager (line 57) -> transform function -> img dataset thingy -> dataset loaders -> somehow transfroms img from img path -> transformed image.
133 | # we want to stop image writing from (numpy array -> )
134 | with torch.no_grad():
135 | qf = []
136 | query_np = t1(query_np)
137 | query_np = query_np.unsqueeze(0)
138 | # print ("T1",query_np.size())
139 | # query_np = t2("hi.jpg")
140 | # print ("T2", query_np)
141 | features = model(query_np) # !!!
142 | features = features.data.cpu()
143 | qf.append(features)
144 | # q_pids.extend(pids)
145 | # q_camids.extend(camids)
146 | qf = torch.cat(qf, 0)
147 | # q_pids = np.asarray(q_pids)
148 | # q_camids = snp.asarray(q_camids)
149 |
150 | # #print ("\n")
151 | # #print ("pid", q_pids)
152 | # #print ("camid", q_camids)
153 | # #print ("\n")
154 | gf = []
155 | # #print ("\n")
156 | # #print ("g_pid", pids)
157 | # #print ("g_camid", camids) #
158 | gal_np = t1(gal_np)
159 | gal_np = gal_np.unsqueeze(0)
160 | features = model(gal_np)
161 | # #print ("FEaT1", features)
162 | # #print ("FL1", len(features[0]))
163 |
164 | features = features.data.cpu()
165 | # #print ("FEaT", features)
166 | # #print ("FL", len(features[0]))
167 | gf.append(features)
168 | # g_pids.extend(pids)
169 | # g_camids.extend(camids)
170 | gf = torch.cat(gf, 0)
171 | # g_pids = np.asarray(g_pids)
172 | # g_camids = np.asarray(g_camids)
173 |
174 | #print("Extracted features for gallery set, obtained {}-by-{} matrix".format(gf.size(0), gf.size(1)))
175 |
176 | m, n = qf.size(0), gf.size(0)
177 | distmat = torch.pow(qf, 2).sum(dim=1, keepdim=True).expand(m, n) + \
178 | torch.pow(gf, 2).sum(dim=1, keepdim=True).expand(n, m).t()
179 | # #print ("dist_b", distmat)
180 |
181 | distmat = distmat.addmm(beta=1, alpha=-2, mat1=qf, mat2=gf.t())
182 |
183 | distmat = distmat.numpy()
184 | # #print("dids: "+str(distmat))
185 | # #print ("W",distmat)
186 | indices = np.argsort(distmat, axis=1)
187 | # #print ("RESULT:", distmat[0][0], (distmat[0][0] < 0))
188 | # #print ("IND_E:", indices)
189 | # #print("Computing CMC and mAP")
190 | #match = evaluate(distmat, q_pids, g_pids, q_camids, g_camids, use_cython=False)
191 | # #print("Results ----------")
192 | # #print("mAP: {:.1%}".format(mAP))
193 | # #print("CMC curve")
194 | # # for r in ranks:
195 | # # from p#print import p#print
196 | # # #print("Rank-{:<3}: {:.1%}".format(r, cmc[r-1]))
197 | # # #print("------------------")
198 |
199 | #print ("match", match)
200 | if return_distmat:
201 | return distmat
202 |
203 | #print(cmc)
204 | #return ((distmat))
205 | # img = cv2.imread("hi.jpg")
206 | # deep_reid(img, img)
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------