Skip to content

Instantly share code, notes, and snippets.

@iosdevie
Created May 26, 2021 05:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iosdevie/25fe2019766d7e2ee23a07a97d11c1e3 to your computer and use it in GitHub Desktop.
Save iosdevie/25fe2019766d7e2ee23a07a97d11c1e3 to your computer and use it in GitHub Desktop.
Predict an image using MLModel
func predict(image: UIImage) -> Animal? {
let imageConstraint = model.modelDescription.inputDescriptionsByName["image"]!.imageConstraint!
do{
let imageOptions: [MLFeatureValue.ImageOption: Any] = [
.cropAndScale: VNImageCropAndScaleOption.scaleFill.rawValue
]
let featureValue = try MLFeatureValue(cgImage: image.cgImage!, constraint: imageConstraint, options: imageOptions)
let featureProviderDict = try MLDictionaryFeatureProvider(dictionary: ["image" : featureValue])
let prediction = try updatableModel?.prediction(from: featureProviderDict)
let value = prediction?.featureValue(for: "classLabel")?.stringValue
if value == "Dog"{
return .dog
}
else{
return .cat
}
}catch(let error){
print("error is \(error.localizedDescription)")
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment