Classifier.py 2.39 KB
Newer Older
liucong's avatar
liucong committed
1
2
3
4
5
6
7
8
9
10
# -*- coding: utf-8 -*-
"""
分类器示例
"""

import cv2
import numpy as np
import migraphx

def Preprocessing(pathOfImage):
liucong's avatar
liucong committed
11
12
    # 读取图像
    image = cv2.imread(pathOfImage, cv2.IMREAD_COLOR)             
liucong's avatar
liucong committed
13
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
liucong's avatar
liucong committed
14
15
16
17
18
19
20
    
    # 调整大小,使短边为256,保持长宽比
    ratio = float(256) / min(image.shape[0], image.shape[1])
    if image.shape[0] > image.shape[1]:
        new_size = [int(round(ratio * image.shape[0])), 256]
    else:
        new_size = [256, int(round(ratio * image.shape[1]))]
liucong's avatar
liucong committed
21
    image = np.array(cv2.resize(image, (new_size[1],new_size[0])))
liucong's avatar
liucong committed
22
23
24
25
26
27
28
29
    
    # 裁剪中心窗口为224*224
    h, w, c = image.shape
    start_x = w//2 - 224//2
    start_y = h//2 - 224//2
    image = image[start_y:start_y+224, start_x:start_x+224, :]
    
    # transpose
liucong's avatar
liucong committed
30
    image = image.transpose(2, 0, 1)
liucong's avatar
liucong committed
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    
    # 将输入数据转换为float32
    img_data = image.astype('float32')
    
    # normalize
    mean_vec = np.array([123.675, 116.28, 103.53])
    stddev_vec = np.array([58.395, 57.12, 57.375])
    norm_img_data = np.zeros(img_data.shape).astype('float32')
    for i in range(img_data.shape[0]):
        norm_img_data[i,:,:] = (img_data[i,:,:] - mean_vec[i]) / stddev_vec[i]
    
    # 调整尺寸
    norm_img_data = norm_img_data.reshape(1, 3, 224, 224).astype('float32')
    return norm_img_data
liucong's avatar
liucong committed
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

if __name__ == '__main__':
    # 加载模型
    model = migraphx.parse_onnx("../Resource/Models/resnet50-v2-7.onnx")
    inputName=model.get_parameter_names()[0]
    inputShape=model.get_parameter_shapes()[inputName].lens()
    print("inputName:{0} \ninputShape:{1}".format(inputName,inputShape))

    # 编译
    model.compile(t=migraphx.get_target("gpu"),device_id=0) # device_id: 设置GPU设备,默认为0号设备

    # 预处理并转换为NCHW
    pathOfImage ="../Resource/Images/ImageNet_01.jpg"
    image = Preprocessing(pathOfImage)

    # 推理
    results = model.run({inputName: image}) # 推理结果,list类型

    # 获取输出节点属性
    result=results[0] # 获取第一个输出节点的数据,migraphx.argument类型
    outputShape=result.get_shape() # 输出节点的shape,migraphx.shape类型
    outputSize=outputShape.lens() # 每一维大小,维度顺序为(N,C,H,W),list类型
    numberOfOutput=outputShape.elements() # 输出节点元素的个数

    # 获取分类结果
liucong's avatar
liucong committed
70
    result=np.array(results[0])
liucong's avatar
liucong committed
71
72

    print(result)