├── edits └── test-output.mp4 ├── config ├── download_weights.sh ├── coco.data ├── coco.names ├── yolov3-tiny.cfg └── yolov3.cfg ├── __pycache__ ├── sort.cpython-37.pyc ├── models.cpython-37.pyc ├── motion_cython.cpython-37.pyc ├── object_tracker.cpython-37.pyc ├── video_splice.cpython-37.pyc └── motion_detection.cpython-37.pyc ├── .vscode └── settings.json ├── utils ├── __pycache__ │ ├── utils.cpython-36.pyc │ ├── utils.cpython-37.pyc │ ├── __init__.cpython-36.pyc │ ├── datasets.cpython-36.pyc │ ├── parse_config.cpython-36.pyc │ └── parse_config.cpython-37.pyc ├── parse_config.py ├── datasets.py └── utils.py ├── .gitignore ├── requirements.txt ├── README.md ├── main.py ├── motion_detection.py ├── video_splice.py ├── object_tracker.py ├── sort.py ├── models.py └── LICENSE /edits/test-output.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nishgowda/autocutpro/HEAD/edits/test-output.mp4 -------------------------------------------------------------------------------- /config/download_weights.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | wget https://pjreddie.com/media/files/yolov3.weights 4 | -------------------------------------------------------------------------------- /__pycache__/sort.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nishgowda/autocutpro/HEAD/__pycache__/sort.cpython-37.pyc -------------------------------------------------------------------------------- /__pycache__/models.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nishgowda/autocutpro/HEAD/__pycache__/models.cpython-37.pyc -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "/Users/nishgowda/Desktop/Code/Projects/Smart-Clips/env/bin/python3" 3 | } -------------------------------------------------------------------------------- /utils/__pycache__/utils.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nishgowda/autocutpro/HEAD/utils/__pycache__/utils.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/utils.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nishgowda/autocutpro/HEAD/utils/__pycache__/utils.cpython-37.pyc -------------------------------------------------------------------------------- /__pycache__/motion_cython.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nishgowda/autocutpro/HEAD/__pycache__/motion_cython.cpython-37.pyc -------------------------------------------------------------------------------- /__pycache__/object_tracker.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nishgowda/autocutpro/HEAD/__pycache__/object_tracker.cpython-37.pyc -------------------------------------------------------------------------------- /__pycache__/video_splice.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nishgowda/autocutpro/HEAD/__pycache__/video_splice.cpython-37.pyc -------------------------------------------------------------------------------- /utils/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nishgowda/autocutpro/HEAD/utils/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/datasets.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nishgowda/autocutpro/HEAD/utils/__pycache__/datasets.cpython-36.pyc -------------------------------------------------------------------------------- /__pycache__/motion_detection.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nishgowda/autocutpro/HEAD/__pycache__/motion_detection.cpython-37.pyc -------------------------------------------------------------------------------- /utils/__pycache__/parse_config.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nishgowda/autocutpro/HEAD/utils/__pycache__/parse_config.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/parse_config.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nishgowda/autocutpro/HEAD/utils/__pycache__/parse_config.cpython-37.pyc -------------------------------------------------------------------------------- /config/coco.data: -------------------------------------------------------------------------------- 1 | classes= 80 2 | train=data/coco/trainvalno5k.txt 3 | valid=data/coco/5k.txt 4 | names=data/coco.names 5 | backup=backup/ 6 | eval=coco 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | videos 2 | images 3 | config/yolov3.weights 4 | .DS_Store 5 | _pycache_ 6 | out 7 | edits 8 | processing_module.cpython-37m-darwin.so 9 | build 10 | env 11 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | cycler==0.10.0 2 | decorator==4.4.2 3 | filterpy==1.4.5 4 | imageio==2.9.0 5 | joblib==1.0.0 6 | kiwisolver==1.3.1 7 | llvmlite==0.35.0 8 | matplotlib==3.3.3 9 | networkx==2.5 10 | numba==0.52.0 11 | numpy==1.19.5 12 | opencv-python==4.5.1.48 13 | Pillow==8.1.0 14 | pyparsing==2.4.7 15 | python-dateutil==2.8.1 16 | PyWavelets==1.1.1 17 | scikit-image==0.18.1 18 | scikit-learn==0.22.2 19 | scipy==1.6.0 20 | six==1.15.0 21 | threadpoolctl==2.1.0 22 | tifffile==2021.1.8 23 | torch==1.7.1 24 | torchvision==0.8.2 25 | tqdm==4.55.2 26 | typing-extensions==3.7.4.3 -------------------------------------------------------------------------------- /config/coco.names: -------------------------------------------------------------------------------- 1 | person 2 | bicycle 3 | car 4 | motorbike 5 | aeroplane 6 | bus 7 | train 8 | truck 9 | boat 10 | traffic light 11 | fire hydrant 12 | stop sign 13 | parking meter 14 | bench 15 | bird 16 | cat 17 | dog 18 | horse 19 | sheep 20 | cow 21 | elephant 22 | bear 23 | zebra 24 | giraffe 25 | backpack 26 | umbrella 27 | handbag 28 | tie 29 | suitcase 30 | frisbee 31 | skis 32 | snowboard 33 | sports ball 34 | kite 35 | baseball bat 36 | baseball glove 37 | skateboard 38 | surfboard 39 | tennis racket 40 | bottle 41 | wine glass 42 | cup 43 | fork 44 | knife 45 | spoon 46 | bowl 47 | banana 48 | apple 49 | sandwich 50 | orange 51 | broccoli 52 | carrot 53 | hot dog 54 | pizza 55 | donut 56 | cake 57 | chair 58 | sofa 59 | pottedplant 60 | bed 61 | diningtable 62 | toilet 63 | tvmonitor 64 | laptop 65 | mouse 66 | remote 67 | keyboard 68 | cell phone 69 | microwave 70 | oven 71 | toaster 72 | sink 73 | refrigerator 74 | book 75 | clock 76 | vase 77 | scissors 78 | teddy bear 79 | hair drier 80 | toothbrush 81 | -------------------------------------------------------------------------------- /utils/parse_config.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def parse_model_config(path): 4 | """Parses the yolo-v3 layer configuration file and returns module definitions""" 5 | file = open(path, 'r') 6 | lines = file.read().split('\n') 7 | lines = [x for x in lines if x and not x.startswith('#')] 8 | lines = [x.rstrip().lstrip() for x in lines] # get rid of fringe whitespaces 9 | module_defs = [] 10 | for line in lines: 11 | if line.startswith('['): # This marks the start of a new block 12 | module_defs.append({}) 13 | module_defs[-1]['type'] = line[1:-1].rstrip() 14 | if module_defs[-1]['type'] == 'convolutional': 15 | module_defs[-1]['batch_normalize'] = 0 16 | else: 17 | key, value = line.split("=") 18 | value = value.strip() 19 | module_defs[-1][key.rstrip()] = value.strip() 20 | 21 | return module_defs 22 | 23 | def parse_data_config(path): 24 | """Parses the data configuration file""" 25 | options = dict() 26 | options['gpus'] = '0,1,2,3' 27 | options['num_workers'] = '10' 28 | with open(path, 'r') as fp: 29 | lines = fp.readlines() 30 | for line in lines: 31 | line = line.strip() 32 | if line == '' or line.startswith('#'): 33 | continue 34 | key, value = line.split('=') 35 | options[key.strip()] = value.strip() 36 | return options 37 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # autocutpro 2 | 3 | Autonomous video editing powered by Object Tracking and Motion Detection 4 | 5 | ## What is this? 6 | The first method of video editing is through the use of **Object Tracking**. Using PyTorch, YOLOv3, and OpenCV a [deep learning model](https://github.com/abewley/sort) is made to track objects in a given video. Using this model, the user specifies which objects in a given video they would like to scan through and will then make cuts along the frames of these objects in the video and splice them together to create a new scene. 7 | 8 | The other method of video editing is by using **Motion Detection**. Each frame of a given video is compared by computing the difference between the RGB channels of each pixel and the video is cut along the given motion threshold 9 | 10 | ## How to Run: 11 | Firt clone this repositiory and then install the required dependencies (preferably in your virtual environment) with ``pip``. 12 | ``` 13 | pip install requirements.txt 14 | ``` 15 | ### Object Tracking 16 | 1. Run the shell file download_weights.sh or run 17 | ```wget https://pjreddie.com/media/files/yolov3.weights``` (only need to do this once) 18 | 2. Specify object tracking method 19 | 3. Specify a directory of the video you would like to read and specify the output directory for the edited copy. (You can also choose random to select a random object in the video for fun) 20 | 4. Once it detects objects, choose the objects from the displayed list to edit the video around 21 | ### Usage: 22 | 23 | ``` 24 | $ python3 main.py object videos/short-clip.mp4 out/test-output2.mp4 25 | ``` 26 | ### Motion Detection: 27 | 1. Specify motion algorithm 28 | 2. Provide the directory of the video you would like to read, specify what the filename and output should be and the motion threshold (Random is also an option if you want to select a random motion percentage) 29 | ### Usage: 30 | ``` 31 | $ python3 main.py motion videos/short-clip.mp4 edits/motion-test-variety-new.mp4 10 15 32 | ``` 33 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | @file: main.py 4 | @author: Nish Gowda 5 | 6 | The purpose of this file is to purely be the 7 | main pipeline between the video_splice, object_tracker, and motion_detection files. 8 | Given the inputted command line arguments, the program extends 9 | the values to the functions of the aformentioned files and 10 | executes the functions. 11 | """ 12 | 13 | from video_splice import * 14 | from object_tracker import * 15 | from motion_detection import * 16 | import sys 17 | 18 | def run_motion_detection(video_file, outpath, motion_percent): 19 | motion_detector = MotionDetection() 20 | video_splice = VideoSplice() 21 | motion_detector.compare_frames(video_file) 22 | frames = motion_detector.frames 23 | video_splice.cut_motion_video(video_file, outpath, motion_percent, frames) 24 | 25 | def run_obj_tracker(video_file, outpath): 26 | obj_tracker = ObjectTracker() 27 | video_splice = VideoSplice() 28 | obj_tracker.track_video(video_file, outpath) 29 | object_frames = obj_tracker.obj_frames 30 | print("Detected the following objects in the supplied video") 31 | print(', '.join(str(obj) for obj in set(obj_tracker.objects))) 32 | 33 | desired_objects = [] 34 | while True: 35 | resp = input("Enter the objects you want to cut along (press quit to end) ") 36 | if resp == "quit": 37 | break 38 | if resp not in set(obj_tracker.objects): 39 | desired_objects.append(resp) 40 | else: 41 | print(resp, " is not one of the options") 42 | video_splice.cut_tracker_video(video_file, outpath, desired_objects, object_frames) 43 | 44 | if __name__ == "__main__": 45 | option = sys.argv[1] 46 | if option == "motion": 47 | video_file = sys.argv[2] 48 | outpath = sys.argv[3] 49 | motion_percent = sys.argv[4:] 50 | run_motion_detection(video_file, outpath, motion_percent) 51 | elif option == "object": 52 | video_file = sys.argv[2] 53 | outpath = sys.argv[3] 54 | run_obj_tracker(video_file, outpath) 55 | else: 56 | sys.exit("You supplied an invalid option") 57 | -------------------------------------------------------------------------------- /motion_detection.py: -------------------------------------------------------------------------------- 1 | """ 2 | @file: motion_detection.py 3 | @author: Nish Gowda 4 | 5 | The purpose of this program is to compare each frame by 6 | computing the difference between their rgb values for every pixel. 7 | This is later applied to video_splice.py to connect each frame to 8 | a full video. 9 | """ 10 | import cv2 11 | import numpy as np 12 | from PIL import Image 13 | import collections 14 | from tqdm import tqdm 15 | import time 16 | 17 | class MotionDetection: 18 | def __init__(self): 19 | self.total_diff = 0.0 20 | self.frames = {} 21 | # computes the rgb value for each pixel in each frame 22 | def compare_frames(self, videopath): 23 | vid = cv2.VideoCapture(videopath) 24 | video_length = int(vid.get(cv2.CAP_PROP_FRAME_COUNT)) 25 | old_frame = None 26 | for i in tqdm(range(video_length)): 27 | ret, frame = vid.read() 28 | if not ret: 29 | break 30 | pilimg = Image.fromarray(frame) 31 | prev_frame = cv2.cvtColor(frame, cv2.COLOR_HSV2RGB) 32 | pilimg2 = Image.fromarray(prev_frame) 33 | img = np.array(pilimg) 34 | prev_img = np.array(pilimg2) 35 | 36 | img_width = img.shape[0] 37 | img_height = img.shape[1] 38 | num_pixels = img.size 39 | # compare the rgb value of each pixel between the current and previous frames 40 | diff_r, diff_g, diff_b = 0.0, 0.0, 0.0 41 | if old_frame is not None: 42 | # .split grabs the rgb (in order of grb) of the img 43 | colors_b1, colors_g1, colors_r1 = cv2.split(img) 44 | colors_b2, colors_g2, colors_r2 = cv2.split(prev_img) 45 | # grab the sums of each channels difference -- matrix or np array and divide by 255 46 | diff_r += np.sum(colors_r1 - colors_r2) / 255.0 47 | diff_g += np.sum(colors_g1 - colors_g2) / 255.0 48 | diff_b += np.sum(colors_b1 - colors_b2) / 255.0 49 | # divide each difference by num pixels to get the avg difference per chanel 50 | diff_r /= num_pixels 51 | diff_g /= num_pixels 52 | diff_b /= num_pixels 53 | # get the avg of all three channels 54 | self.total_diff = (diff_r + diff_g + diff_b) / 3.0 55 | self.total_diff = round(self.total_diff * 100) 56 | # update our dictionary to grab the difference of the current and previous frame as well as the current frame 57 | self.frames.update({self.total_diff : frame}) 58 | old_frame = prev_frame 59 | ch = 0xFF & cv2.waitKey(1) 60 | if ch == 27: 61 | break 62 | cv2.destroyAllWindows() 63 | 64 | -------------------------------------------------------------------------------- /config/yolov3-tiny.cfg: -------------------------------------------------------------------------------- 1 | [net] 2 | # Testing 3 | batch=1 4 | subdivisions=1 5 | # Training 6 | # batch=64 7 | # subdivisions=2 8 | width=416 9 | height=416 10 | channels=3 11 | momentum=0.9 12 | decay=0.0005 13 | angle=0 14 | saturation = 1.5 15 | exposure = 1.5 16 | hue=.1 17 | 18 | learning_rate=0.001 19 | burn_in=1000 20 | max_batches = 500200 21 | policy=steps 22 | steps=400000,450000 23 | scales=.1,.1 24 | 25 | # 0 26 | [convolutional] 27 | batch_normalize=1 28 | filters=16 29 | size=3 30 | stride=1 31 | pad=1 32 | activation=leaky 33 | 34 | # 1 35 | [maxpool] 36 | size=2 37 | stride=2 38 | 39 | # 2 40 | [convolutional] 41 | batch_normalize=1 42 | filters=32 43 | size=3 44 | stride=1 45 | pad=1 46 | activation=leaky 47 | 48 | # 3 49 | [maxpool] 50 | size=2 51 | stride=2 52 | 53 | # 4 54 | [convolutional] 55 | batch_normalize=1 56 | filters=64 57 | size=3 58 | stride=1 59 | pad=1 60 | activation=leaky 61 | 62 | # 5 63 | [maxpool] 64 | size=2 65 | stride=2 66 | 67 | # 6 68 | [convolutional] 69 | batch_normalize=1 70 | filters=128 71 | size=3 72 | stride=1 73 | pad=1 74 | activation=leaky 75 | 76 | # 7 77 | [maxpool] 78 | size=2 79 | stride=2 80 | 81 | # 8 82 | [convolutional] 83 | batch_normalize=1 84 | filters=256 85 | size=3 86 | stride=1 87 | pad=1 88 | activation=leaky 89 | 90 | # 9 91 | [maxpool] 92 | size=2 93 | stride=2 94 | 95 | # 10 96 | [convolutional] 97 | batch_normalize=1 98 | filters=512 99 | size=3 100 | stride=1 101 | pad=1 102 | activation=leaky 103 | 104 | # 11 105 | [maxpool] 106 | size=2 107 | stride=1 108 | 109 | # 12 110 | [convolutional] 111 | batch_normalize=1 112 | filters=1024 113 | size=3 114 | stride=1 115 | pad=1 116 | activation=leaky 117 | 118 | ########### 119 | 120 | # 13 121 | [convolutional] 122 | batch_normalize=1 123 | filters=256 124 | size=1 125 | stride=1 126 | pad=1 127 | activation=leaky 128 | 129 | # 14 130 | [convolutional] 131 | batch_normalize=1 132 | filters=512 133 | size=3 134 | stride=1 135 | pad=1 136 | activation=leaky 137 | 138 | # 15 139 | [convolutional] 140 | size=1 141 | stride=1 142 | pad=1 143 | filters=255 144 | activation=linear 145 | 146 | 147 | 148 | # 16 149 | [yolo] 150 | mask = 3,4,5 151 | anchors = 10,14, 23,27, 37,58, 81,82, 135,169, 344,319 152 | classes=80 153 | num=6 154 | jitter=.3 155 | ignore_thresh = .7 156 | truth_thresh = 1 157 | random=1 158 | 159 | # 17 160 | [route] 161 | layers = -4 162 | 163 | # 18 164 | [convolutional] 165 | batch_normalize=1 166 | filters=128 167 | size=1 168 | stride=1 169 | pad=1 170 | activation=leaky 171 | 172 | # 19 173 | [upsample] 174 | stride=2 175 | 176 | # 20 177 | [route] 178 | layers = -1, 8 179 | 180 | # 21 181 | [convolutional] 182 | batch_normalize=1 183 | filters=256 184 | size=3 185 | stride=1 186 | pad=1 187 | activation=leaky 188 | 189 | # 22 190 | [convolutional] 191 | size=1 192 | stride=1 193 | pad=1 194 | filters=255 195 | activation=linear 196 | 197 | # 23 198 | [yolo] 199 | mask = 1,2,3 200 | anchors = 10,14, 23,27, 37,58, 81,82, 135,169, 344,319 201 | classes=80 202 | num=6 203 | jitter=.3 204 | ignore_thresh = .7 205 | truth_thresh = 1 206 | random=1 207 | -------------------------------------------------------------------------------- /utils/datasets.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import random 3 | import os 4 | import numpy as np 5 | 6 | import torch 7 | 8 | from torch.utils.data import Dataset 9 | from PIL import Image 10 | import torchvision.transforms as transforms 11 | 12 | ##import matplotlib.pyplot as plt 13 | ##import matplotlib.patches as patches 14 | 15 | from skimage.transform import resize 16 | 17 | import sys 18 | 19 | class ImageFolder(Dataset): 20 | def __init__(self, folder_path, img_size=416): 21 | self.files = sorted(glob.glob('%s/*.*' % folder_path)) 22 | self.img_shape = (img_size, img_size) 23 | 24 | def __getitem__(self, index): 25 | img_path = self.files[index % len(self.files)] 26 | # Extract image 27 | img = np.array(Image.open(img_path)) 28 | h, w, _ = img.shape 29 | dim_diff = np.abs(h - w) 30 | # Upper (left) and lower (right) padding 31 | pad1, pad2 = dim_diff // 2, dim_diff - dim_diff // 2 32 | # Determine padding 33 | pad = ((pad1, pad2), (0, 0), (0, 0)) if h <= w else ((0, 0), (pad1, pad2), (0, 0)) 34 | # Add padding 35 | input_img = np.pad(img, pad, 'constant', constant_values=127.5) / 255. 36 | # Resize and normalize 37 | input_img = resize(input_img, (*self.img_shape, 3), mode='reflect') 38 | # Channels-first 39 | input_img = np.transpose(input_img, (2, 0, 1)) 40 | # As pytorch tensor 41 | input_img = torch.from_numpy(input_img).float() 42 | 43 | return img_path, input_img 44 | 45 | def __len__(self): 46 | return len(self.files) 47 | 48 | 49 | class ListDataset(Dataset): 50 | def __init__(self, list_path, img_size=416): 51 | with open(list_path, 'r') as file: 52 | self.img_files = file.readlines() 53 | self.label_files = [path.replace('images', 'labels').replace('.png', '.txt').replace('.jpg', '.txt') for path in self.img_files] 54 | self.img_shape = (img_size, img_size) 55 | self.max_objects = 50 56 | 57 | def __getitem__(self, index): 58 | 59 | #--------- 60 | # Image 61 | #--------- 62 | 63 | img_path = self.img_files[index % len(self.img_files)].rstrip() 64 | img = np.array(Image.open(img_path)) 65 | 66 | # Handles images with less than three channels 67 | while len(img.shape) != 3: 68 | index += 1 69 | img_path = self.img_files[index % len(self.img_files)].rstrip() 70 | img = np.array(Image.open(img_path)) 71 | 72 | h, w, _ = img.shape 73 | dim_diff = np.abs(h - w) 74 | # Upper (left) and lower (right) padding 75 | pad1, pad2 = dim_diff // 2, dim_diff - dim_diff // 2 76 | # Determine padding 77 | pad = ((pad1, pad2), (0, 0), (0, 0)) if h <= w else ((0, 0), (pad1, pad2), (0, 0)) 78 | # Add padding 79 | input_img = np.pad(img, pad, 'constant', constant_values=128) / 255. 80 | padded_h, padded_w, _ = input_img.shape 81 | # Resize and normalize 82 | input_img = resize(input_img, (*self.img_shape, 3), mode='reflect') 83 | # Channels-first 84 | input_img = np.transpose(input_img, (2, 0, 1)) 85 | # As pytorch tensor 86 | input_img = torch.from_numpy(input_img).float() 87 | 88 | #--------- 89 | # Label 90 | #--------- 91 | 92 | label_path = self.label_files[index % len(self.img_files)].rstrip() 93 | 94 | labels = None 95 | if os.path.exists(label_path): 96 | labels = np.loadtxt(label_path).reshape(-1, 5) 97 | # Extract coordinates for unpadded + unscaled image 98 | x1 = w * (labels[:, 1] - labels[:, 3]/2) 99 | y1 = h * (labels[:, 2] - labels[:, 4]/2) 100 | x2 = w * (labels[:, 1] + labels[:, 3]/2) 101 | y2 = h * (labels[:, 2] + labels[:, 4]/2) 102 | # Adjust for added padding 103 | x1 += pad[1][0] 104 | y1 += pad[0][0] 105 | x2 += pad[1][0] 106 | y2 += pad[0][0] 107 | # Calculate ratios from coordinates 108 | labels[:, 1] = ((x1 + x2) / 2) / padded_w 109 | labels[:, 2] = ((y1 + y2) / 2) / padded_h 110 | labels[:, 3] *= w / padded_w 111 | labels[:, 4] *= h / padded_h 112 | # Fill matrix 113 | filled_labels = np.zeros((self.max_objects, 5)) 114 | if labels is not None: 115 | filled_labels[range(len(labels))[:self.max_objects]] = labels[:self.max_objects] 116 | filled_labels = torch.from_numpy(filled_labels) 117 | 118 | return img_path, input_img, filled_labels 119 | 120 | def __len__(self): 121 | return len(self.img_files) 122 | -------------------------------------------------------------------------------- /video_splice.py: -------------------------------------------------------------------------------- 1 | """ 2 | @file: video_slice.py 3 | @author: Nish Gowda 4 | 5 | This selects the frames of the selected objects or motion 6 | and splices them together to create a new scene of 7 | the video. This is meant to be built on top of the object_tracker.py 8 | and motion_detection.py files. 9 | """ 10 | from models import * 11 | import utils 12 | from object_tracker import ObjectTracker 13 | from motion_detection import MotionDetection 14 | import os, sys, time, datetime, random 15 | import torch 16 | from torch.utils.data import DataLoader 17 | from torchvision import datasets, transforms 18 | from torch.autograd import Variable 19 | from datetime import datetime 20 | from collections import defaultdict 21 | from PIL import Image 22 | import cv2 23 | import sort 24 | 25 | class VideoSplice: 26 | def __init__(self): 27 | self.split = "\n------------------------------------" 28 | # stitches together the frames of the targeted objects to create a sequence 29 | def cut_tracker_video(self, videopath, outpath, object_list, obj_frames): 30 | vid = cv2.VideoCapture(videopath) 31 | old_vid_length = int(vid.get(cv2.CAP_PROP_FRAME_COUNT)) 32 | vid.set(cv2.CAP_PROP_BUFFERSIZE, 2) 33 | # fourcc = cv2.VideoWriter_fourcc(*'XVID') 34 | ret,frame=vid.read() 35 | vw = frame.shape[1] 36 | vh = frame.shape[0] 37 | filepath = outpath 38 | fourcc = cv2.VideoWriter_fourcc(*'XVID') 39 | outvideo = cv2.VideoWriter(filepath, fourcc, 20.0, (vw, vh)) 40 | 41 | if "random" in object_list: 42 | obj = random.choice(list(obj_frames)) 43 | for frames in obj_frames.get(obj): 44 | outvideo.write(frames) 45 | else: 46 | for obj in object_list: 47 | if obj in obj_frames: 48 | # grab the frame from the dictionary and write it to the out video 49 | for frames in obj_frames.get(obj): 50 | outvideo.write(frames) 51 | else: 52 | print(f"{obj} is not detected") 53 | ch = 0xFF & cv2.waitKey(1) 54 | if ch == 27: 55 | break 56 | cv2.destroyAllWindows() 57 | outvideo.release() 58 | new_video = cv2.VideoCapture(filepath) 59 | new_video_length = int(new_video.get(cv2.CAP_PROP_FRAME_COUNT)) 60 | percent_edited = (((old_vid_length - new_video_length) / old_vid_length) * 100) 61 | print(self.split) 62 | print("Edited out {:.0f}% of source video".format(percent_edited)) 63 | print(self.split) 64 | print("Saved edited video to output file as ", filepath) 65 | 66 | 67 | # Stitches together the the frames that have a motion threshold of greater than or equal to the input to create a sequence. 68 | def cut_motion_video(self, videopath, outpath, motion_percent, frames): 69 | vid = cv2.VideoCapture(videopath) 70 | vid.set(cv2.CAP_PROP_BUFFERSIZE, 2) 71 | old_vid_length = int(vid.get(cv2.CAP_PROP_FRAME_COUNT)) 72 | ret,frame=vid.read() 73 | vw = frame.shape[1] 74 | vh = frame.shape[0] 75 | filepath = outpath 76 | fourcc = cv2.VideoWriter_fourcc(*'XVID') 77 | outvideo = cv2.VideoWriter(filepath,fourcc,20.0,(vw,vh)) 78 | edited_frames = [] 79 | print(motion_percent) 80 | if "random" in motion_percent: 81 | for avg_frame, frame in frames.items(): 82 | top_percent = (avg_frame / len(frames)) * 100 83 | compared_percent1 = random.randint(1,99) 84 | compared_percent2 = random.randint(compared_percent1,100) 85 | if top_percent >= float(compared_percent1) or top_percent <= float(compared_percent2): 86 | edited_frames.append(avg_frame) 87 | edited_frames = list(set(edited_frames)) # ensures that there are no duplicate frames in list 88 | else: 89 | for avg_frame, frame in frames.items(): 90 | # calculates what percentage of the values each frame belongs to 91 | top_percent = (avg_frame / len(frames)) * 100 92 | if top_percent >= float(motion_percent[0]) or top_percent <= float(top_percent[1]): 93 | edited_frames.append(avg_frame) 94 | edited_frames = list(set(edited_frames)) # ensures that there are no duplicate frames in list 95 | for percent_frame in edited_frames: 96 | # grab the frames from the dictionary in motion_detection algorithm and write it to the video 97 | outvideo.write(frames.get(percent_frame)) 98 | ch = 0xFF & cv2.waitKey(1) 99 | if ch == 27: 100 | break 101 | cv2.destroyAllWindows() 102 | outvideo.release() 103 | new_video = cv2.VideoCapture(filepath) 104 | new_video_length = int(new_video.get(cv2.CAP_PROP_FRAME_COUNT)) 105 | percent_edited = (((old_vid_length - new_video_length) / old_vid_length) * 100) 106 | print(self.split) 107 | print("Edited out: {:.0f}% of source video".format(percent_edited)) 108 | print(self.split) 109 | print("Saved edited video to: ", filepath) 110 | 111 | -------------------------------------------------------------------------------- /object_tracker.py: -------------------------------------------------------------------------------- 1 | """ 2 | @file: object_tracker.py 3 | @author: Nish Gowda 4 | 5 | The purpose of this file is to detect the objects 6 | in each frame of a given video. The detect image function 7 | uses the sort and model file to detect images that are 8 | within the model class in a given frame. With that, it stores the 9 | contents of the detected object and the frames that object 10 | is located in a dictionary that is then used in the video_slice 11 | file. 12 | """ 13 | from models import * 14 | from utils import * 15 | 16 | import os, sys, time, datetime, random 17 | import torch 18 | from torch.utils.data import DataLoader 19 | from torchvision import datasets, transforms 20 | from torch.autograd import Variable 21 | from datetime import datetime 22 | from collections import defaultdict 23 | from PIL import Image 24 | import cv2 25 | from sort import * 26 | from tqdm import tqdm 27 | 28 | # load weights and set defaults 29 | config_path="config/yolov3.cfg" 30 | weights_path="config/yolov3.weights" 31 | class_path="config/coco.names" 32 | img_size=416 33 | conf_thres=0.8 34 | nms_thres=0.4 35 | 36 | # load model and put into eval mode 37 | model = Darknet(config_path, img_size=img_size) 38 | model.load_weights(weights_path) 39 | model.eval() 40 | 41 | classes = utils.load_classes(class_path) 42 | Tensor = torch.FloatTensor 43 | 44 | class ObjectTracker: 45 | def __init__(self): 46 | self.objects = [] # stores a list of objects found in video 47 | self.obj_frames = {} # stores the frames with the object names 48 | 49 | def detect_image(self, img): 50 | # scale and pad image 51 | ratio = min(img_size/img.size[0], img_size/img.size[1]) 52 | imw = round(img.size[0] * ratio) 53 | imh = round(img.size[1] * ratio) 54 | img_transforms = transforms.Compose([ transforms.Resize((imh, imw)), 55 | transforms.Pad((max(int((imh-imw)/2),0), max(int((imw-imh)/2),0), max(int((imh-imw)/2),0), max(int((imw-imh)/2),0)), 56 | (128,128,128)), 57 | transforms.ToTensor(), 58 | ]) 59 | # convert image to Tensor 60 | image_tensor = img_transforms(img).float() 61 | image_tensor = image_tensor.unsqueeze_(0) 62 | input_img = Variable(image_tensor.type(Tensor)) 63 | # run inference on the model and get detections 64 | with torch.no_grad(): 65 | detections = model(input_img) 66 | detections = utils.non_max_suppression(detections, 80, conf_thres, nms_thres) 67 | return detections[0] 68 | 69 | def track_video(self, video_file, outpath): 70 | videopath = str(video_file) 71 | # color palete for boxes 72 | colors=[(255,0,0),(0,255,0),(0,0,255),(255,0,255),(128,0,0),(0,128,0),(0,0,128),(128,0,128),(128,128,0),(0,128,128)] 73 | vid = cv2.VideoCapture(videopath) 74 | vid.set(cv2.CAP_PROP_BUFFERSIZE, 2) 75 | mot_tracker = Sort() 76 | 77 | fourcc = cv2.VideoWriter_fourcc(*'XVID') 78 | ret,frame=vid.read() 79 | vw = frame.shape[1] 80 | vh = frame.shape[0] 81 | video_length = int(vid.get(cv2.CAP_PROP_FRAME_COUNT)) 82 | outvideo = cv2.VideoWriter(outpath,fourcc,20.0,(vw,vh)) 83 | frames = 0 84 | starttime = time.time() 85 | for i in tqdm(range(video_length)): 86 | ret, frame = vid.read() 87 | if not ret: 88 | break 89 | frames += 1 90 | frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) 91 | pilimg = Image.fromarray(frame) 92 | detections = self.detect_image(pilimg) 93 | 94 | frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) 95 | img = np.array(pilimg) 96 | pad_x = max(img.shape[0] - img.shape[1], 0) * (img_size / max(img.shape)) 97 | pad_y = max(img.shape[1] - img.shape[0], 0) * (img_size / max(img.shape)) 98 | unpad_h = img_size - pad_y 99 | unpad_w = img_size - pad_x 100 | if detections is not None: 101 | tracked_objects = mot_tracker.update(detections.cpu()) 102 | unique_labels = detections[:, -1].cpu().unique() 103 | n_cls_preds = len(unique_labels) 104 | for x1, y1, x2, y2, obj_id, cls_pred in tracked_objects: 105 | cls = classes[int(cls_pred)] 106 | obj = f"{cls}-{obj_id}" # The identity of the objects found 107 | self.objects.append(obj) # append to list of objects; later used in displaying to user 108 | # setdefault allow all the frames that an object exists in to be appended to that 109 | # object in the dictionary. 110 | self.obj_frames.setdefault(obj, []).append(frame) 111 | # Note we don't add the boexes to the frames here like you would normally do. 112 | # Only want the frames so we can later splice them together to make a video 113 | outvideo.write(frame) 114 | ch = 0xFF & cv2.waitKey(1) 115 | if ch == 27: 116 | break 117 | totaltime = time.time()-starttime 118 | print(frames, " frames {:.2f}s/frame".format(totaltime/frames)) 119 | print("Saved file as " + str(outpath)) 120 | cv2.destroyAllWindows() 121 | outvideo.release() 122 | 123 | -------------------------------------------------------------------------------- /utils/utils.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import math 3 | import time 4 | import torch 5 | import torch.nn as nn 6 | import torch.nn.functional as F 7 | from torch.autograd import Variable 8 | import numpy as np 9 | 10 | #import matplotlib.pyplot as plt 11 | #import matplotlib.patches as patches 12 | 13 | 14 | def load_classes(path): 15 | """ 16 | Loads class labels at 'path' 17 | """ 18 | fp = open(path, "r") 19 | names = fp.read().split("\n")[:-1] 20 | return names 21 | 22 | 23 | def weights_init_normal(m): 24 | classname = m.__class__.__name__ 25 | if classname.find("Conv") != -1: 26 | torch.nn.init.normal_(m.weight.data, 0.0, 0.02) 27 | elif classname.find("BatchNorm2d") != -1: 28 | torch.nn.init.normal_(m.weight.data, 1.0, 0.02) 29 | torch.nn.init.constant_(m.bias.data, 0.0) 30 | 31 | 32 | def compute_ap(recall, precision): 33 | """ Compute the average precision, given the recall and precision curves. 34 | Code originally from https://github.com/rbgirshick/py-faster-rcnn. 35 | 36 | # Arguments 37 | recall: The recall curve (list). 38 | precision: The precision curve (list). 39 | # Returns 40 | The average precision as computed in py-faster-rcnn. 41 | """ 42 | # correct AP calculation 43 | # first append sentinel values at the end 44 | mrec = np.concatenate(([0.0], recall, [1.0])) 45 | mpre = np.concatenate(([0.0], precision, [0.0])) 46 | 47 | # compute the precision envelope 48 | for i in range(mpre.size - 1, 0, -1): 49 | mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) 50 | 51 | # to calculate area under PR curve, look for points 52 | # where X axis (recall) changes value 53 | i = np.where(mrec[1:] != mrec[:-1])[0] 54 | 55 | # and sum (\Delta recall) * prec 56 | ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) 57 | return ap 58 | 59 | 60 | def bbox_iou(box1, box2, x1y1x2y2=True): 61 | """ 62 | Returns the IoU of two bounding boxes 63 | """ 64 | if not x1y1x2y2: 65 | # Transform from center and width to exact coordinates 66 | b1_x1, b1_x2 = box1[:, 0] - box1[:, 2] / 2, box1[:, 0] + box1[:, 2] / 2 67 | b1_y1, b1_y2 = box1[:, 1] - box1[:, 3] / 2, box1[:, 1] + box1[:, 3] / 2 68 | b2_x1, b2_x2 = box2[:, 0] - box2[:, 2] / 2, box2[:, 0] + box2[:, 2] / 2 69 | b2_y1, b2_y2 = box2[:, 1] - box2[:, 3] / 2, box2[:, 1] + box2[:, 3] / 2 70 | else: 71 | # Get the coordinates of bounding boxes 72 | b1_x1, b1_y1, b1_x2, b1_y2 = box1[:, 0], box1[:, 1], box1[:, 2], box1[:, 3] 73 | b2_x1, b2_y1, b2_x2, b2_y2 = box2[:, 0], box2[:, 1], box2[:, 2], box2[:, 3] 74 | 75 | # get the corrdinates of the intersection rectangle 76 | inter_rect_x1 = torch.max(b1_x1, b2_x1) 77 | inter_rect_y1 = torch.max(b1_y1, b2_y1) 78 | inter_rect_x2 = torch.min(b1_x2, b2_x2) 79 | inter_rect_y2 = torch.min(b1_y2, b2_y2) 80 | # Intersection area 81 | inter_area = torch.clamp(inter_rect_x2 - inter_rect_x1 + 1, min=0) * torch.clamp( 82 | inter_rect_y2 - inter_rect_y1 + 1, min=0 83 | ) 84 | # Union Area 85 | b1_area = (b1_x2 - b1_x1 + 1) * (b1_y2 - b1_y1 + 1) 86 | b2_area = (b2_x2 - b2_x1 + 1) * (b2_y2 - b2_y1 + 1) 87 | 88 | iou = inter_area / (b1_area + b2_area - inter_area + 1e-16) 89 | 90 | return iou 91 | 92 | 93 | def bbox_iou_numpy(box1, box2): 94 | """Computes IoU between bounding boxes. 95 | Parameters 96 | ---------- 97 | box1 : ndarray 98 | (N, 4) shaped array with bboxes 99 | box2 : ndarray 100 | (M, 4) shaped array with bboxes 101 | Returns 102 | ------- 103 | : ndarray 104 | (N, M) shaped array with IoUs 105 | """ 106 | area = (box2[:, 2] - box2[:, 0]) * (box2[:, 3] - box2[:, 1]) 107 | 108 | iw = np.minimum(np.expand_dims(box1[:, 2], axis=1), box2[:, 2]) - np.maximum( 109 | np.expand_dims(box1[:, 0], 1), box2[:, 0] 110 | ) 111 | ih = np.minimum(np.expand_dims(box1[:, 3], axis=1), box2[:, 3]) - np.maximum( 112 | np.expand_dims(box1[:, 1], 1), box2[:, 1] 113 | ) 114 | 115 | iw = np.maximum(iw, 0) 116 | ih = np.maximum(ih, 0) 117 | 118 | ua = np.expand_dims((box1[:, 2] - box1[:, 0]) * (box1[:, 3] - box1[:, 1]), axis=1) + area - iw * ih 119 | 120 | ua = np.maximum(ua, np.finfo(float).eps) 121 | 122 | intersection = iw * ih 123 | 124 | return intersection / ua 125 | 126 | 127 | def non_max_suppression(prediction, num_classes, conf_thres=0.5, nms_thres=0.4): 128 | """ 129 | Removes detections with lower object confidence score than 'conf_thres' and performs 130 | Non-Maximum Suppression to further filter detections. 131 | Returns detections with shape: 132 | (x1, y1, x2, y2, object_conf, class_score, class_pred) 133 | """ 134 | 135 | # From (center x, center y, width, height) to (x1, y1, x2, y2) 136 | box_corner = prediction.new(prediction.shape) 137 | box_corner[:, :, 0] = prediction[:, :, 0] - prediction[:, :, 2] / 2 138 | box_corner[:, :, 1] = prediction[:, :, 1] - prediction[:, :, 3] / 2 139 | box_corner[:, :, 2] = prediction[:, :, 0] + prediction[:, :, 2] / 2 140 | box_corner[:, :, 3] = prediction[:, :, 1] + prediction[:, :, 3] / 2 141 | prediction[:, :, :4] = box_corner[:, :, :4] 142 | 143 | output = [None for _ in range(len(prediction))] 144 | for image_i, image_pred in enumerate(prediction): 145 | # Filter out confidence scores below threshold 146 | conf_mask = (image_pred[:, 4] >= conf_thres).squeeze() 147 | image_pred = image_pred[conf_mask] 148 | # If none are remaining => process next image 149 | if not image_pred.size(0): 150 | continue 151 | # Get score and class with highest confidence 152 | class_conf, class_pred = torch.max(image_pred[:, 5 : 5 + num_classes], 1, keepdim=True) 153 | # Detections ordered as (x1, y1, x2, y2, obj_conf, class_conf, class_pred) 154 | detections = torch.cat((image_pred[:, :5], class_conf.float(), class_pred.float()), 1) 155 | # Iterate through all predicted classes 156 | unique_labels = detections[:, -1].cpu().unique() 157 | if prediction.is_cuda: 158 | unique_labels = unique_labels.cuda() 159 | for c in unique_labels: 160 | # Get the detections with the particular class 161 | detections_class = detections[detections[:, -1] == c] 162 | # Sort the detections by maximum objectness confidence 163 | _, conf_sort_index = torch.sort(detections_class[:, 4], descending=True) 164 | detections_class = detections_class[conf_sort_index] 165 | # Perform non-maximum suppression 166 | max_detections = [] 167 | while detections_class.size(0): 168 | # Get detection with highest confidence and save as max detection 169 | max_detections.append(detections_class[0].unsqueeze(0)) 170 | # Stop if we're at the last detection 171 | if len(detections_class) == 1: 172 | break 173 | # Get the IOUs for all boxes with lower confidence 174 | ious = bbox_iou(max_detections[-1], detections_class[1:]) 175 | # Remove detections with IoU >= NMS threshold 176 | detections_class = detections_class[1:][ious < nms_thres] 177 | 178 | max_detections = torch.cat(max_detections).data 179 | # Add max detections to outputs 180 | output[image_i] = ( 181 | max_detections if output[image_i] is None else torch.cat((output[image_i], max_detections)) 182 | ) 183 | 184 | return output 185 | 186 | 187 | def build_targets( 188 | pred_boxes, pred_conf, pred_cls, target, anchors, num_anchors, num_classes, grid_size, ignore_thres, img_dim 189 | ): 190 | nB = target.size(0) 191 | nA = num_anchors 192 | nC = num_classes 193 | nG = grid_size 194 | mask = torch.zeros(nB, nA, nG, nG) 195 | conf_mask = torch.ones(nB, nA, nG, nG) 196 | tx = torch.zeros(nB, nA, nG, nG) 197 | ty = torch.zeros(nB, nA, nG, nG) 198 | tw = torch.zeros(nB, nA, nG, nG) 199 | th = torch.zeros(nB, nA, nG, nG) 200 | tconf = torch.ByteTensor(nB, nA, nG, nG).fill_(0) 201 | tcls = torch.ByteTensor(nB, nA, nG, nG, nC).fill_(0) 202 | 203 | nGT = 0 204 | nCorrect = 0 205 | for b in range(nB): 206 | for t in range(target.shape[1]): 207 | if target[b, t].sum() == 0: 208 | continue 209 | nGT += 1 210 | # Convert to position relative to box 211 | gx = target[b, t, 1] * nG 212 | gy = target[b, t, 2] * nG 213 | gw = target[b, t, 3] * nG 214 | gh = target[b, t, 4] * nG 215 | # Get grid box indices 216 | gi = int(gx) 217 | gj = int(gy) 218 | # Get shape of gt box 219 | gt_box = torch.FloatTensor(np.array([0, 0, gw, gh])).unsqueeze(0) 220 | # Get shape of anchor box 221 | anchor_shapes = torch.FloatTensor(np.concatenate((np.zeros((len(anchors), 2)), np.array(anchors)), 1)) 222 | # Calculate iou between gt and anchor shapes 223 | anch_ious = bbox_iou(gt_box, anchor_shapes) 224 | # Where the overlap is larger than threshold set mask to zero (ignore) 225 | conf_mask[b, anch_ious > ignore_thres, gj, gi] = 0 226 | # Find the best matching anchor box 227 | best_n = np.argmax(anch_ious) 228 | # Get ground truth box 229 | gt_box = torch.FloatTensor(np.array([gx, gy, gw, gh])).unsqueeze(0) 230 | # Get the best prediction 231 | pred_box = pred_boxes[b, best_n, gj, gi].unsqueeze(0) 232 | # Masks 233 | mask[b, best_n, gj, gi] = 1 234 | conf_mask[b, best_n, gj, gi] = 1 235 | # Coordinates 236 | tx[b, best_n, gj, gi] = gx - gi 237 | ty[b, best_n, gj, gi] = gy - gj 238 | # Width and height 239 | tw[b, best_n, gj, gi] = math.log(gw / anchors[best_n][0] + 1e-16) 240 | th[b, best_n, gj, gi] = math.log(gh / anchors[best_n][1] + 1e-16) 241 | # One-hot encoding of label 242 | target_label = int(target[b, t, 0]) 243 | tcls[b, best_n, gj, gi, target_label] = 1 244 | tconf[b, best_n, gj, gi] = 1 245 | 246 | # Calculate iou between ground truth and best matching prediction 247 | iou = bbox_iou(gt_box, pred_box, x1y1x2y2=False) 248 | pred_label = torch.argmax(pred_cls[b, best_n, gj, gi]) 249 | score = pred_conf[b, best_n, gj, gi] 250 | if iou > 0.5 and pred_label == target_label and score > 0.5: 251 | nCorrect += 1 252 | 253 | return nGT, nCorrect, mask, conf_mask, tx, ty, tw, th, tconf, tcls 254 | 255 | 256 | def to_categorical(y, num_classes): 257 | """ 1-hot encodes a tensor """ 258 | return torch.from_numpy(np.eye(num_classes, dtype="uint8")[y]) 259 | -------------------------------------------------------------------------------- /sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | SORT: A Simple, Online and Realtime Tracker 3 | Copyright (C) 2016 Alex Bewley alex@dynamicdetection.com 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | """ 18 | from __future__ import print_function 19 | 20 | from numba import jit 21 | import os.path 22 | import numpy as np 23 | ##import matplotlib.pyplot as plt 24 | ##import matplotlib.patches as patches 25 | from skimage import io 26 | from sklearn.utils.linear_assignment_ import linear_assignment 27 | import glob 28 | import time 29 | import argparse 30 | from filterpy.kalman import KalmanFilter 31 | 32 | @jit 33 | def iou(bb_test,bb_gt): 34 | """ 35 | Computes IUO between two bboxes in the form [x1,y1,x2,y2] 36 | """ 37 | xx1 = np.maximum(bb_test[0], bb_gt[0]) 38 | yy1 = np.maximum(bb_test[1], bb_gt[1]) 39 | xx2 = np.minimum(bb_test[2], bb_gt[2]) 40 | yy2 = np.minimum(bb_test[3], bb_gt[3]) 41 | w = np.maximum(0., xx2 - xx1) 42 | h = np.maximum(0., yy2 - yy1) 43 | wh = w * h 44 | o = wh / ((bb_test[2]-bb_test[0])*(bb_test[3]-bb_test[1]) 45 | + (bb_gt[2]-bb_gt[0])*(bb_gt[3]-bb_gt[1]) - wh) 46 | return(o) 47 | 48 | def convert_bbox_to_z(bbox): 49 | """ 50 | Takes a bounding box in the form [x1,y1,x2,y2] and returns z in the form 51 | [x,y,s,r] where x,y is the centre of the box and s is the scale/area and r is 52 | the aspect ratio 53 | """ 54 | w = bbox[2]-bbox[0] 55 | h = bbox[3]-bbox[1] 56 | x = bbox[0]+w/2. 57 | y = bbox[1]+h/2. 58 | s = w*h #scale is just area 59 | r = w/float(h) 60 | return np.array([x,y,s,r]).reshape((4,1)) 61 | 62 | def convert_x_to_bbox(x,score=None): 63 | """ 64 | Takes a bounding box in the centre form [x,y,s,r] and returns it in the form 65 | [x1,y1,x2,y2] where x1,y1 is the top left and x2,y2 is the bottom right 66 | """ 67 | w = np.sqrt(x[2]*x[3]) 68 | h = x[2]/w 69 | if(score==None): 70 | return np.array([x[0]-w/2.,x[1]-h/2.,x[0]+w/2.,x[1]+h/2.]).reshape((1,4)) 71 | else: 72 | return np.array([x[0]-w/2.,x[1]-h/2.,x[0]+w/2.,x[1]+h/2.,score]).reshape((1,5)) 73 | 74 | 75 | class KalmanBoxTracker(object): 76 | """ 77 | This class represents the internel state of individual tracked objects observed as bbox. 78 | """ 79 | count = 0 80 | def __init__(self,bbox): 81 | """ 82 | Initialises a tracker using initial bounding box. 83 | """ 84 | #define constant velocity model 85 | self.kf = KalmanFilter(dim_x=7, dim_z=4) 86 | self.kf.F = np.array([[1,0,0,0,1,0,0],[0,1,0,0,0,1,0],[0,0,1,0,0,0,1],[0,0,0,1,0,0,0], [0,0,0,0,1,0,0],[0,0,0,0,0,1,0],[0,0,0,0,0,0,1]]) 87 | self.kf.H = np.array([[1,0,0,0,0,0,0],[0,1,0,0,0,0,0],[0,0,1,0,0,0,0],[0,0,0,1,0,0,0]]) 88 | 89 | self.kf.R[2:,2:] *= 10. 90 | self.kf.P[4:,4:] *= 1000. #give high uncertainty to the unobservable initial velocities 91 | self.kf.P *= 10. 92 | self.kf.Q[-1,-1] *= 0.01 93 | self.kf.Q[4:,4:] *= 0.01 94 | 95 | self.kf.x[:4] = convert_bbox_to_z(bbox) 96 | self.time_since_update = 0 97 | self.id = KalmanBoxTracker.count 98 | KalmanBoxTracker.count += 1 99 | self.history = [] 100 | self.hits = 0 101 | self.hit_streak = 0 102 | self.age = 0 103 | self.objclass = bbox[6] 104 | 105 | def update(self,bbox): 106 | """ 107 | Updates the state vector with observed bbox. 108 | """ 109 | self.time_since_update = 0 110 | self.history = [] 111 | self.hits += 1 112 | self.hit_streak += 1 113 | self.kf.update(convert_bbox_to_z(bbox)) 114 | 115 | def predict(self): 116 | """ 117 | Advances the state vector and returns the predicted bounding box estimate. 118 | """ 119 | if((self.kf.x[6]+self.kf.x[2])<=0): 120 | self.kf.x[6] *= 0.0 121 | self.kf.predict() 122 | self.age += 1 123 | if(self.time_since_update>0): 124 | self.hit_streak = 0 125 | self.time_since_update += 1 126 | self.history.append(convert_x_to_bbox(self.kf.x)) 127 | return self.history[-1] 128 | 129 | def get_state(self): 130 | """ 131 | Returns the current bounding box estimate. 132 | """ 133 | return convert_x_to_bbox(self.kf.x) 134 | 135 | def associate_detections_to_trackers(detections,trackers,iou_threshold = 0.3): 136 | """ 137 | Assigns detections to tracked object (both represented as bounding boxes) 138 | 139 | Returns 3 lists of matches, unmatched_detections and unmatched_trackers 140 | """ 141 | if(len(trackers)==0): 142 | return np.empty((0,2),dtype=int), np.arange(len(detections)), np.empty((0,5),dtype=int) 143 | iou_matrix = np.zeros((len(detections),len(trackers)),dtype=np.float32) 144 | 145 | for d,det in enumerate(detections): 146 | for t,trk in enumerate(trackers): 147 | iou_matrix[d,t] = iou(det,trk) 148 | matched_indices = linear_assignment(-iou_matrix) 149 | 150 | unmatched_detections = [] 151 | for d,det in enumerate(detections): 152 | if(d not in matched_indices[:,0]): 153 | unmatched_detections.append(d) 154 | unmatched_trackers = [] 155 | for t,trk in enumerate(trackers): 156 | if(t not in matched_indices[:,1]): 157 | unmatched_trackers.append(t) 158 | 159 | #filter out matched with low IOU 160 | matches = [] 161 | for m in matched_indices: 162 | if(iou_matrix[m[0],m[1]]= self.min_hits or self.frame_count <= self.min_hits)): 224 | ret.append(np.concatenate((d,[trk.id+1], [trk.objclass])).reshape(1,-1)) # +1 as MOT benchmark requires positive 225 | i -= 1 226 | #remove dead tracklet 227 | if(trk.time_since_update > self.max_age): 228 | self.trackers.pop(i) 229 | if(len(ret)>0): 230 | return np.concatenate(ret) 231 | return np.empty((0,5)) 232 | 233 | def parse_args(): 234 | """Parse input arguments.""" 235 | parser = argparse.ArgumentParser(description='SORT demo') 236 | parser.add_argument('--display', dest='display', help='Display online tracker output (slow) [False]',action='store_true') 237 | args = parser.parse_args() 238 | return args 239 | 240 | if __name__ == '__main__': 241 | # all train 242 | sequences = ['PETS09-S2L1','TUD-Campus','TUD-Stadtmitte','ETH-Bahnhof','ETH-Sunnyday','ETH-Pedcross2','KITTI-13','KITTI-17','ADL-Rundle-6','ADL-Rundle-8','Venice-2'] 243 | args = parse_args() 244 | display = args.display 245 | phase = 'train' 246 | total_time = 0.0 247 | total_frames = 0 248 | colours = np.random.rand(32,3) #used only for display 249 | if(display): 250 | if not os.path.exists('mot_benchmark'): 251 | print('\n\tERROR: mot_benchmark link not found!\n\n Create a symbolic link to the MOT benchmark\n (https://motchallenge.net/data/2D_MOT_2015/#download). E.g.:\n\n $ ln -s /path/to/MOT2015_challenge/2DMOT2015 mot_benchmark\n\n') 252 | exit() 253 | plt.ion() 254 | fig = plt.figure() 255 | 256 | if not os.path.exists('output'): 257 | os.makedirs('output') 258 | 259 | for seq in sequences: 260 | mot_tracker = Sort() #create instance of the SORT tracker 261 | seq_dets = np.loadtxt('data/%s/det.txt'%(seq),delimiter=',') #load detections 262 | with open('output/%s.txt'%(seq),'w') as out_file: 263 | print("Processing %s."%(seq)) 264 | for frame in range(int(seq_dets[:,0].max())): 265 | frame += 1 #detection and frame numbers begin at 1 266 | dets = seq_dets[seq_dets[:,0]==frame,2:7] 267 | dets[:,2:4] += dets[:,0:2] #convert to [x1,y1,w,h] to [x1,y1,x2,y2] 268 | total_frames += 1 269 | 270 | if(display): 271 | ax1 = fig.add_subplot(111, aspect='equal') 272 | fn = 'mot_benchmark/%s/%s/img1/%06d.jpg'%(phase,seq,frame) 273 | im =io.imread(fn) 274 | ax1.imshow(im) 275 | plt.title(seq+' Tracked Targets') 276 | 277 | start_time = time.time() 278 | trackers = mot_tracker.update(dets) 279 | cycle_time = time.time() - start_time 280 | total_time += cycle_time 281 | 282 | for d in trackers: 283 | print('%d,%d,%.2f,%.2f,%.2f,%.2f,1,-1,-1,-1'%(frame,d[4],d[0],d[1],d[2]-d[0],d[3]-d[1]),file=out_file) 284 | if(display): 285 | d = d.astype(np.int32) 286 | ax1.add_patch(patches.Rectangle((d[0],d[1]),d[2]-d[0],d[3]-d[1],fill=False,lw=3,ec=colours[d[4]%32,:])) 287 | ax1.set_adjustable('box-forced') 288 | 289 | if(display): 290 | fig.canvas.flush_events() 291 | plt.draw() 292 | ax1.cla() 293 | 294 | print("Total Tracking took: %.3f for %d frames or %.1f FPS"%(total_time,total_frames,total_frames/total_time)) 295 | if(display): 296 | print("Note: to get real runtime results run without the option: --display") 297 | 298 | 299 | 300 | -------------------------------------------------------------------------------- /config/yolov3.cfg: -------------------------------------------------------------------------------- 1 | [net] 2 | # Testing 3 | #batch=1 4 | #subdivisions=1 5 | # Training 6 | batch=16 7 | subdivisions=1 8 | width=416 9 | height=416 10 | channels=3 11 | momentum=0.9 12 | decay=0.0005 13 | angle=0 14 | saturation = 1.5 15 | exposure = 1.5 16 | hue=.1 17 | 18 | learning_rate=0.001 19 | burn_in=1000 20 | max_batches = 500200 21 | policy=steps 22 | steps=400000,450000 23 | scales=.1,.1 24 | 25 | [convolutional] 26 | batch_normalize=1 27 | filters=32 28 | size=3 29 | stride=1 30 | pad=1 31 | activation=leaky 32 | 33 | # Downsample 34 | 35 | [convolutional] 36 | batch_normalize=1 37 | filters=64 38 | size=3 39 | stride=2 40 | pad=1 41 | activation=leaky 42 | 43 | [convolutional] 44 | batch_normalize=1 45 | filters=32 46 | size=1 47 | stride=1 48 | pad=1 49 | activation=leaky 50 | 51 | [convolutional] 52 | batch_normalize=1 53 | filters=64 54 | size=3 55 | stride=1 56 | pad=1 57 | activation=leaky 58 | 59 | [shortcut] 60 | from=-3 61 | activation=linear 62 | 63 | # Downsample 64 | 65 | [convolutional] 66 | batch_normalize=1 67 | filters=128 68 | size=3 69 | stride=2 70 | pad=1 71 | activation=leaky 72 | 73 | [convolutional] 74 | batch_normalize=1 75 | filters=64 76 | size=1 77 | stride=1 78 | pad=1 79 | activation=leaky 80 | 81 | [convolutional] 82 | batch_normalize=1 83 | filters=128 84 | size=3 85 | stride=1 86 | pad=1 87 | activation=leaky 88 | 89 | [shortcut] 90 | from=-3 91 | activation=linear 92 | 93 | [convolutional] 94 | batch_normalize=1 95 | filters=64 96 | size=1 97 | stride=1 98 | pad=1 99 | activation=leaky 100 | 101 | [convolutional] 102 | batch_normalize=1 103 | filters=128 104 | size=3 105 | stride=1 106 | pad=1 107 | activation=leaky 108 | 109 | [shortcut] 110 | from=-3 111 | activation=linear 112 | 113 | # Downsample 114 | 115 | [convolutional] 116 | batch_normalize=1 117 | filters=256 118 | size=3 119 | stride=2 120 | pad=1 121 | activation=leaky 122 | 123 | [convolutional] 124 | batch_normalize=1 125 | filters=128 126 | size=1 127 | stride=1 128 | pad=1 129 | activation=leaky 130 | 131 | [convolutional] 132 | batch_normalize=1 133 | filters=256 134 | size=3 135 | stride=1 136 | pad=1 137 | activation=leaky 138 | 139 | [shortcut] 140 | from=-3 141 | activation=linear 142 | 143 | [convolutional] 144 | batch_normalize=1 145 | filters=128 146 | size=1 147 | stride=1 148 | pad=1 149 | activation=leaky 150 | 151 | [convolutional] 152 | batch_normalize=1 153 | filters=256 154 | size=3 155 | stride=1 156 | pad=1 157 | activation=leaky 158 | 159 | [shortcut] 160 | from=-3 161 | activation=linear 162 | 163 | [convolutional] 164 | batch_normalize=1 165 | filters=128 166 | size=1 167 | stride=1 168 | pad=1 169 | activation=leaky 170 | 171 | [convolutional] 172 | batch_normalize=1 173 | filters=256 174 | size=3 175 | stride=1 176 | pad=1 177 | activation=leaky 178 | 179 | [shortcut] 180 | from=-3 181 | activation=linear 182 | 183 | [convolutional] 184 | batch_normalize=1 185 | filters=128 186 | size=1 187 | stride=1 188 | pad=1 189 | activation=leaky 190 | 191 | [convolutional] 192 | batch_normalize=1 193 | filters=256 194 | size=3 195 | stride=1 196 | pad=1 197 | activation=leaky 198 | 199 | [shortcut] 200 | from=-3 201 | activation=linear 202 | 203 | 204 | [convolutional] 205 | batch_normalize=1 206 | filters=128 207 | size=1 208 | stride=1 209 | pad=1 210 | activation=leaky 211 | 212 | [convolutional] 213 | batch_normalize=1 214 | filters=256 215 | size=3 216 | stride=1 217 | pad=1 218 | activation=leaky 219 | 220 | [shortcut] 221 | from=-3 222 | activation=linear 223 | 224 | [convolutional] 225 | batch_normalize=1 226 | filters=128 227 | size=1 228 | stride=1 229 | pad=1 230 | activation=leaky 231 | 232 | [convolutional] 233 | batch_normalize=1 234 | filters=256 235 | size=3 236 | stride=1 237 | pad=1 238 | activation=leaky 239 | 240 | [shortcut] 241 | from=-3 242 | activation=linear 243 | 244 | [convolutional] 245 | batch_normalize=1 246 | filters=128 247 | size=1 248 | stride=1 249 | pad=1 250 | activation=leaky 251 | 252 | [convolutional] 253 | batch_normalize=1 254 | filters=256 255 | size=3 256 | stride=1 257 | pad=1 258 | activation=leaky 259 | 260 | [shortcut] 261 | from=-3 262 | activation=linear 263 | 264 | [convolutional] 265 | batch_normalize=1 266 | filters=128 267 | size=1 268 | stride=1 269 | pad=1 270 | activation=leaky 271 | 272 | [convolutional] 273 | batch_normalize=1 274 | filters=256 275 | size=3 276 | stride=1 277 | pad=1 278 | activation=leaky 279 | 280 | [shortcut] 281 | from=-3 282 | activation=linear 283 | 284 | # Downsample 285 | 286 | [convolutional] 287 | batch_normalize=1 288 | filters=512 289 | size=3 290 | stride=2 291 | pad=1 292 | activation=leaky 293 | 294 | [convolutional] 295 | batch_normalize=1 296 | filters=256 297 | size=1 298 | stride=1 299 | pad=1 300 | activation=leaky 301 | 302 | [convolutional] 303 | batch_normalize=1 304 | filters=512 305 | size=3 306 | stride=1 307 | pad=1 308 | activation=leaky 309 | 310 | [shortcut] 311 | from=-3 312 | activation=linear 313 | 314 | 315 | [convolutional] 316 | batch_normalize=1 317 | filters=256 318 | size=1 319 | stride=1 320 | pad=1 321 | activation=leaky 322 | 323 | [convolutional] 324 | batch_normalize=1 325 | filters=512 326 | size=3 327 | stride=1 328 | pad=1 329 | activation=leaky 330 | 331 | [shortcut] 332 | from=-3 333 | activation=linear 334 | 335 | 336 | [convolutional] 337 | batch_normalize=1 338 | filters=256 339 | size=1 340 | stride=1 341 | pad=1 342 | activation=leaky 343 | 344 | [convolutional] 345 | batch_normalize=1 346 | filters=512 347 | size=3 348 | stride=1 349 | pad=1 350 | activation=leaky 351 | 352 | [shortcut] 353 | from=-3 354 | activation=linear 355 | 356 | 357 | [convolutional] 358 | batch_normalize=1 359 | filters=256 360 | size=1 361 | stride=1 362 | pad=1 363 | activation=leaky 364 | 365 | [convolutional] 366 | batch_normalize=1 367 | filters=512 368 | size=3 369 | stride=1 370 | pad=1 371 | activation=leaky 372 | 373 | [shortcut] 374 | from=-3 375 | activation=linear 376 | 377 | [convolutional] 378 | batch_normalize=1 379 | filters=256 380 | size=1 381 | stride=1 382 | pad=1 383 | activation=leaky 384 | 385 | [convolutional] 386 | batch_normalize=1 387 | filters=512 388 | size=3 389 | stride=1 390 | pad=1 391 | activation=leaky 392 | 393 | [shortcut] 394 | from=-3 395 | activation=linear 396 | 397 | 398 | [convolutional] 399 | batch_normalize=1 400 | filters=256 401 | size=1 402 | stride=1 403 | pad=1 404 | activation=leaky 405 | 406 | [convolutional] 407 | batch_normalize=1 408 | filters=512 409 | size=3 410 | stride=1 411 | pad=1 412 | activation=leaky 413 | 414 | [shortcut] 415 | from=-3 416 | activation=linear 417 | 418 | 419 | [convolutional] 420 | batch_normalize=1 421 | filters=256 422 | size=1 423 | stride=1 424 | pad=1 425 | activation=leaky 426 | 427 | [convolutional] 428 | batch_normalize=1 429 | filters=512 430 | size=3 431 | stride=1 432 | pad=1 433 | activation=leaky 434 | 435 | [shortcut] 436 | from=-3 437 | activation=linear 438 | 439 | [convolutional] 440 | batch_normalize=1 441 | filters=256 442 | size=1 443 | stride=1 444 | pad=1 445 | activation=leaky 446 | 447 | [convolutional] 448 | batch_normalize=1 449 | filters=512 450 | size=3 451 | stride=1 452 | pad=1 453 | activation=leaky 454 | 455 | [shortcut] 456 | from=-3 457 | activation=linear 458 | 459 | # Downsample 460 | 461 | [convolutional] 462 | batch_normalize=1 463 | filters=1024 464 | size=3 465 | stride=2 466 | pad=1 467 | activation=leaky 468 | 469 | [convolutional] 470 | batch_normalize=1 471 | filters=512 472 | size=1 473 | stride=1 474 | pad=1 475 | activation=leaky 476 | 477 | [convolutional] 478 | batch_normalize=1 479 | filters=1024 480 | size=3 481 | stride=1 482 | pad=1 483 | activation=leaky 484 | 485 | [shortcut] 486 | from=-3 487 | activation=linear 488 | 489 | [convolutional] 490 | batch_normalize=1 491 | filters=512 492 | size=1 493 | stride=1 494 | pad=1 495 | activation=leaky 496 | 497 | [convolutional] 498 | batch_normalize=1 499 | filters=1024 500 | size=3 501 | stride=1 502 | pad=1 503 | activation=leaky 504 | 505 | [shortcut] 506 | from=-3 507 | activation=linear 508 | 509 | [convolutional] 510 | batch_normalize=1 511 | filters=512 512 | size=1 513 | stride=1 514 | pad=1 515 | activation=leaky 516 | 517 | [convolutional] 518 | batch_normalize=1 519 | filters=1024 520 | size=3 521 | stride=1 522 | pad=1 523 | activation=leaky 524 | 525 | [shortcut] 526 | from=-3 527 | activation=linear 528 | 529 | [convolutional] 530 | batch_normalize=1 531 | filters=512 532 | size=1 533 | stride=1 534 | pad=1 535 | activation=leaky 536 | 537 | [convolutional] 538 | batch_normalize=1 539 | filters=1024 540 | size=3 541 | stride=1 542 | pad=1 543 | activation=leaky 544 | 545 | [shortcut] 546 | from=-3 547 | activation=linear 548 | 549 | ###################### 550 | 551 | [convolutional] 552 | batch_normalize=1 553 | filters=512 554 | size=1 555 | stride=1 556 | pad=1 557 | activation=leaky 558 | 559 | [convolutional] 560 | batch_normalize=1 561 | size=3 562 | stride=1 563 | pad=1 564 | filters=1024 565 | activation=leaky 566 | 567 | [convolutional] 568 | batch_normalize=1 569 | filters=512 570 | size=1 571 | stride=1 572 | pad=1 573 | activation=leaky 574 | 575 | [convolutional] 576 | batch_normalize=1 577 | size=3 578 | stride=1 579 | pad=1 580 | filters=1024 581 | activation=leaky 582 | 583 | [convolutional] 584 | batch_normalize=1 585 | filters=512 586 | size=1 587 | stride=1 588 | pad=1 589 | activation=leaky 590 | 591 | [convolutional] 592 | batch_normalize=1 593 | size=3 594 | stride=1 595 | pad=1 596 | filters=1024 597 | activation=leaky 598 | 599 | [convolutional] 600 | size=1 601 | stride=1 602 | pad=1 603 | filters=255 604 | activation=linear 605 | 606 | 607 | [yolo] 608 | mask = 6,7,8 609 | anchors = 10,13, 16,30, 33,23, 30,61, 62,45, 59,119, 116,90, 156,198, 373,326 610 | classes=80 611 | num=9 612 | jitter=.3 613 | ignore_thresh = .7 614 | truth_thresh = 1 615 | random=1 616 | 617 | 618 | [route] 619 | layers = -4 620 | 621 | [convolutional] 622 | batch_normalize=1 623 | filters=256 624 | size=1 625 | stride=1 626 | pad=1 627 | activation=leaky 628 | 629 | [upsample] 630 | stride=2 631 | 632 | [route] 633 | layers = -1, 61 634 | 635 | 636 | 637 | [convolutional] 638 | batch_normalize=1 639 | filters=256 640 | size=1 641 | stride=1 642 | pad=1 643 | activation=leaky 644 | 645 | [convolutional] 646 | batch_normalize=1 647 | size=3 648 | stride=1 649 | pad=1 650 | filters=512 651 | activation=leaky 652 | 653 | [convolutional] 654 | batch_normalize=1 655 | filters=256 656 | size=1 657 | stride=1 658 | pad=1 659 | activation=leaky 660 | 661 | [convolutional] 662 | batch_normalize=1 663 | size=3 664 | stride=1 665 | pad=1 666 | filters=512 667 | activation=leaky 668 | 669 | [convolutional] 670 | batch_normalize=1 671 | filters=256 672 | size=1 673 | stride=1 674 | pad=1 675 | activation=leaky 676 | 677 | [convolutional] 678 | batch_normalize=1 679 | size=3 680 | stride=1 681 | pad=1 682 | filters=512 683 | activation=leaky 684 | 685 | [convolutional] 686 | size=1 687 | stride=1 688 | pad=1 689 | filters=255 690 | activation=linear 691 | 692 | 693 | [yolo] 694 | mask = 3,4,5 695 | anchors = 10,13, 16,30, 33,23, 30,61, 62,45, 59,119, 116,90, 156,198, 373,326 696 | classes=80 697 | num=9 698 | jitter=.3 699 | ignore_thresh = .7 700 | truth_thresh = 1 701 | random=1 702 | 703 | 704 | 705 | [route] 706 | layers = -4 707 | 708 | [convolutional] 709 | batch_normalize=1 710 | filters=128 711 | size=1 712 | stride=1 713 | pad=1 714 | activation=leaky 715 | 716 | [upsample] 717 | stride=2 718 | 719 | [route] 720 | layers = -1, 36 721 | 722 | 723 | 724 | [convolutional] 725 | batch_normalize=1 726 | filters=128 727 | size=1 728 | stride=1 729 | pad=1 730 | activation=leaky 731 | 732 | [convolutional] 733 | batch_normalize=1 734 | size=3 735 | stride=1 736 | pad=1 737 | filters=256 738 | activation=leaky 739 | 740 | [convolutional] 741 | batch_normalize=1 742 | filters=128 743 | size=1 744 | stride=1 745 | pad=1 746 | activation=leaky 747 | 748 | [convolutional] 749 | batch_normalize=1 750 | size=3 751 | stride=1 752 | pad=1 753 | filters=256 754 | activation=leaky 755 | 756 | [convolutional] 757 | batch_normalize=1 758 | filters=128 759 | size=1 760 | stride=1 761 | pad=1 762 | activation=leaky 763 | 764 | [convolutional] 765 | batch_normalize=1 766 | size=3 767 | stride=1 768 | pad=1 769 | filters=256 770 | activation=leaky 771 | 772 | [convolutional] 773 | size=1 774 | stride=1 775 | pad=1 776 | filters=255 777 | activation=linear 778 | 779 | 780 | [yolo] 781 | mask = 0,1,2 782 | anchors = 10,13, 16,30, 33,23, 30,61, 62,45, 59,119, 116,90, 156,198, 373,326 783 | classes=80 784 | num=9 785 | jitter=.3 786 | ignore_thresh = .7 787 | truth_thresh = 1 788 | random=1 789 | -------------------------------------------------------------------------------- /models.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | 3 | import torch 4 | import torch.nn as nn 5 | import torch.nn.functional as F 6 | from torch.autograd import Variable 7 | import numpy as np 8 | 9 | from PIL import Image 10 | 11 | from utils.parse_config import * 12 | from utils.utils import build_targets 13 | from collections import defaultdict 14 | 15 | 16 | def create_modules(module_defs): 17 | """ 18 | Constructs module list of layer blocks from module configuration in module_defs 19 | """ 20 | hyperparams = module_defs.pop(0) 21 | output_filters = [int(hyperparams["channels"])] 22 | module_list = nn.ModuleList() 23 | for i, module_def in enumerate(module_defs): 24 | modules = nn.Sequential() 25 | 26 | if module_def["type"] == "convolutional": 27 | bn = int(module_def["batch_normalize"]) 28 | filters = int(module_def["filters"]) 29 | kernel_size = int(module_def["size"]) 30 | pad = (kernel_size - 1) // 2 if int(module_def["pad"]) else 0 31 | modules.add_module( 32 | "conv_%d" % i, 33 | nn.Conv2d( 34 | in_channels=output_filters[-1], 35 | out_channels=filters, 36 | kernel_size=kernel_size, 37 | stride=int(module_def["stride"]), 38 | padding=pad, 39 | bias=not bn, 40 | ), 41 | ) 42 | if bn: 43 | modules.add_module("batch_norm_%d" % i, nn.BatchNorm2d(filters)) 44 | if module_def["activation"] == "leaky": 45 | modules.add_module("leaky_%d" % i, nn.LeakyReLU(0.1)) 46 | 47 | elif module_def["type"] == "maxpool": 48 | kernel_size = int(module_def["size"]) 49 | stride = int(module_def["stride"]) 50 | if kernel_size == 2 and stride == 1: 51 | padding = nn.ZeroPad2d((0, 1, 0, 1)) 52 | modules.add_module("_debug_padding_%d" % i, padding) 53 | maxpool = nn.MaxPool2d( 54 | kernel_size=int(module_def["size"]), 55 | stride=int(module_def["stride"]), 56 | padding=int((kernel_size - 1) // 2), 57 | ) 58 | modules.add_module("maxpool_%d" % i, maxpool) 59 | 60 | elif module_def["type"] == "upsample": 61 | upsample = nn.Upsample(scale_factor=int(module_def["stride"]), mode="nearest") 62 | modules.add_module("upsample_%d" % i, upsample) 63 | 64 | elif module_def["type"] == "route": 65 | layers = [int(x) for x in module_def["layers"].split(",")] 66 | filters = sum([output_filters[layer_i] for layer_i in layers]) 67 | modules.add_module("route_%d" % i, EmptyLayer()) 68 | 69 | elif module_def["type"] == "shortcut": 70 | filters = output_filters[int(module_def["from"])] 71 | modules.add_module("shortcut_%d" % i, EmptyLayer()) 72 | 73 | elif module_def["type"] == "yolo": 74 | anchor_idxs = [int(x) for x in module_def["mask"].split(",")] 75 | # Extract anchors 76 | anchors = [int(x) for x in module_def["anchors"].split(",")] 77 | anchors = [(anchors[i], anchors[i + 1]) for i in range(0, len(anchors), 2)] 78 | anchors = [anchors[i] for i in anchor_idxs] 79 | num_classes = int(module_def["classes"]) 80 | img_height = int(hyperparams["height"]) 81 | # Define detection layer 82 | yolo_layer = YOLOLayer(anchors, num_classes, img_height) 83 | modules.add_module("yolo_%d" % i, yolo_layer) 84 | # Register module list and number of output filters 85 | module_list.append(modules) 86 | output_filters.append(filters) 87 | 88 | return hyperparams, module_list 89 | 90 | 91 | class EmptyLayer(nn.Module): 92 | """Placeholder for 'route' and 'shortcut' layers""" 93 | 94 | def __init__(self): 95 | super(EmptyLayer, self).__init__() 96 | 97 | 98 | class YOLOLayer(nn.Module): 99 | """Detection layer""" 100 | 101 | def __init__(self, anchors, num_classes, img_dim): 102 | super(YOLOLayer, self).__init__() 103 | self.anchors = anchors 104 | self.num_anchors = len(anchors) 105 | self.num_classes = num_classes 106 | self.bbox_attrs = 5 + num_classes 107 | self.image_dim = img_dim 108 | self.ignore_thres = 0.5 109 | self.lambda_coord = 1 110 | 111 | self.mse_loss = nn.MSELoss(size_average=True) # Coordinate loss 112 | self.bce_loss = nn.BCELoss(size_average=True) # Confidence loss 113 | self.ce_loss = nn.CrossEntropyLoss() # Class loss 114 | 115 | def forward(self, x, targets=None): 116 | nA = self.num_anchors 117 | nB = x.size(0) 118 | nG = x.size(2) 119 | stride = self.image_dim / nG 120 | 121 | # Tensors for cuda support 122 | FloatTensor = torch.cuda.FloatTensor if x.is_cuda else torch.FloatTensor 123 | LongTensor = torch.cuda.LongTensor if x.is_cuda else torch.LongTensor 124 | ByteTensor = torch.cuda.ByteTensor if x.is_cuda else torch.ByteTensor 125 | 126 | prediction = x.view(nB, nA, self.bbox_attrs, nG, nG).permute(0, 1, 3, 4, 2).contiguous() 127 | 128 | # Get outputs 129 | x = torch.sigmoid(prediction[..., 0]) # Center x 130 | y = torch.sigmoid(prediction[..., 1]) # Center y 131 | w = prediction[..., 2] # Width 132 | h = prediction[..., 3] # Height 133 | pred_conf = torch.sigmoid(prediction[..., 4]) # Conf 134 | pred_cls = torch.sigmoid(prediction[..., 5:]) # Cls pred. 135 | 136 | # Calculate offsets for each grid 137 | grid_x = torch.arange(nG).repeat(nG, 1).view([1, 1, nG, nG]).type(FloatTensor) 138 | grid_y = torch.arange(nG).repeat(nG, 1).t().view([1, 1, nG, nG]).type(FloatTensor) 139 | scaled_anchors = FloatTensor([(a_w / stride, a_h / stride) for a_w, a_h in self.anchors]) 140 | anchor_w = scaled_anchors[:, 0:1].view((1, nA, 1, 1)) 141 | anchor_h = scaled_anchors[:, 1:2].view((1, nA, 1, 1)) 142 | 143 | # Add offset and scale with anchors 144 | pred_boxes = FloatTensor(prediction[..., :4].shape) 145 | pred_boxes[..., 0] = x.data + grid_x 146 | pred_boxes[..., 1] = y.data + grid_y 147 | pred_boxes[..., 2] = torch.exp(w.data) * anchor_w 148 | pred_boxes[..., 3] = torch.exp(h.data) * anchor_h 149 | 150 | # Training 151 | if targets is not None: 152 | 153 | if x.is_cuda: 154 | self.mse_loss = self.mse_loss.cuda() 155 | self.bce_loss = self.bce_loss.cuda() 156 | self.ce_loss = self.ce_loss.cuda() 157 | 158 | nGT, nCorrect, mask, conf_mask, tx, ty, tw, th, tconf, tcls = build_targets( 159 | pred_boxes=pred_boxes.cpu().data, 160 | pred_conf=pred_conf.cpu().data, 161 | pred_cls=pred_cls.cpu().data, 162 | target=targets.cpu().data, 163 | anchors=scaled_anchors.cpu().data, 164 | num_anchors=nA, 165 | num_classes=self.num_classes, 166 | grid_size=nG, 167 | ignore_thres=self.ignore_thres, 168 | img_dim=self.image_dim, 169 | ) 170 | 171 | nProposals = int((pred_conf > 0.5).sum().item()) 172 | recall = float(nCorrect / nGT) if nGT else 1 173 | precision = float(nCorrect / nProposals) 174 | 175 | # Handle masks 176 | mask = Variable(mask.type(ByteTensor)) 177 | conf_mask = Variable(conf_mask.type(ByteTensor)) 178 | 179 | # Handle target variables 180 | tx = Variable(tx.type(FloatTensor), requires_grad=False) 181 | ty = Variable(ty.type(FloatTensor), requires_grad=False) 182 | tw = Variable(tw.type(FloatTensor), requires_grad=False) 183 | th = Variable(th.type(FloatTensor), requires_grad=False) 184 | tconf = Variable(tconf.type(FloatTensor), requires_grad=False) 185 | tcls = Variable(tcls.type(LongTensor), requires_grad=False) 186 | 187 | # Get conf mask where gt and where there is no gt 188 | conf_mask_true = mask 189 | conf_mask_false = conf_mask - mask 190 | 191 | # Mask outputs to ignore non-existing objects 192 | loss_x = self.mse_loss(x[mask], tx[mask]) 193 | loss_y = self.mse_loss(y[mask], ty[mask]) 194 | loss_w = self.mse_loss(w[mask], tw[mask]) 195 | loss_h = self.mse_loss(h[mask], th[mask]) 196 | loss_conf = self.bce_loss(pred_conf[conf_mask_false], tconf[conf_mask_false]) + self.bce_loss( 197 | pred_conf[conf_mask_true], tconf[conf_mask_true] 198 | ) 199 | loss_cls = (1 / nB) * self.ce_loss(pred_cls[mask], torch.argmax(tcls[mask], 1)) 200 | loss = loss_x + loss_y + loss_w + loss_h + loss_conf + loss_cls 201 | 202 | return ( 203 | loss, 204 | loss_x.item(), 205 | loss_y.item(), 206 | loss_w.item(), 207 | loss_h.item(), 208 | loss_conf.item(), 209 | loss_cls.item(), 210 | recall, 211 | precision, 212 | ) 213 | 214 | else: 215 | # If not in training phase return predictions 216 | output = torch.cat( 217 | ( 218 | pred_boxes.view(nB, -1, 4) * stride, 219 | pred_conf.view(nB, -1, 1), 220 | pred_cls.view(nB, -1, self.num_classes), 221 | ), 222 | -1, 223 | ) 224 | return output 225 | 226 | 227 | class Darknet(nn.Module): 228 | """YOLOv3 object detection model""" 229 | 230 | def __init__(self, config_path, img_size=416): 231 | super(Darknet, self).__init__() 232 | self.module_defs = parse_model_config(config_path) 233 | self.hyperparams, self.module_list = create_modules(self.module_defs) 234 | self.img_size = img_size 235 | self.seen = 0 236 | self.header_info = np.array([0, 0, 0, self.seen, 0]) 237 | self.loss_names = ["x", "y", "w", "h", "conf", "cls", "recall", "precision"] 238 | 239 | def forward(self, x, targets=None): 240 | is_training = targets is not None 241 | output = [] 242 | self.losses = defaultdict(float) 243 | layer_outputs = [] 244 | for i, (module_def, module) in enumerate(zip(self.module_defs, self.module_list)): 245 | if module_def["type"] in ["convolutional", "upsample", "maxpool"]: 246 | x = module(x) 247 | elif module_def["type"] == "route": 248 | layer_i = [int(x) for x in module_def["layers"].split(",")] 249 | x = torch.cat([layer_outputs[i] for i in layer_i], 1) 250 | elif module_def["type"] == "shortcut": 251 | layer_i = int(module_def["from"]) 252 | x = layer_outputs[-1] + layer_outputs[layer_i] 253 | elif module_def["type"] == "yolo": 254 | # Train phase: get loss 255 | if is_training: 256 | x, *losses = module[0](x, targets) 257 | for name, loss in zip(self.loss_names, losses): 258 | self.losses[name] += loss 259 | # Test phase: Get detections 260 | else: 261 | x = module(x) 262 | output.append(x) 263 | layer_outputs.append(x) 264 | 265 | self.losses["recall"] /= 3 266 | self.losses["precision"] /= 3 267 | return sum(output) if is_training else torch.cat(output, 1) 268 | 269 | def load_weights(self, weights_path): 270 | """Parses and loads the weights stored in 'weights_path'""" 271 | 272 | # Open the weights file 273 | fp = open(weights_path, "rb") 274 | header = np.fromfile(fp, dtype=np.int32, count=5) # First five are header values 275 | 276 | # Needed to write header when saving weights 277 | self.header_info = header 278 | 279 | self.seen = header[3] 280 | weights = np.fromfile(fp, dtype=np.float32) # The rest are weights 281 | fp.close() 282 | 283 | ptr = 0 284 | for i, (module_def, module) in enumerate(zip(self.module_defs, self.module_list)): 285 | if module_def["type"] == "convolutional": 286 | conv_layer = module[0] 287 | if module_def["batch_normalize"]: 288 | # Load BN bias, weights, running mean and running variance 289 | bn_layer = module[1] 290 | num_b = bn_layer.bias.numel() # Number of biases 291 | # Bias 292 | bn_b = torch.from_numpy(weights[ptr : ptr + num_b]).view_as(bn_layer.bias) 293 | bn_layer.bias.data.copy_(bn_b) 294 | ptr += num_b 295 | # Weight 296 | bn_w = torch.from_numpy(weights[ptr : ptr + num_b]).view_as(bn_layer.weight) 297 | bn_layer.weight.data.copy_(bn_w) 298 | ptr += num_b 299 | # Running Mean 300 | bn_rm = torch.from_numpy(weights[ptr : ptr + num_b]).view_as(bn_layer.running_mean) 301 | bn_layer.running_mean.data.copy_(bn_rm) 302 | ptr += num_b 303 | # Running Var 304 | bn_rv = torch.from_numpy(weights[ptr : ptr + num_b]).view_as(bn_layer.running_var) 305 | bn_layer.running_var.data.copy_(bn_rv) 306 | ptr += num_b 307 | else: 308 | # Load conv. bias 309 | num_b = conv_layer.bias.numel() 310 | conv_b = torch.from_numpy(weights[ptr : ptr + num_b]).view_as(conv_layer.bias) 311 | conv_layer.bias.data.copy_(conv_b) 312 | ptr += num_b 313 | # Load conv. weights 314 | num_w = conv_layer.weight.numel() 315 | conv_w = torch.from_numpy(weights[ptr : ptr + num_w]).view_as(conv_layer.weight) 316 | conv_layer.weight.data.copy_(conv_w) 317 | ptr += num_w 318 | 319 | 320 | def save_weights(self, path, cutoff=-1): 321 | 322 | fp = open(path, "wb") 323 | self.header_info[3] = self.seen 324 | self.header_info.tofile(fp) 325 | 326 | # Iterate through layers 327 | for i, (module_def, module) in enumerate(zip(self.module_defs[:cutoff], self.module_list[:cutoff])): 328 | if module_def["type"] == "convolutional": 329 | conv_layer = module[0] 330 | # If batch norm, load bn first 331 | if module_def["batch_normalize"]: 332 | bn_layer = module[1] 333 | bn_layer.bias.data.cpu().numpy().tofile(fp) 334 | bn_layer.weight.data.cpu().numpy().tofile(fp) 335 | bn_layer.running_mean.data.cpu().numpy().tofile(fp) 336 | bn_layer.running_var.data.cpu().numpy().tofile(fp) 337 | # Load conv bias 338 | else: 339 | conv_layer.bias.data.cpu().numpy().tofile(fp) 340 | # Load conv weights 341 | conv_layer.weight.data.cpu().numpy().tofile(fp) 342 | 343 | fp.close() 344 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------