从 UIImage 转换为 MLMultiArray

Roh*_*han 3 multidimensional-array ios swift coreml coremltools

我正在使用预训练的 mlmodel 进行图像分类。该模型将 3 x 224 x 224 MultiArray 作为输入作为图像格式。对于我当前的应用程序,我正在使用 UIImage。有没有办法将 UIImage 转换为 MLMultiArray?

我已经看到了一些关于从 Keras 模型转换为 CoreML 模型的答案,但我的模型已经是 mlmodel 格式并且无法访问数据。

Mat*_*ans 9

最简单的解决方案是更改 mlmodel 文件中输入的格式。即使您没有原始的 Keras 模型,您也可以这样做。

在 Python 脚本中执行以下操作:

import coremltools
import coremltools.proto.FeatureTypes_pb2 as ft 

spec = coremltools.utils.load_spec("YourModel.mlmodel")

input = spec.description.input[0]
input.type.imageType.colorSpace = ft.ImageFeatureType.RGB
input.type.imageType.height = 224 
input.type.imageType.width = 224

coremltools.utils.save_spec(spec, "YourNewModel.mlmodel")
Run Code Online (Sandbox Code Playgroud)

也可以将 UIImage 转换为 MLMultiArray,但如果您的模型确实适用于图像,最好将输入类型更改为图像。

顺便说一句,如果您仍然拥有原始的 Keras 模型,您可以通过提供image_input_names="your_input"给 coremltools Keras 转换器来自动执行此操作。在这种情况下无需编写新的 Python 脚本。

  • 是的,Core ML 使用 CVPixelBuffer 而不是 UIImage。但将 UIImage 转换为 CVPixelBuffer 相对简单。请参阅 https://github.com/hollance/CoreMLHelpers (2认同)