Skip to content

Commit 1358c90

Browse files
authored
Add files via upload
1 parent 12358b3 commit 1358c90

File tree

8 files changed

+811
-0
lines changed

8 files changed

+811
-0
lines changed

data.py

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
# -*- coding: utf-8 -*-
2+
3+
import os
4+
import glob
5+
import random
6+
7+
import cv2
8+
import numpy as np
9+
import h5py
10+
from sklearn.utils import shuffle
11+
12+
13+
class FileHDF5(object):
14+
@staticmethod
15+
def read(filename, db_name):
16+
db = h5py.File(filename, "r")
17+
np_data = np.array(db[db_name])
18+
db.close()
19+
20+
return np_data
21+
22+
@staticmethod
23+
def write(data, filename, db_name, write_mode="w"):
24+
"""Write data to hdf5 format.
25+
26+
# Args
27+
data : ndarray
28+
filename : str
29+
including full path
30+
db_name : str
31+
database name
32+
"""
33+
def _check_directory(filename):
34+
directory = os.path.dirname(filename)
35+
if not os.path.exists(directory):
36+
os.mkdir(directory)
37+
38+
_check_directory(filename)
39+
# todo : overwrite check
40+
db = h5py.File(filename, write_mode)
41+
dataset = db.create_dataset(db_name, data.shape, dtype="float")
42+
dataset[:] = data[:]
43+
db.close()
44+
45+
46+
def list_files(directory, pattern="*.*", n_files_to_sample=None, recursive_option=True, random_order=True):
47+
"""list files in a directory matched in defined pattern.
48+
49+
# Args
50+
directory : str
51+
filename of json file
52+
pattern : str
53+
regular expression for file matching
54+
55+
n_files_to_sample : int or None
56+
number of files to sample randomly and return.
57+
If this parameter is None, function returns every files.
58+
59+
recursive_option : boolean
60+
option for searching subdirectories. If this option is True,
61+
function searches all subdirectories recursively.
62+
63+
# Returns
64+
conf : dict
65+
dictionary containing contents of json file
66+
"""
67+
68+
if recursive_option == True:
69+
dirs = [path for path, _, _ in os.walk(directory)]
70+
else:
71+
dirs = [directory]
72+
73+
files = []
74+
for dir_ in dirs:
75+
for p in glob.glob(os.path.join(dir_, pattern)):
76+
files.append(p)
77+
78+
if n_files_to_sample is not None:
79+
if random_order:
80+
files = random.sample(files, n_files_to_sample)
81+
else:
82+
files = files[:n_files_to_sample]
83+
return files
84+
85+
86+
def files_to_images(files):
87+
images = []
88+
for filename in files:
89+
image = cv2.imread(filename)
90+
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
91+
images.append(image)
92+
images = np.array(images)
93+
return images
94+
95+
96+
def create_xy(pos_features, neg_features):
97+
pos_ys = np.ones((len(pos_features)))
98+
neg_ys = np.zeros((len(neg_features)))
99+
xs = np.concatenate([pos_features, neg_features], axis=0)
100+
ys = np.concatenate([pos_ys, neg_ys], axis=0)
101+
xs, ys = shuffle(xs, ys, random_state=0)
102+
103+
from sklearn.model_selection import train_test_split
104+
X_train, X_test, y_train, y_test = train_test_split(xs, ys, test_size=0.2, random_state=0)
105+
return X_train, X_test, y_train, y_test

desc.py

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
2+
from skimage.feature import hog
3+
import numpy as np
4+
import abc
5+
6+
class _Descriptor(object):
7+
8+
__metaclass__ = abc.ABCMeta
9+
10+
def __init_(self, params):
11+
pass
12+
13+
@abc.abstractmethod
14+
def get_features(self, images):
15+
pass
16+
17+
@abc.abstractmethod
18+
def get_params(self):
19+
pass
20+
21+
class HogDesc(_Descriptor):
22+
23+
def __init__(self, orientations=9, pix_per_cell=8, cell_per_block=2):
24+
self._orientations = orientations
25+
self._pix_per_cell = pix_per_cell
26+
self._cell_per_block = cell_per_block
27+
28+
def get_features(self, images, feature_vector=True):
29+
"""
30+
# Args
31+
images : ndarray, shape of (N, n_rows, n_cols)
32+
gray scale images
33+
34+
# Returns
35+
features :
36+
if feature_vector == True:
37+
2d-array, shape of (N, (pix_per_cell - cell_per_block + 1)**2 * cell_per_block**2 * orientations)
38+
else:
39+
5d-array, shape of (N,
40+
pix_per_cell - cell_per_block + 1,
41+
pix_per_cell - cell_per_block + 1,
42+
cell_per_block,
43+
cell_per_block,
44+
orientations)
45+
"""
46+
47+
features = []
48+
for img in images:
49+
feature_array = hog(img,
50+
orientations=self._orientations,
51+
pixels_per_cell=(self._pix_per_cell, self._pix_per_cell),
52+
cells_per_block=(self._cell_per_block, self._cell_per_block),
53+
visualise=False,
54+
feature_vector=feature_vector)
55+
features.append(feature_array)
56+
57+
features = np.array(features)
58+
return features
59+
60+
61+
class HogMap(object):
62+
63+
def __init__(self, hog_desc=HogDesc()):
64+
self._img = None
65+
self._desc = hog_desc
66+
67+
def _to_feature_map_point(self, x, y):
68+
"""
69+
# Args
70+
x : start x point in image
71+
y : start y point in image
72+
73+
# Returns
74+
x1 : x1 point in hog feature map
75+
y1 : y1 point in hog feature map
76+
x2
77+
y2
78+
"""
79+
unit_dim = self._desc._pix_per_cell - self._desc._cell_per_block + 1
80+
x1 = x // self._desc._pix_per_cell
81+
y1 = y // self._desc._pix_per_cell
82+
x2 = x1 + unit_dim
83+
y2 = y1 + unit_dim
84+
return x1, y1, x2, y2
85+
86+
def set_features(self, gray):
87+
self._img = gray
88+
self._feature_map = self._desc.get_features([gray], feature_vector=False)
89+
90+
def get_features(self, x, y):
91+
x1, y1, x2, y2 = self._to_feature_map_point(x, y)
92+
feature_vector = self._feature_map[:, y1:y2, x1:x2, :, :, :].ravel().reshape(1, -1)
93+
return feature_vector
94+
95+
96+

heatmap.py

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
# -*- coding: utf-8 -*-
2+
3+
import cv2
4+
import numpy as np
5+
import matplotlib.pyplot as plt
6+
7+
from scipy.ndimage.measurements import label
8+
9+
10+
def separate(boxes_):
11+
"""separate heat boxes by aspect ratio"""
12+
def _separate_box(box, axis="x"):
13+
x1, y1, x2, y2 = box
14+
15+
if axis == "x":
16+
px = (x1 + x2) / 2
17+
box1 = np.array([x1, y1, px, y2]).astype(int)
18+
box2 = np.array([px, y1, x2, y2]).astype(int)
19+
elif axis == "y":
20+
py = (y1 + y2) / 2
21+
box1 = np.array([x1, y1, x2, py]).astype(int)
22+
box2 = np.array([x1, py, x2, y2]).astype(int)
23+
return box1, box2
24+
25+
boxes = np.array(boxes_).tolist()
26+
for box in boxes[:]:
27+
x1, y1, x2, y2 = box
28+
w = x2-x1
29+
h = y2-y1
30+
31+
if w / h >= 1.85:
32+
print("separation x", w / h)
33+
box1, box2 = _separate_box(box, axis="x")
34+
boxes.remove(box)
35+
boxes.append(box1)
36+
boxes.append(box2)
37+
38+
elif h / w >= 1.85:
39+
print("separation y")
40+
box1, box2 = _separate_box(box, axis="y")
41+
boxes.remove(box)
42+
boxes.append(box1)
43+
boxes.append(box2)
44+
45+
return boxes
46+
47+
48+
class HeatMap(object):
49+
def __init__(self, threshold=2):
50+
self._threshold = threshold
51+
self._heat_map = None
52+
self._heat_bin = None
53+
54+
def get_boxes(self, boxes, w, h):
55+
"""
56+
# Args
57+
boxes : list of tuple (x1, y1, x2, y2)
58+
detected boxes
59+
w : int
60+
h : int
61+
62+
# Returns
63+
heat_boxes : list of tuple (x1, y1, x2, y2)
64+
"""
65+
66+
self._heat_map = np.zeros((h, w)).astype(float)
67+
68+
for box in boxes:
69+
x1, y1, x2, y2 = box
70+
self._heat_map[y1:y2, x1:x2] += 1
71+
72+
self._heat_bin = self._get_bin()
73+
heat_boxes = self._extract_boxes()
74+
return heat_boxes
75+
76+
77+
78+
def _get_bin(self):
79+
heat_map_bin = np.zeros_like(self._heat_map)
80+
heat_map_bin[self._heat_map >= self._threshold] = 255
81+
return heat_map_bin
82+
83+
def _extract_boxes(self):
84+
"""
85+
# Args
86+
heat_map : ndarray
87+
binary image
88+
"""
89+
def _box(ccl_map, car_number):
90+
# Find pixels with each car_number label value
91+
nonzero = (ccl_map == car_number).nonzero()
92+
# Identify x and y values of those pixels
93+
nonzeroy = np.array(nonzero[0])
94+
nonzerox = np.array(nonzero[1])
95+
# Define a bounding box based on min/max x and y
96+
x1 = np.min(nonzerox)
97+
y1 = np.min(nonzeroy)
98+
x2 = np.max(nonzerox)
99+
y2 = np.max(nonzeroy)
100+
return (x1, y1, x2, y2)
101+
102+
boxes = []
103+
ccl_map, n_labels = label(self._heat_bin)
104+
for car_number in range(1, n_labels+1):
105+
box = _box(ccl_map, car_number)
106+
boxes.append(box)
107+
return boxes
108+
109+
110+
if __name__ == '__main__':
111+
pass
112+
113+

0 commit comments

Comments
 (0)