Skip to content

Commit 6eafe84

Browse files
authored
Add files via upload
1 parent 3dc1fa4 commit 6eafe84

File tree

4 files changed

+1047
-19
lines changed

4 files changed

+1047
-19
lines changed

watch_cameras.py

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,17 @@
1313
from PIL import Image
1414

1515
from PriusImageCache import ImageDeduplication
16-
from imageai.Detection import ObjectDetection
16+
from yolo4 import Yolo4
1717
from imageai.Prediction.Custom import CustomImagePrediction
1818
from prius_color import has_prius_color_from_array
1919
from prius_color import has_prius_contour_from_array
2020

21+
import colorsys
22+
from keras import backend as K
23+
from keras.models import load_model
24+
from keras.layers import Input
25+
26+
2127
import warnings
2228
warnings.filterwarnings('ignore', category=DeprecationWarning)
2329
warnings.filterwarnings('ignore', category=FutureWarning)
@@ -30,8 +36,6 @@
3036
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
3137
deprecation._PER_MODULE_WARNING_LIMIT = 0
3238

33-
34-
3539
cams = []
3640

3741
cam_threads = []
@@ -49,27 +53,28 @@
4953
help='Output Path')
5054
ap.add_argument("-a", "--accuracy", default=50,
5155
help="predict accuracy")
52-
ap.add_argument("-y", "--detectspeed", default='normal',
53-
help="detection speed")
5456
ap.add_argument("-z", "--predictspeed", default='normal',
5557
help="prediction speed")
5658
ap.add_argument("-n", "--name", default='predictor1',
5759
help="name")
5860
ap.add_argument("-m", "--models", default='./',
5961
help='model path')
60-
ap.add_argument("-q", "--model", default='model_ex-011_acc-0.869792.h5',
62+
ap.add_argument("-q", "--model", default='model_ex-006_acc-0.994420.h5',
6163
help='model')
6264

6365
args = vars(ap.parse_args())
6466

6567
if os.path.isdir(args['output']) is False:
6668
os.mkdir(args['output'])
6769

68-
detector = ObjectDetection()
69-
detector.setModelTypeAsYOLOv3()
70-
detector.setModelPath(args['models'] + "yolo.h5")
71-
detector.loadModel(detection_speed=args["detectspeed"])
72-
custom_objects = detector.CustomObjects(car=True)
70+
model_path = args['models'] + 'yolo4_weight.h5'
71+
anchors_path = args['models'] + 'yolo4_anchors.txt'
72+
classes_path = args['models'] + 'coco_classes.txt'
73+
74+
score = 0.5
75+
iou = 0.5
76+
model_image_size = (608, 608)
77+
yolo4_model = Yolo4(score, iou, anchors_path, classes_path, model_path)
7378

7479
prediction = CustomImagePrediction()
7580
prediction.setModelTypeAsResNet()
@@ -123,18 +128,14 @@ def watch_camera(cam):
123128
decoded = cv2.imdecode(np.frombuffer(img_data, np.uint8), -1)
124129

125130
#start1 = time.time()
126-
result = detector.detectCustomObjectsFromImage(custom_objects=custom_objects,
127-
input_type="array",
128-
extract_detected_objects=True,
129-
input_image=decoded,
130-
output_type="array",
131-
minimum_percentage_probability=50)
131+
result = yolo4_model.detect_image(decoded, model_image_size=model_image_size)
132+
132133
#start2 = time.time()
133134

134135
#print("Detection Time: " + str(start2 - start1))
135136

136-
for arr in result[1]:
137-
(x1, y1, x2, y2) = arr["box_points"]
137+
for car in result:
138+
(x1, y1, x2, y2) = car["box"]
138139
img = decoded[y1:y2, x1:x2]
139140

140141
#start2 = time.time()

yolo4.py

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
import os
2+
import colorsys
3+
4+
import numpy as np
5+
from keras import backend as K
6+
from keras.models import load_model
7+
from keras.layers import Input
8+
9+
from yolo4_model.model import yolo_eval, yolo4_body
10+
from yolo4_model.utils import letterbox_image
11+
12+
class Yolo4(object):
13+
def get_class(self):
14+
classes_path = os.path.expanduser(self.classes_path)
15+
with open(classes_path) as f:
16+
class_names = f.readlines()
17+
class_names = [c.strip() for c in class_names]
18+
return class_names
19+
20+
def get_anchors(self):
21+
anchors_path = os.path.expanduser(self.anchors_path)
22+
with open(anchors_path) as f:
23+
anchors = f.readline()
24+
anchors = [float(x) for x in anchors.split(',')]
25+
return np.array(anchors).reshape(-1, 2)
26+
27+
def load_yolo(self):
28+
model_path = os.path.expanduser(self.model_path)
29+
assert model_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.'
30+
31+
self.class_names = self.get_class()
32+
self.anchors = self.get_anchors()
33+
34+
num_anchors = len(self.anchors)
35+
num_classes = len(self.class_names)
36+
37+
# Generate colors for drawing bounding boxes.
38+
hsv_tuples = [(x / len(self.class_names), 1., 1.)
39+
for x in range(len(self.class_names))]
40+
self.colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
41+
self.colors = list(
42+
map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),
43+
self.colors))
44+
45+
self.sess = K.get_session()
46+
47+
# Load model, or construct model and load weights.
48+
self.yolo4_model = yolo4_body(Input(shape=(608, 608, 3)), num_anchors//3, num_classes)
49+
self.yolo4_model.load_weights(model_path)
50+
51+
print('{} model, anchors, and classes loaded.'.format(model_path))
52+
53+
if self.gpu_num>=2:
54+
self.yolo4_model = multi_gpu_model(self.yolo4_model, gpus=self.gpu_num)
55+
56+
self.input_image_shape = K.placeholder(shape=(2, ))
57+
self.boxes, self.scores, self.classes = yolo_eval(self.yolo4_model.output, self.anchors,
58+
len(self.class_names), self.input_image_shape,
59+
score_threshold=self.score)
60+
61+
def __init__(self, score, iou, anchors_path, classes_path, model_path, gpu_num=1):
62+
self.score = score
63+
self.iou = iou
64+
self.anchors_path = anchors_path
65+
self.classes_path = classes_path
66+
self.model_path = model_path
67+
self.gpu_num = gpu_num
68+
self.load_yolo()
69+
70+
def close_session(self):
71+
self.sess.close()
72+
73+
def detect_image(self, image, model_image_size=(608, 608)):
74+
start = timer()
75+
76+
boxed_image = letterbox_image(image, tuple(reversed(model_image_size)))
77+
image_data = np.array(boxed_image, dtype='float32')
78+
79+
80+
image_data /= 255.
81+
image_data = np.expand_dims(image_data, 0) # Add batch dimension.
82+
83+
out_boxes, out_scores, out_classes = self.sess.run(
84+
[self.boxes, self.scores, self.classes],
85+
feed_dict={
86+
self.yolo4_model.input: image_data,
87+
self.input_image_shape: [image.size[1], image.size[0]],
88+
K.learning_phase(): 0
89+
})
90+
91+
print('Found {} boxes for {}'.format(len(out_boxes), 'img'))
92+
93+
#font = ImageFont.truetype(font='font/FiraMono-Medium.otf',
94+
# size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32'))
95+
#thickness = (image.size[0] + image.size[1]) // 300
96+
cars = []
97+
for i, c in reversed(list(enumerate(out_classes))):
98+
predicted_class = self.class_names[c]
99+
100+
if "car" in predicted_class:
101+
car = {
102+
"box": out_boxes[i],
103+
"score": out_scores[i]
104+
}
105+
cars.append(car)
106+
return cars
107+
'''
108+
label = '{} {:.2f}'.format(predicted_class, score)
109+
draw = ImageDraw.Draw(image)
110+
label_size = draw.textsize(label, font)
111+
112+
top, left, bottom, right = box
113+
top = max(0, np.floor(top + 0.5).astype('int32'))
114+
left = max(0, np.floor(left + 0.5).astype('int32'))
115+
bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))
116+
right = min(image.size[0], np.floor(right + 0.5).astype('int32'))
117+
print(label, (left, top), (right, bottom))
118+
119+
if top - label_size[1] >= 0:
120+
text_origin = np.array([left, top - label_size[1]])
121+
else:
122+
text_origin = np.array([left, top + 1])
123+
124+
# My kingdom for a good redistributable image drawing library.
125+
for i in range(thickness):
126+
draw.rectangle(
127+
[left + i, top + i, right - i, bottom - i],
128+
outline=self.colors[c])
129+
draw.rectangle(
130+
[tuple(text_origin), tuple(text_origin + label_size)],
131+
fill=self.colors[c])
132+
draw.text(text_origin, label, fill=(0, 0, 0), font=font)
133+
del draw
134+
'''

0 commit comments

Comments
 (0)