import torch
import torchvision
# Load a pre-trained version of MobileNetV2
torch_model = torchvision.models.mobilenet_v2(pretrained=True)
# Set the model in evaluation mode.
torch_model.eval()
# Trace the model with random data.
example_input = torch.rand(1, 3, 224, 224)
traced_model = torch.jit.trace(torch_model, example_input)
# 여기서 sample input과 sample output에 대한 세팅이 진행된다
out = traced_model(example_input)
convert()
# Using image_input in the inputs parameter:
# Convert to Core ML using the Unified Conversion API.
model = ct.convert(
traced_model,
inputs=[ct.TensorType(shape=example_input.shape)]
)
# Save the converted model.
model.save("mobilenet.mlmodel")
guard let model = try? VNCoreMLModel(for: FaceParsing().model) else {
fatalError("Loading CoreML Model Failed.")
}
let handler : VNImageRequestHandler = VNImageRequestHandler(ciImage: inputImg as! CIImage)
do{
try! handler.perform([request])
}catch{
print("error")
}
let request = VNCoreMLRequest(model: model) {
request, error in
guard let results = request.results as? [VNCoreMLFeatureValueObservation],
let segmentationmap = results.first?.featureValue.multiArrayValue,
let row = segmentationmap.shape[0] as? Int,
let col = segmentationmap.shape[1] as? Int else {
fatalError("Model failed to process images.")
}
self.model_results = results
self.model_segmentationmap = segmentationmap
}
실제 코드
guard let model = try? VNCoreMLModel(for: FaceParsing().model) else {
fatalError("Loading CoreML Model Failed.")
}
let request = VNCoreMLRequest(model: model) {
request, error in
guard let results = request.results as? [VNCoreMLFeatureValueObservation],
let segmentationmap = results.first?.featureValue.multiArrayValue,
let row = segmentationmap.shape[0] as? Int,
let col = segmentationmap.shape[1] as? Int else {
fatalError("Model failed to process images.")
}
self.model_results = results
self.model_segmentationmap = segmentationmap
}
let handler : VNImageRequestHandler = VNImageRequestHandler(ciImage: inputImg as! CIImage)
do{
try! handler.perform([request])
}catch{
print("error")
}
Ref)
https://coremltools.readme.io/docs/what-are-coreml-tools