-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.py
51 lines (36 loc) · 1.52 KB
/
utils.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
import cv2
import numpy as np
class ImageUtils:
@staticmethod
def read_stream(stream):
arrayed_image = np.frombuffer(stream.read(), dtype=np.uint8)
decoded_image = cv2.imdecode(arrayed_image, cv2.IMREAD_UNCHANGED)
return decoded_image
@staticmethod
def letterbox(image, size, padding_color):
current_size = max(image.shape[0], image.shape[1])
x1 = (current_size - image.shape[1]) >> 1
y1 = (current_size - image.shape[0]) >> 1
x2 = x1 + image.shape[1]
y2 = y1 + image.shape[0]
background = np.full((current_size, current_size, 3), padding_color, dtype=np.uint8)
background[y1:y2, x1:x2] = image
return cv2.resize(background, (size, size))
@staticmethod
def convert_inputs(image, precision):
inputs = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).transpose((2, 0, 1))
inputs = inputs / 255.0
inputs = np.expand_dims(inputs, axis=0)
if precision == 'fp16':
return inputs.astype(np.float16)
else:
return inputs.astype(np.float32)
@staticmethod
def preprocess(image, size, padding_color, precision):
return ImageUtils.convert_inputs(ImageUtils.letterbox(image, size, padding_color), precision)
class ResultUtils:
@staticmethod
def parse_outputs(outputs):
probability_outputs = np.exp(outputs) / np.sum(np.exp(outputs), axis=0)
class_index = np.argmax(probability_outputs)
return str(class_index), probability_outputs[class_index]