-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvehicle_classification_service.py
74 lines (59 loc) · 2.28 KB
/
vehicle_classification_service.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import numpy as np
from tensorflow import expand_dims
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import img_to_array, load_img
from configparser import ConfigParser
config = ConfigParser()
config.read("./config.ini")
MODEL_PATH = config["LOCAL"]["MODEL_PATH"]
IMAGE_SIZE = (300, 300)
class VehicleClassification:
_instance = None
model = None
_mappings = [
"Two-wheeler",
"Bus",
"Car"
]
def process_image(self, image_path):
""" preprocessing of a vehicle image provided by image path before prediction
:param image_path (str) - path of image under prediction
:return img_array (ndarray) : image array data
"""
img = load_img(image_path, target_size=IMAGE_SIZE)
img_array = img_to_array(img)
# Create a batch by increase dimensions
img_array = expand_dims(img_array, 0)
print(img_array.shape)
return img_array
def predict_class(self, image_path):
""" Predict class of a vehicle image provided by image path
:param image_path (str): path of image under prediction
:return class of vehicle (str): a class from _mappings
"""
img_array = self.process_image(image_path)
predictions = self.model.predict(img_array)
vehicle = self._mappings[np.argmax(abs(predictions))]
return vehicle
def classification_engine(model_path=MODEL_PATH):
""" Factory function for VehicleClassification class
:param model_path (str): path of serialised model
:return VehicleClassification._instance (ndarray):
"""
if VehicleClassification._instance is None:
VehicleClassification._instance = VehicleClassification()
VehicleClassification.model = load_model(model_path)
return VehicleClassification._instance
if __name__ == "__main__":
vcs = classification_engine(MODEL_PATH)
# make a prediction
keyword = vcs.predict_class("./temp/b1.jpeg")
print(keyword)
keyword = vcs.predict_class("./temp/b2.jpeg")
print(keyword)
keyword = vcs.predict_class("./temp/b3.jpeg")
print(keyword)
keyword = vcs.predict_class("./temp/b4.jpeg")
print(keyword)
keyword = vcs.predict_class("./temp/b5.jpeg")
print(keyword)