JeVoisBase  1.22
JeVois Smart Embedded Machine Vision Toolkit Base Modules
Share this page:
Loading...
Searching...
No Matches
mobilenet_v2.py
Go to the documentation of this file.
1import numpy as np
2import cv2 as cv
3
5 def __init__(self, modelPath, labelPath, backendId=0, targetId=0):
6 self.model_path = modelPath
7 self.label_path = labelPath
8 self.backend_id = backendId
9 self.target_id = targetId
10
11 self.model = cv.dnn.readNet(self.model_path)
12 self.model.setPreferableBackend(self.backend_id)
13 self.model.setPreferableTarget(self.target_id)
14
15 self.input_names = ''
16 self.output_names = ''
17 self.input_size = [224, 224]
18 self.mean=[0.485, 0.456, 0.406]
19 self.std=[0.229, 0.224, 0.225]
20
21 # load labels
22 self.labels = self._load_labels()
23
24 def _load_labels(self):
25 labels = []
26 with open(self.label_path, 'r') as f:
27 for line in f:
28 labels.append(line.strip())
29 return labels
30
31 @property
32 def name(self):
33 return self.__class__.__name__
34
35 def setBackend(self, backendId):
36 self.backend_id = backendId
37 self.model.setPreferableBackend(self.backend_id)
38
39 def setTarget(self, targetId):
40 self.target_id = targetId
41 self.model.setPreferableTarget(self.target_id)
42
43 def _preprocess(self, image):
44 input_blob = (image / 255.0 - self.mean) / self.std
45 input_blob = input_blob.transpose(2, 0, 1)
46 input_blob = input_blob[np.newaxis, :, :, :]
47 input_blob = input_blob.astype(np.float32)
48 return input_blob
49
50 def infer(self, image):
51 # Preprocess
52 input_blob = self._preprocess(image)
53
54 # Forward
55 self.model.setInput(input_blob, self.input_names)
56 output_blob = self.model.forward(self.output_names)
57
58 # Postprocess
59 results = self._postprocess(output_blob)
60
61 return results
62
63 def _postprocess(self, output_blob):
64 predicted_labels = []
65 for o in output_blob:
66 class_id = np.argmax(o)
67 predicted_labels.append(self.labels[class_id])
68 return predicted_labels
69
_postprocess(self, output_blob)
__init__(self, modelPath, labelPath, backendId=0, targetId=0)
setBackend(self, backendId)
setTarget(self, targetId)