Skip to content

Instantly share code, notes, and snippets.

@nmichlo
Created October 25, 2024 11:10
Show Gist options
  • Save nmichlo/26b1bb30e7ed98bfe0786ff429d76d75 to your computer and use it in GitHub Desktop.
Save nmichlo/26b1bb30e7ed98bfe0786ff429d76d75 to your computer and use it in GitHub Desktop.
golang coreml mlmodel & mlpackage inference example using darwinkit
package main
import (
"github.com/progrium/darwinkit/macos/coreml"
"github.com/progrium/darwinkit/macos/foundation"
"github.com/progrium/darwinkit/objc"
"log"
"unsafe"
)
func main() {
// convert with:
// $ xcrun coremlcompiler compile /path/to/file.mlpackage /outdir/
// $ xcrun coremlcompiler compile /path/to/file.mlmodel /outdir/
modelPath := "/path/to/model.mlmodelc"
imagePath := "/path/to/image.jpg"
log.Println("Image path:", imagePath)
log.Println("Model path:", modelPath)
// Load the model
var errModel foundation.Error
model := coreml.Model_ModelWithContentsOfURLError(
foundation.URL_FileURLWithPath(modelPath),
unsafe.Pointer(&errModel),
)
if !errModel.IsNil() {
log.Fatalf(errModel.Description())
}
log.Println("Model loaded successfully:", model.ModelDescription())
// Get the input descriptions, and find the one for "image"
inputDescriptions := model.ModelDescription().InputDescriptionsByName()
imageInputDesc := inputDescriptions["image"]
if imageInputDesc.IsNil() {
log.Fatalf("Input 'image' not found in model input descriptions")
return
}
imageInputConstraint := imageInputDesc.ImageConstraint()
log.Println("'image' input constraint:", imageInputConstraint.Description()) // Color, 640 x 640
// create features from image
var errImg foundation.Error
imageFeature := coreml.FeatureValue_FeatureValueWithImageAtURLConstraintOptionsError(
foundation.URL_FileURLWithPath(imagePath),
imageInputConstraint,
nil,
unsafe.Pointer(&errImg),
)
if !errImg.IsNil() {
log.Fatalf(errImg.Description())
}
log.Println("Image feature created successfully:", imageFeature.Description())
// predict
var errFeatures foundation.Error
featureProvider := coreml.NewDictionaryFeatureProvider()
featureProvider.InitWithDictionaryError(
map[string]objc.IObject{"image": imageFeature},
unsafe.Pointer(&errFeatures),
)
if !errFeatures.IsNil() {
log.Fatalf(errFeatures.Description())
}
log.Println("Feature provider created successfully:", featureProvider.Description())
obj := coreml.FeatureProviderObject{featureProvider.Object}
// prediction
var errPred foundation.Error
result := model.PredictionFromFeaturesError(obj, unsafe.Pointer(&errPred))
if !errPred.IsNil() {
log.Fatalf(errPred.Description())
}
log.Println("Prediction successful:", result.Description())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment