RDK X5 ,YOLOV8 转换模型报错

第一步下载模型

yolov8 https://github.com/ultralytics/ultralytics

第二步训练模型

yolo train data=自定义.yaml model=yolov8s.pt pretrained=True project=Train_640 name=n_pretrain epochs=1000 batch=4 device=0 patience=0 lr0=0.001 lrf=0.001

第三步转换模型onnx

1、修改head.py

class Detect(nn.Module):

...
   
   #新增forward  
   def forward(self, x):
        bboxes = [self.cv2[i](x[i]).permute(0, 2, 3, 1).contiguous() for i in range(self.nl)]
        clses = [self.cv3[i](x[i]).permute(0, 2, 3, 1).contiguous() for i in range(self.nl)]
        return (bboxes, clses)
    
   #重命名 forward -> forward_
   def forward_(self, x): 
        """Concatenates and returns predicted bounding boxes and class probabilities."""
        if self.end2end:
            return self.forward_end2end(x)

        for i in range(self.nl):
            x[i] = torch.cat((self.cv2[i](x[i]), self.cv3[i](x[i])), 1)
        if self.training:  # Training path
            return x
        y = self._inference(x)
        return y if self.export else (y, x)

...

class Segment(Detect)
   #新增forward  
   def forward(self, x):
        p = self.proto(x[0]).permute(0, 2, 3, 1).contiguous()  # mask protos
        results = []
        for i in range(self.nl):
            box = self.cv2[i](x[i]).permute(0, 2, 3, 1).contiguous()
            cls = self.cv3[i](x[i]).permute(0, 2, 3, 1).contiguous()
            mask = self.cv4[i](x[i]).permute(0, 2, 3, 1).contiguous()
            results.append(cls)
            results.append(box)
            results.append(mask)
        results.append(p)
        return tuple(results)

    #重命名 forward -> forward_
    def forward_(self, x):
        """Return model outputs and mask coefficients if training, otherwise return outputs and mask coefficients."""
        p = self.proto(x[0])  # mask protos
        bs = p.shape[0]  # batch size

        mc = torch.cat([self.cv4[i](x[i]).view(bs, self.nm, -1) for i in range(self.nl)], 2)  # mask coefficients
        x = Detect.forward(self, x)
        if self.training:
            return x, mc, p
        return (torch.cat([x, mc], 1), p) if self.export else (torch.cat([x[0], mc], 1), (x[1], mc, p))

2、导出ONNX

from ultralytics import YOLO

YOLO('H:/git/ultralytics/volleyball/best.pt').export(imgsz=640, format='onnx', simplify=True, opset=11)

第四步Docker环境准备 参考:

RDK X5 算法工具链社区手册:https://developer.d-robotics.cc/api/v1/fileData/x5_doc-v126cn/index.html

1、下载
wget -c ftp://x5ftp@vrftp.horizon.ai/OpenExplorer/v1.2.6_release/docker_openexplorer_ubuntu_20_x5_cpu_v1.2.6.tar.gz --ftp-password=x5ftp@123$%
2、加载
docker load --input docker_openexplorer_ubuntu_20_x5_cpu_v1.2.6.tar.gz
3、查看
docker image list
4、挂载
docker run -it -v "H:\horizonx5\codes":/data/horizon_x5/codes -v "H:\horizonx5\data":/data/horizon_x5/data openexplorer/ai_toolchain_ubuntu_20_x5_cpu:v1.2.6

第五步转换模型onnx

1、检查模型

 hb_mapper checker --model-type onnx --march bayes-e --model yolov8.onnx

2、验证集准备 生成校准数据集 使用 generate_calibration_data.py

https://github.com/D-Robotics/rdk_model_zoo/tree/main/demos/tools/generate_calibration_data

3、转换模型

转换配置文件 yolov8_onnx_convert.yaml

# 模型转化相关的参数
model_parameters:
  # 必选参数
  # Onnx浮点网络数据模型文件, 例如:onnx_model: './horizon_x3_onnx.onnx'
  onnx_model: './yolov8.onnx'
  march: "bayes-e"
  layer_out_dump: False
  working_dir: 'model_output'
  output_model_file_prefix: 'horizon_x5'
  node_info: {"/model.10/m/m.0/attn/Softmax": {'ON': 'BPU','InputType': 'int16','OutputType': 'int16'}}
              
# 模型输入相关参数
input_parameters:
  input_name: ""
  input_type_rt: 'nv12'
  input_type_train: 'rgb'
  input_layout_train: 'NCHW'
  norm_type: 'data_scale'
  scale_value: 0.003921568627451

# 模型量化相关参数
calibration_parameters:
  # 必选参数, 使用2.1中的图片路径
  cal_data_dir: './calibration_data_rgb_f32_640' 
  cal_data_type: 'float32'
# 编译器相关参数
compiler_parameters:
  compile_mode: 'latency'
  debug: False
  # core_num: 2	
  optimize_level: 'O3'

转换命令执行

hb_mapper makertbin --config yolov8_onnx_convert.yaml --model-type onnx

此处报错:

2025-01-16 10:25:03,245 ERROR load cal data for input 'images' error

2025-01-16 10:25:03,249 ERROR cannot reshape array of size 307200 into shape (1,3,640,640)

生成的校准数据是uint8存储的,而读取是以float32读取的。那个生成的脚本只是一个示例,需要根据需要修改。

谢谢超哥,改成int8编译过了

3、转换模型 转换配置文件 yolov8_onnx_convert.yaml

cal_data_type: ‘float32’ 改成 ‘int8’ 转换过了-
但是后面放到x5上执行-
export CAM_TYPE=mipi-

# 启动launch文件-
ros2 launch dnn_node_example dnn_node_example.launch.py dnn_example_config_file:=config/myyolov8workconfig.json-

异常

改成int8 后续调用有问题,-
# 配置MIPI摄像头

export CAM_TYPE=mipi

# 启动launch文件

ros2 launch dnn_node_example dnn_node_example.launch.py dnn_example_config_file:=config/myyolov8workconfig.json

你好,请前往机器人开发章节发帖,除了发帖规范外,还需要提供hrt_model_exec model_info --model_file 命令提供的信息

root@3b80807aa032:/data/horizon_x5/codes/model_output# hrt_model_exec model_info --model_file horizon_x5.bin

hrt_model_exec model_info --model_file horizon_x5.bin

I0000 00:00:00.000000 18 vlog_is_on.cc:197] RAW: Set VLOG level for “*” to 3

core[0] open!

core[1] open!

[HBRT] set log level as 0. version = 3.15.54.0

[DNN] Runtime version = 1.23.10_(3.15.54 HBRT)

[A][DNN][packed_model.cpp:247][Model](2025-01-23,10:53:25.813.630) [HorizonRT] The model builder version = 1.23.8

Load model to DDR cost 286.915ms.

This model file has 1 model:

[horizon_x5]

---------------------------------------------------------------------

[model name]: horizon_x5

input[0]:

name: images

input source: HB_DNN_INPUT_FROM_PYRAMID

valid shape: (1,3,640,640,)

aligned shape: (1,3,640,640,)

aligned byte size: 614400

tensor type: HB_DNN_IMG_TYPE_NV12

tensor layout: HB_DNN_LAYOUT_NCHW

quanti type: NONE

stride: (0,0,0,0,)

output[0]:

name: output0

valid shape: (1,80,80,64,)

aligned shape: (1,80,80,64,)

aligned byte size: 1638400

tensor type: HB_DNN_TENSOR_TYPE_F32

tensor layout: HB_DNN_LAYOUT_NHWC

quanti type: NONE

stride: (1638400,20480,256,4,)

output[1]:

name: 326

valid shape: (1,40,40,64,)

aligned shape: (1,40,40,64,)

aligned byte size: 409600

tensor type: HB_DNN_TENSOR_TYPE_F32

tensor layout: HB_DNN_LAYOUT_NHWC

quanti type: NONE

stride: (409600,10240,256,4,)

output[2]:

name: 334

valid shape: (1,20,20,64,)

aligned shape: (1,20,20,64,)

aligned byte size: 102400

tensor type: HB_DNN_TENSOR_TYPE_F32

tensor layout: HB_DNN_LAYOUT_NHWC

quanti type: NONE

stride: (102400,5120,256,4,)

output[3]:

name: 342

valid shape: (1,80,80,1,)

aligned shape: (1,80,80,1,)

aligned byte size: 25600

tensor type: HB_DNN_TENSOR_TYPE_F32

tensor layout: HB_DNN_LAYOUT_NCHW

quanti type: NONE

stride: (25600,320,4,4,)

output[4]:

name: 350

valid shape: (1,40,40,1,)

aligned shape: (1,40,40,1,)

aligned byte size: 6400

tensor type: HB_DNN_TENSOR_TYPE_F32

tensor layout: HB_DNN_LAYOUT_NCHW

quanti type: NONE

stride: (6400,160,4,4,)

output[5]:

name: 358

valid shape: (1,20,20,1,)

aligned shape: (1,20,20,1,)

aligned byte size: 1600

tensor type: HB_DNN_TENSOR_TYPE_F32

tensor layout: HB_DNN_LAYOUT_NCHW

quanti type: NONE

stride: (1600,80,4,4,)

---------------------------------------------------------------------

root@3b80807aa032:/data/horizon_x5/codes/model_output#

执行 ros2 launch dnn_node_example dnn_node_example.launch.py dnn_example_config_file:=config/myyolov8workconfig.json dnn_example_image_width:=640 dnn_example_image_height:=640

报错-

root@ubuntu:/home/sunrise/share/hobot_dnn-develop/dnn_node_example# ros2 launch dnn_node_example dnn_node_example.launch.py dnn_example_config_file:=config/myyolov8workconfig.json dnn_example_image_width:=640 dnn_example_image_height:=640

[INFO] [launch]: All log files can be found below /root/.ros/log/2025-01-23-10-49-54-157251-ubuntu-6107

[INFO] [launch]: Default logging verbosity is set to INFO

dnn_node_example_path is /opt/tros/humble/lib/dnn_node_example

cp_cmd is cp -r /opt/tros/humble/lib/dnn_node_example/config .

camera_type is mipi

using mipi cam

Hobot shm pkg enables zero-copy with fastrtps profiles file: /opt/tros/humble/lib/hobot_shm/config/shm_fastdds.xml

Hobot shm pkg sets RMW_FASTRTPS_USE_QOS_FROM_XML: 1

config_file_path is /opt/tros/humble/lib/mipi_cam/config/

env of RMW_FASTRTPS_USE_QOS_FROM_XML is 1 , ignore env setting

env of RMW_FASTRTPS_USE_QOS_FROM_XML is 1 , ignore env setting

webserver has launch

env of RMW_FASTRTPS_USE_QOS_FROM_XML is 1 , ignore env setting

config_file_path is /opt/tros/humble/lib/mipi_cam/config/

env of RMW_FASTRTPS_USE_QOS_FROM_XML is 1 , ignore env setting

env of RMW_FASTRTPS_USE_QOS_FROM_XML is 1 , ignore env setting

env of RMW_FASTRTPS_USE_QOS_FROM_XML is 1 , ignore env setting

env of RMW_FASTRTPS_USE_QOS_FROM_XML is 1 , ignore env setting

webserver has launch

[INFO] [mipi_cam-1]: process started with pid [6113]

[INFO] [hobot_codec_republish-2]: process started with pid [6115]

[INFO] [example-3]: process started with pid [6117]

[INFO] [websocket-4]: process started with pid [6119]

[hobot_codec_republish-2] [WARN] [1737600594.714994895] [hobot_codec_encoder]: Parameters:

[hobot_codec_republish-2] sub_topic: /hbmem_img

[hobot_codec_republish-2] pub_topic: /image

[hobot_codec_republish-2] channel: 1

[hobot_codec_republish-2] in_mode: shared_mem

[hobot_codec_republish-2] out_mode: ros

[hobot_codec_republish-2] in_format: nv12

[hobot_codec_republish-2] out_format: jpeg

[hobot_codec_republish-2] enc_qp: 10

[hobot_codec_republish-2] jpg_quality: 60

[hobot_codec_republish-2] input_framerate: 30

[hobot_codec_republish-2] output_framerate: -1

[hobot_codec_republish-2] dump_output: 0

[hobot_codec_republish-2] [WARN] [1737600594.720961255] [HobotCodecImpl]: platform x5

[hobot_codec_republish-2] [WARN] [1737600594.721199797] [hobot_codec_encoder]: Enabling zero-copy

[example-3] [WARN] [1737600595.026228719] [dnn_example_node]: Parameter:

[example-3] feed_type(0:local, 1:sub): 1

[example-3] image: config/test.jpg

[example-3] image_type: 0

[example-3] dump_render_img: 0

[example-3] is_shared_mem_sub: 1

[example-3] config_file: config/myyolov8workconfig.json

[example-3] msg_pub_topic_name: hobot_dnn_detection

[example-3] info_msg_pub_topic_name: hobot_dnn_detection_info

[example-3] ros_img_topic_name: /image

[example-3] sharedmem_img_topic_name: /hbmem_img

[example-3] [WARN] [1737600595.027284140] [dnn_example_node]: Load [1] class types from file [/home/sunrise/share/myyolov8/coco.list]

[example-3] [WARN] [1737600595.027450599] [dnn_example_node]: Parameter:

[example-3] model_file_name: /home/sunrise/share/myyolov8/horizon_x5.bin

[example-3] model_name:

[example-3] [WARN] [1737600595.027546683] [dnn_example_node]: model_file_name_: /home/sunrise/share/myyolov8/horizon_x5.bin, task_num: 4

[mipi_cam-1] [WARN] [1737600595.027432766] [mipi_node]: dual_combine value: 0

[mipi_cam-1] [WARN] [1737600595.027603183] [mipi_node]: frame_ts_type value: realtime

[mipi_cam-1] [WARN] [1737600595.038410522] [mipi_factory]: board_type X5_RDK

[mipi_cam-1]

[mipi_cam-1] [WARN] [1737600595.039608111] [mipi_cam]: this board support mipi:

[mipi_cam-1] [WARN] [1737600595.039920946] [mipi_cam]: host 0

[mipi_cam-1] [WARN] [1737600595.039997529] [mipi_cam]: host 2

[mipi_cam-1] [WARN] [1737600595.040304364] [mipi_cam]: Camera calibration file: /_calibration.yaml is not exist!

[mipi_cam-1] If you need calibration msg, please make sure the calibration file path is correct and the calibration file exists!

[example-3] [BPU_PLAT]BPU Platform Version(1.3.6)!

[example-3] [HBRT] set log level as 0. version = 3.15.55.0

[example-3] [DNN] Runtime version = 1.24.5_(3.15.55 HBRT)

[websocket-4] [WARN] [1737600595.070121663] [websocket]:

[websocket-4] Parameter:

[websocket-4] image_topic: /image

[websocket-4] image_type: mjpeg

[websocket-4] only_show_image: 0

[websocket-4] smart_topic: hobot_dnn_detection

[websocket-4] output_fps: 0

[example-3] [A][DNN][packed_model.cpp:247][Model](2025-01-23,10:49:55.246.226) [HorizonRT] The model builder version = 1.23.8

[example-3] [WARN] [1737600595.434356897] [dnn_example_node]: Get model name: horizon_x5 from load model.

[example-3] [WARN] [1737600595.434549189] [dnn_example_node]: Create ai msg publisher with topic_name: hobot_dnn_detection

[example-3] [WARN] [1737600595.448653835] [dnn_example_node]: Create img hbmem_subscription with topic_name: /hbmem_img

[mipi_cam-1] [WARN] [1737600599.273880219] [mipi_cap]: gdc bin file h���� open failed

[mipi_cam-1]

[hobot_codec_republish-2] [ERROR] [1737600599.721337505] [hobot_codec_encoder]: Hobot_Codec has not received image for more than 5 seconds! Please check whether the image publisher still exists by ‘ros2 topic info /hbmem_img’!

[websocket-4] [ERROR] [1737600600.099774355] [websocket]: Websocket did not receive image data! Please check whether the image publisher still exists by ‘ros2 topic info /image’!

[websocket-4] [ERROR] [1737600600.099962939] [websocket]: Websocket did not receive AI data! Please check whether the AI data publisher still exists by ‘ros2 topic info hobot_dnn_detection’!

[mipi_cam-1] [WARN] [1737600600.335008808] [mipi_cam]: [init]->cap F37 init success.

[mipi_cam-1]

[mipi_cam-1] [WARN] [1737600600.335258351] [mipi_cam]: Enabling zero-copy

[example-3] [WARN] [1737600600.428721821] [dnn_example_node]: Loaned messages are only safe with const ref subscription callbacks. If you are using any other kind of subscriptions, set the ROS_DISABLE_LOANED_MESSAGES environment variable to 1 (the default).

[hobot_codec_republish-2] [WARN] [1737600600.428721404] [hobot_codec_encoder]: Loaned messages are only safe with const ref subscription callbacks. If you are using any other kind of subscriptions, set the ROS_DISABLE_LOANED_MESSAGES environment variable to 1 (the default).

[hobot_codec_republish-2] [WARN] [1737600600.429007364] [HobotVenc]: init_pic_w_: 640, init_pic_h_: 640, alined_pic_w_: 640, alined_pic_h_: 640, aline_w_: 16, aline_h_: 16

[example-3] [WARN] [1737600600.429013239] [dnn_example_node]: Recved img encoding: nv12, h: 640, w: 640, step: 640, index: 0, stamp: 1737600600_428130985, data size: 614400, comm delay [0.8624]ms

[hobot_codec_republish-2] [WARN] [1737600600.537508153] [hobot_codec_encoder]: Pub img fps [0.17]

[ERROR] [example-3]: process has died [pid 6117, exit code -11, cmd ‘/opt/tros/humble/lib/dnn_node_example/example --ros-args --log-level warn --ros-args --params-file /tmp/launch_params_1kbaejp6 --params-file /tmp/launch_params_cdnx4x3g --params-file /tmp/launch_params_sl68jttd --params-file /tmp/launch_params_oe0perdt --params-file /tmp/launch_params_t0lp6f94’].

[hobot_codec_republish-2] [WARN] [1737600601.554274997] [hobot_codec_encoder]: sub nv12 640x640, fps: 34.3474, pub jpeg, fps: 34.3474, comm delay [3.5429]ms, codec delay [4.4857]ms

[websocket-4] [ERROR] [1737600605.099911400] [websocket]: Websocket did not receive AI data! Please check whether the AI