Toybrick

PC转官方例子出错

ooo

注册会员

积分
158
楼主
发表于 2021-11-24 12:53:45    查看: 3799|回复: 5 | [复制链接]    打印 | 只看该作者
背景说明 : 昨天尝试在板子转换ssd_inception_v2_coco的模型,一段时间后被系统kill了。随后在PC(Win7)安装rknn_toolkit-1.6.0,安装成功后,先尝试ssd_mobilenet_v1_coco模型的rknn转换,可以成功生成rknn模型,但报错Init runtime environment failed   (就简单在笔记本安装了rknn_toolkit-1.6.0,也没连接rk3399pro板子或rk1808计算棒,ret = rknn.init_runtime()也没指定rk3399pro或rk1808)

下面是test.py

import numpy as np

import re
import math
import random
import cv2

from rknn.api import RKNN

INPUT_SIZE = 300

NUM_RESULTS = 1917
NUM_CLASSES = 91

Y_SCALE = 10.0
X_SCALE = 10.0
H_SCALE = 5.0
W_SCALE = 5.0


def expit(x):
    return 1. / (1. + math.exp(-x))


def unexpit(y):
    return -1.0 * math.log((1.0 / y) - 1.0);


def CalculateOverlap(xmin0, ymin0, xmax0, ymax0, xmin1, ymin1, xmax1, ymax1):
    w = max(0.0, min(xmax0, xmax1) - max(xmin0, xmin1))
    h = max(0.0, min(ymax0, ymax1) - max(ymin0, ymin1))
    i = w * h
    u = (xmax0 - xmin0) * (ymax0 - ymin0) + (xmax1 - xmin1) * (ymax1 - ymin1) - i

    if u <= 0.0:
        return 0.0

    return i / u


def load_box_priors():
    box_priors_ = []
    fp = open('./box_priors.txt', 'r')
    ls = fp.readlines()
    for s in ls:
        aList = re.findall('([-+]?\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?', s)
        for ss in aList:
            aNum = float((ss[0]+ss[2]))
            box_priors_.append(aNum)
    fp.close()

    box_priors = np.array(box_priors_)
    box_priors = box_priors.reshape(4, NUM_RESULTS)

    return box_priors


if __name__ == '__main__':

    # Create RKNN object
    rknn = RKNN()

    # Config for Model Input PreProcess
    print('--> Config model')
    rknn.config(mean_values=[[127.5, 127.5, 127.5]], std_values=[[127.5, 127.5, 127.5]], reorder_channel='0 1 2')
    print('done')

    # Load TensorFlow Model
    print('--> Loading model')
    ret = rknn.load_tensorflow(tf_pb='./frozen_inference_graph.pb',
                               inputs=['FeatureExtractor/MobilenetV1/MobilenetV1/Conv2d_0/BatchNorm/batchnorm/mul_1'],
                               outputs=['concat', 'concat_1'],
                               input_size_list=[[INPUT_SIZE, INPUT_SIZE, 3]])
    if ret != 0:
        print('Load model failed!')
        exit(ret)
    print('done')

    # Build Model
    print('--> Building model')
    ret = rknn.build(do_quantization=True, dataset='./dataset.txt')
    if ret != 0:
        print('Build model failed!')
        exit(ret)
    print('done')

    # Export RKNN Model
    print('--> Export RKNN model')
    rknn.export_rknn('./tflite_graph.rknn')
    if ret != 0:
        print('Export RKNN model failed!')
        exit(ret)
    print('done')

    # Direct Load RKNN Model
    # rknn.load_rknn('./tflite_graph.rknn')

    # Set inputs
    orig_img = cv2.imread('./horizontal.bmp')
    img = cv2.cvtColor(orig_img, cv2.COLOR_BGR2RGB)
    img = cv2.resize(img, (INPUT_SIZE, INPUT_SIZE), interpolation=cv2.INTER_CUBIC)

    # init runtime environment
    print('--> Init runtime environment')
    ret = rknn.init_runtime()
    if ret != 0:
        print('Init runtime environment failed')
        exit(ret)
    print('done')

    # Inference
    print('--> Running model')
    outputs = rknn.inference(inputs=[img])
    print('done')

    predictions = outputs[0].reshape((1, NUM_RESULTS, 4))
    outputClasses = outputs[1].reshape((1, NUM_RESULTS, NUM_CLASSES))
    candidateBox = np.zeros([2, NUM_RESULTS], dtype=int)
    vaildCnt = 0

    box_priors = load_box_priors()

    # Post Process
    # got valid candidate box
    for i in range(0, NUM_RESULTS):
        topClassScore = -1000
        topClassScoreIndex = -1

        # Skip the first catch-all class.
        for j in range(1, NUM_CLASSES):
            score = expit(outputClasses[0][i][j]);

            if score > topClassScore:
                topClassScoreIndex = j
                topClassScore = score

        if topClassScore > 0.4:
            candidateBox[0][vaildCnt] = i
            candidateBox[1][vaildCnt] = topClassScoreIndex
            vaildCnt += 1

    # calc position
    for i in range(0, vaildCnt):
        if candidateBox[0][i] == -1:
            continue

        n = candidateBox[0][i]
        ycenter = predictions[0][n][0] / Y_SCALE * box_priors[2][n] + box_priors[0][n]
        xcenter = predictions[0][n][1] / X_SCALE * box_priors[3][n] + box_priors[1][n]
        h = math.exp(predictions[0][n][2] / H_SCALE) * box_priors[2][n]
        w = math.exp(predictions[0][n][3] / W_SCALE) * box_priors[3][n]

        ymin = ycenter - h / 2.
        xmin = xcenter - w / 2.
        ymax = ycenter + h / 2.
        xmax = xcenter + w / 2.

        predictions[0][n][0] = ymin
        predictions[0][n][1] = xmin
        predictions[0][n][2] = ymax
        predictions[0][n][3] = xmax

    # NMS
    for i in range(0, vaildCnt):
        if candidateBox[0][i] == -1:
            continue

        n = candidateBox[0][i]
        xmin0 = predictions[0][n][1]
        ymin0 = predictions[0][n][0]
        xmax0 = predictions[0][n][3]
        ymax0 = predictions[0][n][2]

        for j in range(i+1, vaildCnt):
            m = candidateBox[0][j]

            if m == -1:
                continue

            xmin1 = predictions[0][m][1]
            ymin1 = predictions[0][m][0]
            xmax1 = predictions[0][m][3]
            ymax1 = predictions[0][m][2]

            iou = CalculateOverlap(xmin0, ymin0, xmax0, ymax0, xmin1, ymin1, xmax1, ymax1)

            if iou >= 0.45:
                candidateBox[0][j] = -1

    # Draw result
    for i in range(0, vaildCnt):
        if candidateBox[0][i] == -1:
            continue

        n = candidateBox[0][i]

        xmin = max(0.0, min(1.0, predictions[0][n][1])) * INPUT_SIZE
        ymin = max(0.0, min(1.0, predictions[0][n][0])) * INPUT_SIZE
        xmax = max(0.0, min(1.0, predictions[0][n][3])) * INPUT_SIZE
        ymax = max(0.0, min(1.0, predictions[0][n][2])) * INPUT_SIZE

        # print("%d @ (%d, %d) (%d, %d) score=%f" % (topClassScoreIndex, xmin, ymin, xmax, ymax, topClassScore))
        cv2.rectangle(orig_img, (int(xmin), int(ymin)), (int(xmax), int(ymax)),
                      (random.random()*255, random.random()*255, random.random()*255), 3)

    cv2.imwrite("out.jpg", orig_img)

    # Evaluate Perf on Simulator
    print('--> Evaluate model performance')
    rknn.eval_perf(inputs=[img], is_print=True)
    print('done')

    # Release RKNN Context
    rknn.release()





下面是Anaconda Prompt窗口


(tensorflow) C:\Users\Administrator\ssd_mobilenet_v1_coco>python test.py
--> Config model
done
--> Loading model
W:tensorflow:From C:\Users\Administrator\Anaconda3\envs\tensorflow\lib\site-packages\rknn\api\rknn.py:75: extract_sub_graph (from tensorflow.python.fr
amework.graph_util_impl) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.compat.v1.graph_util.extract_sub_graph
done
--> Building model
W The target_platform is not set in config, using default target platform rk1808.
W:tensorflow:From C:\Users\Administrator\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\ops\control_flow_ops.py:3632: colocate_with (fr
om tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
W:tensorflow:From C:\Users\Administrator\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\ops\control_flow_ops.py:1941: py_func (from ten
sorflow.python.ops.script_ops) is deprecated and will be removed in a future version.
Instructions for updating:
tf.py_func is deprecated in TF V2. Instead, use
    tf.py_function, which takes a python function which manipulates tf eager
    tensors instead of numpy arrays. It's easy to convert a tf eager tensor to
    an ndarray (just call tensor.numpy()) but having access to eager tensors
    means `tf.py_function`s can use accelerators such as GPUs as well as
    being differentiable using a gradient tape.

done
--> Export RKNN model
done
--> Init runtime environment
E Catch exception when init runtime!
E Traceback (most recent call last):
E   File "rknn\api\rknn_base.py", line 815, in rknn.api.rknn_base.RKNNBase.init_runtime
E   File "rknn\api\rknn_runtime.py", line 162, in rknn.api.rknn_runtime.RKNNRuntime.__init__
E   File "rknn\api\rknn_runtime.py", line 225, in rknn.api.rknn_runtime.RKNNRuntime._load_library
E   File "rknn\api\rknn_platform_utils.py", line 66, in rknn.api.rknn_platform_utils.get_rknn_api_lib_path
E Exception: Simulator can not run on Windows_x64! Please set supported target!
Init runtime environment failed

回复

使用道具 举报

ooo

注册会员

积分
158
沙发
 楼主| 发表于 2021-11-24 15:17:02 | 只看该作者
没人么?toybrick的人回一下
回复

使用道具 举报

jefferyzhang

版主

积分
13658
板凳
发表于 2021-11-24 17:37:48 | 只看该作者
这么大log写着:
E Exception: Simulator can not run on Windows_x64! Please set supported target!
装个ubuntu用吧
回复

使用道具 举报

ooo

注册会员

积分
158
地板
 楼主| 发表于 2021-11-24 19:46:24 | 只看该作者
jefferyzhang 发表于 2021-11-24 17:37
这么大log写着:
E Exception: Simulator can not run on Windows_x64! Please set supported target!
装个 ...

你好,我只要是有四个疑问,希望得到解惑
①在上面我是不是已经正常转换为rknn模型了?只是他这个在推理的时候出现了问题?
②如果我把上面生成的rknn模型拿到板子上,能不能正常地推理?
③如果在Ubuntu上弄,要不要连接rk3399pro的板子或是插个rk1808棒才能仿真推理?
④ret = rknn.init_runtime()要不要指定rk3399pro或rk1808?
回复

使用道具 举报

jefferyzhang

版主

积分
13658
5#
发表于 2021-11-25 08:41:23 | 只看该作者
ooo 发表于 2021-11-24 19:46
你好,我只要是有四个疑问,希望得到解惑
①在上面我是不是已经正常转换为rknn模型了?只是他这个在推理 ...

1. 可转换,仿真不可在你当前系统运行
2. 可以
3. 不用,仿真器和目标机没关系
4. 仿真不需要写target,如果是目标机运行需要写

这些文档上都说的很清楚,多看看文档
回复

使用道具 举报

ooo

注册会员

积分
158
6#
 楼主| 发表于 2021-11-25 11:14:37 | 只看该作者
jefferyzhang 发表于 2021-11-25 08:41
1. 可转换,仿真不可在你当前系统运行
2. 可以
3. 不用,仿真器和目标机没关系

了解,感谢
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

产品中心 购买渠道 开源社区 Wiki教程 资料下载 关于Toybrick


快速回复 返回顶部 返回列表