如何修改KerasCV训练的YOLOV8Detector以适配CoreML输出格式
解决KerasCV YOLOv8转CoreML输出格式适配问题
步骤1:加载训练好的YOLOv8模型
先加载已训练完成的YOLOV8Detector模型并加载对应权重:
import tensorflow as tf from keras_cv.models import YOLOV8Detector # 按训练时的配置初始化模型 num_classes = 你的类别数量 bounding_box_format = "xyxy" # 替换为训练时实际使用的格式,如"xywh" model = YOLOV8Detector( backbone="yolo_v8_xs_backbone", num_classes=num_classes, bounding_box_format=bounding_box_format ) # 加载训练好的权重文件 model.load_weights("your_trained_weights.h5")
步骤2:构建适配CoreML的包装模型
CoreML要求输出为独立张量而非字典,因此创建新模型提取并转换原模型的输出:
def adapt_model_for_coreml(original_model, box_format="xyxy"): inputs = original_model.input output_dict = original_model(inputs) # 转换检测框格式为CoreML常用的归一化xyxy格式 boxes = output_dict["boxes"] if box_format == "xywh": # xywh转xyxy:左上角x、左上角y、右下角x、右下角y x_center, y_center, w, h = tf.split(boxes, 4, axis=-1) x_min = x_center - w / 2 y_min = y_center - h / 2 x_max = x_center + w / 2 y_max = y_center + h / 2 boxes = tf.concat([x_min, y_min, x_max, y_max], axis=-1) # 提取每个检测框的最高类别置信度(适配CoreML常用输出形状) confidence = tf.reduce_max(output_dict["confidence"], axis=-1) # 创建新模型并设置输出名称(适配Xcode预览识别) coreml_model = tf.keras.Model( inputs=inputs, outputs=[boxes, confidence], name="YOLOv8_CoreML_Adapter" ) coreml_model.output_names = ["detection_boxes", "detection_confidence"] return coreml_model # 生成适配后的模型 coreml_ready_model = adapt_model_for_coreml(model, bounding_box_format)
步骤3:转换为CoreML MLPackage格式
使用coremltools将模型转换为CoreML格式并保存为MLPackage:
import coremltools as ct # 定义输入图像类型,匹配模型输入尺寸(如640x640) input_shape = coreml_ready_model.input_shape[1:] # 去除batch维度,示例:(640, 640, 3) image_input = ct.ImageType( name="image", shape=input_shape, scale=1/255.0 # 必须与训练时的图像归一化逻辑一致 ) # 转换模型为MLProgram格式(对应MLPackage) mlmodel = ct.convert( coreml_ready_model, inputs=[image_input], outputs=[ ct.TensorType(name="detection_boxes"), ct.TensorType(name="detection_confidence") ], convert_to="mlprogram" ) # 保存为MLPackage mlmodel.save("YOLOv8_Detector.mlpackage")
关键注意事项
- 坐标格式:CoreML目标检测模型默认期望归一化的
xyxy格式,务必保证转换逻辑与训练时的框格式匹配。 - 输出命名:使用
detection_boxes和detection_confidence作为输出名称,Xcode预览模式会自动识别并展示检测结果。 - 置信度处理:原模型输出的
confidence为(batch, num_detections, num_classes)形状,通过tf.reduce_max处理后得到(batch, num_detections)形状,更符合CoreML使用习惯。 - 归一化匹配:转换时的
scale参数必须和训练时的图像预处理一致,避免模型推理结果偏差。
内容的提问来源于stack exchange,提问作者yageek
相关产品推荐
相关产品推荐

