Skip to content

Commit de3783e

Browse files
authored
Add files via upload
1 parent 5bfdfa8 commit de3783e

File tree

5 files changed

+342
-74
lines changed

5 files changed

+342
-74
lines changed

PredictionRunner.py

Lines changed: 41 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
import argparse
22
import multiprocessing
33
import os
4-
import os
5-
import os
4+
import json
65
import queue
76
import shutil
87
import threading
@@ -36,6 +35,8 @@
3635
ap.add_argument("-r", "--results", required=False,
3736
default=70,
3837
help="Prius Results")
38+
ap.add_argument("-z", "--test", required=False,
39+
help="True for test",default=False)
3940
args = vars(ap.parse_args())
4041

4142
q = queue.Queue()
@@ -96,11 +97,11 @@ def predict_vehicle(self, image_meta):
9697
eachProbability) + " at path: " + image_meta['image_path'])
9798

9899
result = {
99-
"time": str(dlocaltime()),
100+
"time": str(time.localtime()),
100101
"image_name": image_meta["image_name"],
101102
"image_path": image_meta["image_path"],
102103
"probability": str(eachProbability),
103-
"object": str(eachObject)
104+
"object": str(eachPrediction)
104105
}
105106

106107
save_result(result)
@@ -109,6 +110,39 @@ def predict_vehicle(self, image_meta):
109110

110111
return dict(result=found, prob=prius_prob)
111112

113+
def predict_array(self, decoded):
114+
start = time.time()
115+
found_prius = False
116+
prius_prob = 0
117+
try:
118+
prius.detect_vehicle_from_array(decoded)
119+
#prediction_meta = dict(image_name=eachObject['name'], image_points=eachObject["box_points"],
120+
# image_path=eachObjectPath)
121+
122+
#if has_prius_color(eachObjectPath, eachObjectPath):
123+
# result_meta = self.predict_vehicle(prediction_meta)
124+
# found_prius = result_meta['result']
125+
# prius_prob = result_meta['prob']
126+
'''
127+
except Exception as e:
128+
print("Exception while predicting: " + str(e))
129+
130+
try:
131+
if found_prius:
132+
shutil.copy(os.path.join(image_meta['image_path'], image_meta['image_name']),
133+
args['output'] + 'detection/match_' + str(prius_prob) + "_" + image_meta['image_name'])
134+
135+
if args['test'] is False:
136+
shutil.move(os.path.join(image_meta['image_path'], image_meta['image_name']),
137+
args['output'] + 'processed/' + image_meta['image_name'])
138+
'''
139+
except Exception as e:
140+
print("Exception while predicting: " + str(e))
141+
142+
end = time.time()
143+
print("Prediction Time: " + str(end - start))
144+
145+
112146
def predict(self, image_meta):
113147
start = time.time()
114148
found_prius = False
@@ -130,8 +164,9 @@ def predict(self, image_meta):
130164
shutil.copy(os.path.join(image_meta['image_path'], image_meta['image_name']),
131165
args['output'] + 'detection/match_' + str(prius_prob) + "_" + image_meta['image_name'])
132166

133-
shutil.move(os.path.join(image_meta['image_path'], image_meta['image_name']),
134-
args['output'] + 'processed/' + image_meta['image_name'])
167+
if args['test'] is False:
168+
shutil.move(os.path.join(image_meta['image_path'], image_meta['image_name']),
169+
args['output'] + 'processed/' + image_meta['image_name'])
135170

136171
except Exception as e:
137172
print("Exception while predicting: " + str(e))

PriusObjectDetection.py

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def __init__(self, image_path, model_path, output_path):
2222
self.detector = ObjectDetection()
2323
self.detector.setModelTypeAsYOLOv3()
2424
self.detector.setModelPath(model_path + "yolo.h5")
25-
self.detector.loadModel()
25+
self.detector.loadModel(detection_speed="flash")
2626

2727
self.prediction = CustomImagePrediction()
2828
self.prediction.setModelTypeAsResNet()
@@ -72,10 +72,10 @@ def detect_pca(self, image):
7272

7373
def detect_vehicle(self, meta_data):
7474
try:
75+
7576
image = os.path.join(meta_data["image_path"], meta_data['image_name'])
7677
output_image = self.output_path + meta_data['image_name']
77-
print("Detecting vehicle for " + meta_data['image_name'] + " -> " + output_image)
78-
78+
#print("Detecting vehicle for " + meta_data['image_name'] + " -> " + output_image)
7979
if os.path.exists(image) is not True:
8080
print("File doesnt exist. File: " + image)
8181
custom_objects = self.detector.CustomObjects(car=True)
@@ -87,4 +87,18 @@ def detect_vehicle(self, meta_data):
8787

8888
return zip(detections, objects_path)
8989
except Exception as e:
90-
print("While detecting vehicle: " + str(e))
90+
print("While detecting vehicle: " + str(e))
91+
92+
def detect_vehicle_from_array(self, decoded):
93+
94+
#print("Detecting vehicle for " + meta_data['image_name'] + " -> " + output_image)
95+
96+
custom_objects = self.detector.CustomObjects(car=True)
97+
result = self.detector.detectCustomObjectsFromImage(custom_objects=custom_objects,
98+
input_type="array",
99+
input_image=np.array(decoded),
100+
#output_type="array",
101+
minimum_percentage_probability=50)
102+
103+
print("Detected: " + str(result))
104+
return result

image_test.py

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
import time
2+
import json
3+
import cv2
4+
import numpy as np
5+
import requests
6+
from PIL import Image
7+
from imageai.Detection import ObjectDetection
8+
from imageai.Prediction.Custom import CustomImagePrediction
9+
from prius_color import has_prius_color_from_array
10+
11+
def write_json(data, filename= "prius_results.json"):
12+
with open(filename, "w") as f:
13+
json.dump(data, f, indent=4)
14+
15+
16+
17+
def save_result(result):
18+
with open("prius_results.json") as json_file:
19+
data = json.load(json_file)
20+
temp = data
21+
22+
temp.append(result)
23+
write_json(data)
24+
25+
26+
27+
detector = ObjectDetection()
28+
detector.setModelTypeAsYOLOv3()
29+
detector.setModelPath("./yolo.h5")
30+
detector.loadModel(detection_speed="fastest")
31+
32+
prediction = CustomImagePrediction()
33+
prediction.setModelTypeAsResNet()
34+
# self.prediction.setModelPath(model_path + "model_ex-012_acc-0.988819.h5")
35+
prediction.setModelPath("./model_ex-043_acc-0.996787.h5")
36+
prediction.setJsonPath("./model_class.json")
37+
prediction.loadModel(prediction_speed="fastest")
38+
39+
custom_objects = detector.CustomObjects(car=True)
40+
41+
accuracy = 0
42+
imgs = []
43+
44+
data = requests.get("http://seattle.gov/trafficcams/images/15_NW_65_NS.jpg").content
45+
decoded = cv2.imdecode(np.frombuffer(data, np.uint8), -1)
46+
imgs.append(decoded)
47+
data = requests.get("http://seattle.gov/trafficcams/images/15_NW_65_NS.jpg").content
48+
decoded = cv2.imdecode(np.frombuffer(data, np.uint8), -1)
49+
imgs.append(decoded)
50+
51+
for decoded in imgs:
52+
53+
start1 = time.time()
54+
result = detector.detectCustomObjectsFromImage(custom_objects=custom_objects,
55+
input_type="array",
56+
extract_detected_objects=True,
57+
input_image=np.array(decoded),
58+
output_type="array",
59+
minimum_percentage_probability=50)
60+
start2 = time.time()
61+
print("Detection Time: " + str(start2 - start1))
62+
detected = []
63+
for arr in result[1]:
64+
(x1, y1, x2, y2) = arr["box_points"]
65+
img = decoded[y1:y2, x1:x2]
66+
67+
colorStart = time.time()
68+
has_color = has_prius_color_from_array(img)
69+
colorEnd = time.time()
70+
print("has_color Time: " + str(colorEnd - colorStart))
71+
72+
if has_color is not True:
73+
start2 = time.time()
74+
predictions, probabilities = prediction.predictImage(img, input_type="array", result_count=2)
75+
start3 = time.time()
76+
77+
print("Prediction Time: " + str(start3 - start2))
78+
for eachPrediction, eachProbability in zip(predictions, probabilities):
79+
if "prius" in eachPrediction and eachProbability > accuracy:
80+
try:
81+
success = {
82+
#'timestamp': frame_time,
83+
# 'image_name': frame_file,
84+
# 'image_path': frame_dir,
85+
# 'cam_id': str(cam['id']),
86+
'probability': str(eachProbability)
87+
#'predictor': 'series'
88+
}
89+
r = requests.post("http://priusvision.azurewebsites.net/api/PriusTrigger", data=json.dumps(success))
90+
print("----> PRIUS IDENTIFIED. Data: " + str(success))
91+
except Exception as e:
92+
print("Saving Prius result failed: " + str(e))
93+
save_result(success)
94+
95+
if r.status_code is not 200:
96+
print("POST Failed. Saving manually.")
97+
save_result(success)
98+
99+
with open("./test/img2.jpg", 'wb') as handler:
100+
handler.write(data)
101+
102+
cv2.imwrite("./test/img1.jpg", img)
103+
104+
105+
106+
107+
108+
109+

prius_color.py

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ def save_result(result, file):
181181

182182

183183
def find_significant_contour(img):
184-
contours, hierarchy = cv2.findContours(
184+
image,contours, hierarchy = cv2.findContours(
185185
img,
186186
cv2.RETR_EXTERNAL,
187187
cv2.CHAIN_APPROX_SIMPLE
@@ -207,14 +207,17 @@ def find_significant_contour(img):
207207
contoursWithArea.sort(key=lambda meta: meta[1], reverse=True)
208208
return contoursWithArea[0][0]
209209

210-
211210
def get_contour_colors(image_src):
212211
# load the image and resize it to a smaller factor so that
213212
# the shapes can be approximated better
214213
# image = cv2.imread(os.path.join(path,image))
215-
try:
216-
image = cv2.imread(image_src)
214+
return get_contour_colors_from_array(cv2.imread(image_src))
217215

216+
def get_contour_colors_from_array(image):
217+
# load the image and resize it to a smaller factor so that
218+
# the shapes can be approximated better
219+
# image = cv2.imread(os.path.join(path,image))
220+
try:
218221
resized = imutils.resize(image, width=300)
219222
ratio = image.shape[0] / float(resized.shape[0])
220223
# blur the resized image slightly, then convert it to both
@@ -243,17 +246,25 @@ def get_contour_colors(image_src):
243246
def has_prius_contour(image):
244247
colors = get_contour_colors(image)
245248
for color in colors:
246-
if color in prius_color:
249+
if color in prius_colors:
250+
return True
251+
return False
252+
253+
def has_prius_contour_from_array(arr):
254+
colors = get_contour_colors_from_array(arr)
255+
for color in colors:
256+
if color in prius_colors:
247257
return True
248258
return False
249259

250-
def detect_color(image_src, image_name):
260+
def detect_color(image_src):
261+
return detect_color_from_array(cv2.imread(image_src))
262+
263+
def detect_color_from_array(image):
251264
# load the image and resize it to a smaller factor so that
252265
# the shapes can be approximated better
253266
# image = cv2.imread(os.path.join(path,image))
254267
try:
255-
image = cv2.imread(image_src)
256-
257268
resized = imutils.resize(image, width=300)
258269
ratio = image.shape[0] / float(resized.shape[0])
259270
# blur the resized image slightly, then convert it to both
@@ -266,19 +277,20 @@ def detect_color(image_src, image_name):
266277
# find contours in the thresholded image
267278
cnts = find_significant_contour(thresh.copy())
268279

269-
# cnts = imutils.grab_contours(cnts)
270-
# initialize the shape detector and color labeler
271280
cl = ColorLabeler()
272-
273281
color = cl.label(lab, cnts)
274-
275-
#print("Image " + image_name + " has contour with color " + str(color))
276282
return color
277283
except Exception as e:
278284
print("While detecting color: " + str(e))
279285

280-
def has_prius_color(image, image_name):
281-
detected_color = detect_color(image, image_name)
286+
def has_prius_color(image):
287+
detected_color = detect_color(image)
288+
if detected_color in prius_colors:
289+
return True
290+
return False
291+
292+
def has_prius_color_from_array(image):
293+
detected_color = detect_color_from_array(image)
282294
if detected_color in prius_colors:
283295
return True
284296
return False

0 commit comments

Comments
 (0)