Skip to content

Commit 5eb1027

Browse files
author
Shuvashish Chatterjee
committed
build
1 parent eb3291b commit 5eb1027

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+6028
-455
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ wheels/
3232
*.egg-info/
3333
.installed.cfg
3434
*.egg
35+
*.mp4
3536

3637
# PyInstaller
3738
# Usually these files are written by a python script from a template

.vscode/launch.json

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
// Use IntelliSense to learn about possible attributes.
3+
// Hover to view descriptions of existing attributes.
4+
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5+
"version": "0.2.0",
6+
"configurations": [
7+
{
8+
"name": "Python: Current File",
9+
"type": "python",
10+
"request": "launch",
11+
"program": "${file}",
12+
"console": "integratedTerminal"
13+
}
14+
]
15+
}

.vscode/settings.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
{
2-
"python.pythonPath": "/anaconda3/bin/python"
2+
"python.pythonPath": "C:\\ProgramData\\Anaconda3\\python.exe",
3+
"python.linting.pylintEnabled": true,
4+
"python.linting.enabled": true
35
}

callbacks.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
from keras.callbacks import TensorBoard, ModelCheckpoint
2+
import tensorflow as tf
3+
import numpy as np
4+
5+
class CustomTensorBoard(TensorBoard):
6+
""" to log the loss after each batch
7+
"""
8+
def __init__(self, log_every=1, **kwargs):
9+
super(CustomTensorBoard, self).__init__(**kwargs)
10+
self.log_every = log_every
11+
self.counter = 0
12+
13+
def on_batch_end(self, batch, logs=None):
14+
self.counter+=1
15+
if self.counter%self.log_every==0:
16+
for name, value in logs.items():
17+
if name in ['batch', 'size']:
18+
continue
19+
summary = tf.Summary()
20+
summary_value = summary.value.add()
21+
summary_value.simple_value = value.item()
22+
summary_value.tag = name
23+
self.writer.add_summary(summary, self.counter)
24+
self.writer.flush()
25+
26+
super(CustomTensorBoard, self).on_batch_end(batch, logs)
27+
28+
class CustomModelCheckpoint(ModelCheckpoint):
29+
""" to save the template model, not the multi-GPU model
30+
"""
31+
def __init__(self, model_to_save, **kwargs):
32+
super(CustomModelCheckpoint, self).__init__(**kwargs)
33+
self.model_to_save = model_to_save
34+
35+
def on_epoch_end(self, epoch, logs=None):
36+
logs = logs or {}
37+
self.epochs_since_last_save += 1
38+
if self.epochs_since_last_save >= self.period:
39+
self.epochs_since_last_save = 0
40+
filepath = self.filepath.format(epoch=epoch + 1, **logs)
41+
if self.save_best_only:
42+
current = logs.get(self.monitor)
43+
if current is None:
44+
warnings.warn('Can save best model only with %s available, '
45+
'skipping.' % (self.monitor), RuntimeWarning)
46+
else:
47+
if self.monitor_op(current, self.best):
48+
if self.verbose > 0:
49+
print('\nEpoch %05d: %s improved from %0.5f to %0.5f,'
50+
' saving model to %s'
51+
% (epoch + 1, self.monitor, self.best,
52+
current, filepath))
53+
self.best = current
54+
if self.save_weights_only:
55+
self.model_to_save.save_weights(filepath, overwrite=True)
56+
else:
57+
self.model_to_save.save(filepath, overwrite=True)
58+
else:
59+
if self.verbose > 0:
60+
print('\nEpoch %05d: %s did not improve from %0.5f' %
61+
(epoch + 1, self.monitor, self.best))
62+
else:
63+
if self.verbose > 0:
64+
print('\nEpoch %05d: saving model to %s' % (epoch + 1, filepath))
65+
if self.save_weights_only:
66+
self.model_to_save.save_weights(filepath, overwrite=True)
67+
else:
68+
self.model_to_save.save(filepath, overwrite=True)
69+
70+
super(CustomModelCheckpoint, self).on_batch_end(epoch, logs)

camera.py

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
import numpy as np
1717
import pickle
1818
from pathlib import Path
19-
19+
from datetime import datetime
2020

2121

2222

@@ -28,7 +28,7 @@ class VIDEO :
2828
"save": False,
2929
"anotate": False,
3030
"save_path" :'./images/',
31-
"path" : "./video/",
31+
"path" : "./videos/VID_20190518_181206.mp4",
3232
"period" : 0.1
3333
}
3434

@@ -46,22 +46,25 @@ def __init__(self, **kwargs):
4646
self.anotate : bool
4747
self.fps : int
4848
self.path : str
49-
self.video : cv2.VideoCapture
5049
self.__dict__.update(self._defaults) # set up default values
5150
self.__dict__.update(kwargs) # and update with user overrides
51+
self.video = None
52+
self.fps = int
53+
self.step = int
54+
# self.extract_frames()
55+
56+
def extract_frames(self):
5257
self.video = cv2.VideoCapture(self.path)
5358
self.fps = self.video.get(cv2.CAP_PROP_FPS)
5459
self.step = int(self.period* self.fps)
55-
56-
def extract_frames(self):
5760
count = 0
5861
success = 1
5962

6063
while success:
6164
success, image = self.video.read()
62-
if count % self.step == 0 :
63-
64-
count += 1
65+
fn = int(datetime.utcnow().timestamp())
66+
cv2.imwrite(self.save_path+str(fn)+".jpg",image)
67+
count += 1
6568

6669

6770

@@ -75,10 +78,10 @@ def __init__(self):
7578
self.img_size = None
7679
self.rvecs = None
7780
self.tvecs = None
78-
self.callibrate()
81+
# self.callibrate()
7982

8083

81-
def callibrate(self , folder = 'camera_cal',n_x = 9, n_y = 6, verbose = False):
84+
def callibrate(self , folder = 'camera_cal',n_x = 7, n_y = 7, verbose = False):
8285
objp = np.zeros((n_y*n_x, 3), np.float32)
8386
objp[:, :2] = np.mgrid[0:n_x, 0:n_y].T.reshape(-1, 2)
8487
image_points = []
@@ -87,6 +90,7 @@ def callibrate(self , folder = 'camera_cal',n_x = 9, n_y = 6, verbose = False)
8790
directory = Path(folder)
8891
for image_file in directory.glob("*.jpg"):
8992
img = cv2.imread(str( image_file))
93+
img= cv2.resize(img, (400,300))
9094
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
9195
found, corners = cv2.findChessboardCorners(img_gray, (n_x, n_y))
9296
if found:
@@ -117,4 +121,5 @@ def __init__(self):
117121
self.image_path : str
118122
self.type : int
119123
self.speed : float
120-
self.coordinates : [float, float]
124+
self.coordinates : [float, float]
125+

config.json

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
{
2+
"model" : {
3+
"min_input_size": 288,
4+
"max_input_size": 448,
5+
"anchors": [55,69, 75,234, 133,240, 136,129, 142,363, 203,290, 228,184, 285,359, 341,260],
6+
"labels": ["kangaroo"]
7+
},
8+
9+
"train": {
10+
"train_image_folder": "/home/andy/Desktop/github/kangaroo/images/",
11+
"train_annot_folder": "/home/andy/Desktop/github/kangaroo/annots/",
12+
"cache_name": "kangaroo_train.pkl",
13+
14+
"train_times": 8,
15+
"batch_size": 16,
16+
"learning_rate": 1e-4,
17+
"nb_epochs": 100,
18+
"warmup_epochs": 3,
19+
"ignore_thresh": 0.5,
20+
"gpus": "0,1",
21+
22+
"grid_scales": [1,1,1],
23+
"obj_scale": 5,
24+
"noobj_scale": 1,
25+
"xywh_scale": 1,
26+
"class_scale": 1,
27+
28+
"tensorboard_dir": "logs",
29+
"saved_weights_name": "kangaroo.h5",
30+
"debug": true
31+
},
32+
33+
"valid": {
34+
"valid_image_folder": "",
35+
"valid_annot_folder": "",
36+
"cache_name": "",
37+
38+
"valid_times": 1
39+
}
40+
}

evaluate.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
#! /usr/bin/env python
2+
3+
import argparse
4+
import os
5+
import numpy as np
6+
import json
7+
from voc import parse_voc_annotation
8+
from yolo import create_yolov3_model
9+
from generator import BatchGenerator
10+
from utils.utils import normalize, evaluate
11+
from keras.callbacks import EarlyStopping, ModelCheckpoint
12+
from keras.optimizers import Adam
13+
from keras.models import load_model
14+
15+
def _main_(args):
16+
config_path = args.conf
17+
18+
with open(config_path) as config_buffer:
19+
config = json.loads(config_buffer.read())
20+
21+
###############################
22+
# Create the validation generator
23+
###############################
24+
valid_ints, labels = parse_voc_annotation(
25+
config['valid']['valid_annot_folder'],
26+
config['valid']['valid_image_folder'],
27+
config['valid']['cache_name'],
28+
config['model']['labels']
29+
)
30+
31+
labels = labels.keys() if len(config['model']['labels']) == 0 else config['model']['labels']
32+
labels = sorted(labels)
33+
34+
valid_generator = BatchGenerator(
35+
instances = valid_ints,
36+
anchors = config['model']['anchors'],
37+
labels = labels,
38+
downsample = 32, # ratio between network input's size and network output's size, 32 for YOLOv3
39+
max_box_per_image = 0,
40+
batch_size = config['train']['batch_size'],
41+
min_net_size = config['model']['min_input_size'],
42+
max_net_size = config['model']['max_input_size'],
43+
shuffle = True,
44+
jitter = 0.0,
45+
norm = normalize
46+
)
47+
48+
###############################
49+
# Load the model and do evaluation
50+
###############################
51+
os.environ['CUDA_VISIBLE_DEVICES'] = config['train']['gpus']
52+
53+
infer_model = load_model(config['train']['saved_weights_name'])
54+
55+
# compute mAP for all the classes
56+
average_precisions = evaluate(infer_model, valid_generator)
57+
58+
# print the score
59+
for label, average_precision in average_precisions.items():
60+
print(labels[label] + ': {:.4f}'.format(average_precision))
61+
print('mAP: {:.4f}'.format(sum(average_precisions.values()) / len(average_precisions)))
62+
63+
if __name__ == '__main__':
64+
argparser = argparse.ArgumentParser(description='Evaluate YOLO_v3 model on any dataset')
65+
argparser.add_argument('-c', '--conf', help='path to configuration file')
66+
67+
args = argparser.parse_args()
68+
_main_(args)

0 commit comments

Comments
 (0)