LPRNet_migraphx_infer.py 3.76 KB
Newer Older
liuhy's avatar
liuhy committed
1
2
3
4
5
6
7
# -*- coding: utf-8 -*-
"""
MIGraphX示例程序
"""
import cv2
import numpy as np
import migraphx
liuhy's avatar
liuhy committed
8
9
import argparse
import os
liuhy's avatar
liuhy committed
10
import time
liuhy's avatar
liuhy committed
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

CHARS = ['京', '沪', '津', '渝', '冀', '晋', '蒙', '辽', '吉', '黑',
         '苏', '浙', '皖', '闽', '赣', '鲁', '豫', '鄂', '湘', '粤',
         '桂', '琼', '川', '贵', '云', '藏', '陕', '甘', '青', '宁',
         '新',
         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
         'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K',
         'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
         'W', 'X', 'Y', 'Z', 'I', 'O', '-'
         ]

def LPRNetPreprocess(image):
    img = cv2.imread(image)
    img = cv2.resize(img, (94, 24)).astype('float32')
    img -= 127.5
    img *= 0.0078125
liuhy's avatar
liuhy committed
27
28
    # img = np.expand_dims(img.transpose(2, 0, 1), 0)
    img = np.ascontiguousarray(np.expand_dims(img.transpose(2, 0, 1), 0))
liuhy's avatar
liuhy committed
29
30
31
    return img

def LPRNetPostprocess(infer_res):
liuhy's avatar
liuhy committed
32
    preb_label = np.argmax(infer_res, axis=1)[0]
liuhy's avatar
liuhy committed
33
34
35
36
37
38
39
40
41
42
43
44
45
46
    no_repeat_blank_label = []
    pre_c = preb_label[0]
    if pre_c != len(CHARS) - 1:
        no_repeat_blank_label.append(pre_c)
    for c in preb_label:  # dropout repeate label and blank label
        if (pre_c == c) or (c == len(CHARS) - 1):
            if c == len(CHARS) - 1:
                pre_c = c
            continue
        no_repeat_blank_label.append(c)
        pre_c = c
    result = ''.join(list(map(lambda x: CHARS[x], no_repeat_blank_label)))
    return result

liuhy's avatar
liuhy committed
47
def LPRNetInference(args):
liuhy's avatar
liuhy committed
48
    # 加载模型
liuhy's avatar
liuhy committed
49
50
    if args.model[-3:] == 'mxr':
        model = migraphx.load(args.model)
liuhy's avatar
liuhy committed
51
    else:
liuhy's avatar
liuhy committed
52
        print('convert onnx to mxr...')
liuhy's avatar
liuhy committed
53
        model = migraphx.parse_onnx(args.model)
liuhy's avatar
liuhy committed
54
        model.compile(t=migraphx.get_target("gpu"),device_id=0) # device_id: 设置GPU设备,默认为0号设备(>=1.2版本中支持)
liuhy's avatar
liuhy committed
55
        migraphx.save(model, args.savepath)
liuhy's avatar
liuhy committed
56

liuhy's avatar
liuhy committed
57
58
    if os.path.isdir(args.imgpath):
        images = os.listdir(args.imgpath)
liuhy's avatar
liuhy committed
59
60
61
        Tp = 0
        Tn_1 = 0
        Tn_2 = 0
liuhy's avatar
liuhy committed
62
        time1 = time.perf_counter()
liuhy's avatar
liuhy committed
63
64
        for image in images:
            img = LPRNetPreprocess(os.path.join(args.imgpath, image))
liuhy's avatar
liuhy committed
65
66
            inputName = model.get_parameter_names()[0]
            inputShape = model.get_parameter_shapes()[inputName].lens()
liuhy's avatar
liuhy committed
67
68
69
            # print("inputName:{0} \ninputShape:{1}".format(inputName,inputShape))
            results = model.run({inputName: migraphx.argument(img)})
            result = LPRNetPostprocess(np.array(results[0]))
liuhy's avatar
liuhy committed
70
            if result == image[:-4]:
liuhy's avatar
liuhy committed
71
72
73
74
75
76
                Tp += 1
            elif len(result) != len(image[:-4]):
                Tn_1 += 1
            else:
                Tn_2 += 1
            print(image + ' Inference Result:', result)
liuhy's avatar
liuhy committed
77
        time2 = time.perf_counter()
liuhy's avatar
liuhy committed
78
79
80
        Acc = Tp * 1.0 / (Tp + Tn_1 + Tn_2)
        print("[Info] Test Accuracy: {} [{}:{}:{}:{}]".format(Acc, Tp, Tn_1, Tn_2, (Tp+Tn_1+Tn_2)))
        print("[Info] Test Speed: {}s 1/{}]".format((time2 - time1) / len(images), len(images))) 
liuhy's avatar
liuhy committed
81
82
83
84
85
86
87
88
    else:
        img = LPRNetPreprocess(args.imgpath)
        inputName=model.get_parameter_names()[0]
        inputShape=model.get_parameter_shapes()[inputName].lens()
        # print("inputName:{0} \ninputShape:{1}".format(inputName,inputShape))
        results = model.run({inputName: migraphx.argument(img)})
        result = LPRNetPostprocess(np.array(results[0]))
        print('Inference Result:', result)
liuhy's avatar
liuhy committed
89
90

if __name__ == '__main__':
liuhy's avatar
liuhy committed
91
    parser = argparse.ArgumentParser(description='parameters to vaildate net')
liuhy's avatar
liuhy committed
92
    parser.add_argument('--model', default='model/LPRNet.onnx', help='model path to inference')
liuhy's avatar
liuhy committed
93
    parser.add_argument('--imgpath', default='imgs', help='the image path')
liuhy's avatar
liuhy committed
94
95
96
97
    parser.add_argument('--savepath', default='model/LPRNet.mxr', help='mxr model save path and name')
    args = parser.parse_args()

    LPRNetInference(args)