Python示例
更新时间:2024-05-16
Python接口
Python接口目录结构
EdgeBoard系统已经安装了python环境,用户可直接使用即可,同时python接口为用户提供了paddlemobile的python安装包以及示例工程,下载链接,包含文件如下:
| 文件名称 | 说明 |
|---|---|
| paddlemobile-0.0.1.linux-aarch64-py2.tar.gz | paddlemobile的python2安装包 |
| edgeboard.py | 基于python的模型预测示例 |
| api.py | edgeboard.py的api示例 |
| configs.classification | 分类模型的配置文件目录,同C++示例的配置文件 |
| configs.detection | 检测模型的配置文件目录,同C++示例的配置文件 |
| models.classification | 分类模型的模型文件目录,同C++示例的模型文件 |
| models.detection | 检测模型的模型文件目录,同C++示例的模型文件 |
edgeboard.py代码如下:
Python
1#!/usr/bin/python
2# -*- coding: UTF-8 -*-
3
4import errno
5import math
6import os
7import sys
8import json
9
10import cv2
11import numpy as np
12
13import paddlemobile as pm
14
15predictor = None
16labels = []
17
18def init(configs):
19 global predictor
20
21 model_dir = configs['model']
22 pm_config = pm.PaddleMobileConfig() # 创建paddlemobile配置对象
23 pm_config.precision = pm.PaddleMobileConfig.Precision.FP32 # 对精度赋值成FP32
24 pm_config.device = pm.PaddleMobileConfig.Device.kFPGA # 选定FPGA
25 pm_config.prog_file = model_dir + "/model"
26 pm_config.param_file = model_dir + '/params'
27 pm_config.thread_num = 4
28
29 print('')
30 print('configuration for predictor is :')
31 print('\tPrecision: ' + str(pm_config.precision))
32 print('\t Device: ' + str(pm_config.device))
33 print('\t Model: ' + str(pm_config.prog_file))
34 print('\t Params: ' + str(pm_config.param_file))
35 print('\tThreadNum: ' + str(pm_config.thread_num))
36 print('')
37
38 predictor = pm.CreatePaddlePredictor(pm_config) # 创建预测器
39
40# 读取label_list.txt文件
41def read_labels(configs):
42 global labels
43 if not 'labels' in configs:
44 return
45 label_path = configs['labels']
46 if label_path is None or label_path == '':
47 return
48 with open(label_path) as label_file:
49 line = label_file.readline()
50 while line:
51 labels.append(line.strip().split(':')[-1])
52 line = label_file.readline()
53
54# 读取本地图片
55def read_image(configs):
56 image_input = cv2.imread(configs['image'], cv2.IMREAD_COLOR)
57 return image_input
58
59# 图像预处理
60def preprocess_image(image_input, configs):
61 # resizing image
62 print('image shape input: ' + str(image_input.shape))
63 width = configs['input_width']
64 height = configs['input_height']
65 image_resized = cv2.resize(image_input, (width, height), cv2.INTER_CUBIC)
66 print('image shape resized: ' + str(image_resized.shape))
67
68 # to float32
69 image = image_resized.astype('float32')
70
71 # transpose to channel-first format
72 image_transposed = np.transpose(image, (2, 0, 1))
73 print('image shape transposed: ' + str(image_transposed.shape))
74
75 # mean and scale preprocessing
76 mean = np.array(configs['mean']).reshape((3, 1, 1))
77 scale_number = configs['scale']
78 scale = np.array([scale_number, scale_number, scale_number]).reshape((3, 1, 1))
79
80 # RGB or BGR formatting
81 format = configs['format'].upper()
82 if format == 'RGB':
83 b = image_transposed[0]
84 g = image_transposed[1]
85 r = image_transposed[2]
86 image_transposed = np.stack([r, g, b])
87 print('image shape formatted transposed: ' + str(image_transposed.shape))
88
89 # mean and scale
90 print 'substract mean', mean.flatten(), ' and multiple with scale', scale.flatten()
91 image_transposed -= mean
92 image_transposed *= scale
93
94 # transpose back
95 image_result = np.transpose(image_transposed, (1, 2, 0))
96 print('image shape transposed-back: ' + str(image_result.shape))
97
98 print('')
99 return image_result
100
101# 检测模型输出结果图片
102def draw_results(image, output, threshold):
103 height, width, _ = image.shape
104 print 'boxes with scores above the threshold (%f): \n' % threshold
105 i = 1
106 for box in output:
107 if box[1] > threshold:
108 print '\t', i, '\t', box[0], '\t', box[1], '\t', box[2], '\t', box[3], '\t', box[4], '\t', box[5]
109 x_min = int(box[2] * width )
110 y_min = int(box[3] * height)
111 x_max = int(box[4] * width )
112 y_max = int(box[5] * height)
113 cv2.rectangle(image, (x_min, y_min), (x_max, y_max), (0, 255, 0), 3)
114 i += 1
115 cv2.imwrite('result.jpg', image)
116 print('')
117
118# 分类模型预测结果输出
119def classify(output, configs):
120 data = output.flatten()
121 max_index = 0
122 score = 0.0
123 for i in range(len(data)):
124 if data[i] > score and not data[i] == float('inf'):
125 max_index = i
126 score = data[i]
127
128 print 'label: ', labels[max_index]
129 print 'index: ', max_index
130 print 'score: ', score
131 print ''
132
133# 检测模型预测结果输出
134def detect(output, configs):
135 image = read_image(configs)
136 draw_results(image, output, configs['threshold'])
137
138# 模型预测
139def predict(configs, detection):
140 global predictor
141 width = configs['input_width']
142 height = configs['input_height']
143
144 image = read_image(configs)
145 input = preprocess_image(image, configs)
146
147 tensor = pm.PaddleTensor()
148 tensor.dtype = pm.PaddleDType.FLOAT32
149 tensor.shape = (1, 3, width, height)
150 tensor.data = pm.PaddleBuf(input)
151
152 paddle_data_feeds = [tensor]
153
154 print('prediction is running ...')
155 outputs = predictor.Run(paddle_data_feeds)
156 assert len(outputs) == 1, 'error numbers of tensor returned from Predictor.Run function !!!'
157
158 output = np.array(outputs[0], copy = False)
159
160 print('\nprediction result :')
161 print('\t nDim: ' + str(output.ndim))
162 print('\tShape: ' + str(output.shape))
163 print('\tDType: ' + str(output.dtype))
164 print('')
165 # print(output)
166 # print('')
167 if detection:
168 detect(output, configs)
169 else:
170 classify(output, configs)
api.py代码如下:
Python
1#!/usr/bin/python
2# -*- coding: UTF-8 -*-
3
4import errno
5import math
6import os
7import sys
8import argparse
9import json
10
11import cv2
12import numpy as np
13
14import edgeboard
15
16# 参数设定
17def parse_args():
18 parser = argparse.ArgumentParser(description='API implementation for Paddle-Mobile')
19 parser.add_argument('-d', '--detection',
20 help='flag indicating detections',
21 action="store_true")
22 parser.add_argument('-j', '--json',
23 help='configuration file for the prediction')
24 return parser.parse_args()
25
26# 输出参数
27def print_args(args):
28 print 'Arguments: '
29 print '\t', ' detection flag: ', args.detection
30 print '\t', 'json configuration: ', args.json
31
32# 主函数
33def main():
34 args = parse_args()
35 print_args(args)
36 if args.json is None or args.json == '':
37 print '\nFor usage, please use the -h switch.\n\n'
38 sys.exit(0)
39
40 with open(args.json) as json_file:
41 configs = json.load(json_file)
42
43 edgeboard.init(configs)
44 edgeboard.read_labels(configs)
45 edgeboard.predict(configs, args.detection)
46
47if __name__ == '__main__':
48 sys.exit(main())
安装和使用
1、拷贝paddlemobile-0.0.1.linux-aarch64-py2.tar.gz到用户目录,例如拷贝至/home/root/workspace/目录下
2、安装paddlemobile-python SDK,请在根目录中展开tar.gz压缩包
Plain Text
1//进入系统根目录
2cd /
3
4//展开tar.gz 压缩包
5tar -xzvf home/root/workspace/paddlemobile-0.0.1.linux-aarch64-py2.tar.gz
6
7//返回用户HOME目录
8cd
9
10//检查package paddlemobile (0.0.1) 是否已经安装
11pip list
3、把EdgeBoard的paddle-mobile预测库到/usr/lib目录下
EdgeBoard软核升级文件的版本(fpgadrv.ko、paddlemobile.so、image.ub&BOOT.BIN)必须版本一致才能正确运行,请升级软核版本。
1.3.0版本以上的预测库包含版本号,需连同ln.sh脚本文件一同拷贝到usr/lib目录下,并执行脚本文件sh ln.sh如下图所示:
4、查看配置文件,调用python接口api.py。python接口的配置文件同C++示例配置文件结构相同,在运行自己的模型时需要更改模型文件及对应的配置文件,在此不再赘述。
本地图片预测示例
1、分类模型预测
Plain Text
1 python api.py -j {分类模型json文件}
例如:运行预置模型Inceptionv3
Plain Text
1 python api.py -j configs.classification/Inceptionv3/zebra.json
如下图:
2、检测模型预测
Plain Text
1python api.py -d -j {检测模型json文件}
例如:运行预置模型vgg-ssd
Plain Text
1python api.py -d -j configs.detection/vgg-ssd/screw.json
如下图:
预测结果图:
