简体   繁体   English

从UIImage转换为MLMultiArray

[英]Converting from UIImage to MLMultiArray

I am using a pre-trained mlmodel for image classification. 我正在使用经过预先训练的mlmodel进行图像分类。 The model takes in as input a 3 x 224 x 224 MultiArray as the format for the image. 该模型将3 x 224 x 224 MultiArray作为图像格式输入。 For my current application, I am working with a UIImage. 对于当前的应用程序,我正在使用UIImage。 Is there a way to convert a UIImage to a MLMultiArray? 有没有一种方法可以将UIImage转换为MLMultiArray?

I have seen some answers regarding converting from a Keras model to a CoreML model, but my model is already in the mlmodel format and don't have access to the data. 我已经看到有关从Keras模型转换为CoreML模型的一些答案,但是我的模型已经是mlmodel格式,无法访问数据。

The easiest solution is to change the format of the input in the mlmodel file. 最简单的解决方案是更改mlmodel文件中的输入格式。 You can do this even if you don't have the original Keras model. 即使您没有原始的Keras模型,也可以执行此操作。

Do the following in a Python script: 在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")

It's also possible to convert the UIImage into an MLMultiArray, but if your model really works on images anyway, it's best to change the input type to an image. 也可以将UIImage转换为MLMultiArray,但是如果您的模型仍然可以在图像上正常工作,则最好将输入类型更改为图像。

By the way, if you still do have the original Keras model, you can automatically do this by providing image_input_names="your_input" to the coremltools Keras converter. 顺便说一句,如果您仍然拥有原始Keras模型,则可以通过向image_input_names="your_input" Keras转换器提供image_input_names="your_input"来自动执行此操作。 No need to write a new Python script in that case. 在这种情况下,无需编写新的Python脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM