Part 4. Deploying a YOLO v3 Model on iOS with CoreML
Sharing how to deploy a YOLO v3 model in an iOS application using CoreML.
Part 1. Building a More Realistic AR App with Deep Learning
Part 2. Building an iOS AR App with ARKit
Part 3. Creating a Custom YOLO v3 Model
✔︎ Part 4. Deploying a YOLO v3 Model on iOS with CoreML
Using CoreML
CoreML is Apple's machine learning framework, which helps you easily put machine learning models into iOS applications.
✔︎ Outline
- Creating an mlmodel with CoreML Tools
- Putting the model on iOS with CoreML
Creating an mlmodel with CoreML Tools
To put a model on with CoreML, you first need to convert the model to the .mlmodel format, which you can easily do with CoreML Tools. CoreML Tools doesn't support the Darknet format, which is why I converted the Darknet model to a Keras model earlier and trained with that.
Converting a keras model to an mlmodel with CoreML Tools
import coremltools
coreml_model = coremltools.converters.keras.convert('model_data/light_tiny_model.h5',
image_input_names='image',
input_names='image',
output_names=['13'],
image_scale=1/255.0)
coreml_model.output_description['13'] = '13 x 13 x 30'
coreml_model.save('model_data/light_tiny_model.mlmodel')The Tiny YOLO model trained in Part 3 divides the image into a 13 x 13 Grid and predicts 3 boxes per Grid cell for 5 classes, so it returns a result of 13 x 13 x 30, which is why I set the output as above.
N x N x (C + 5) x B)
- N x N : Grid
- C : Number of trained Objects (Classes)
- 5 : Bounding Box information of the detected Object (x, y, w, h, confidence)
- B : Number of boxes per Grid cell
Putting the Model on iOS with CoreML
Once you add the light_tiny_model.mlmodel model to an iOS project, you can use it as follows.
Load mlmodel
import CoreML
let model = light_tiny_model()The Model has a prediction function that takes a CVPixelBuffer of size 416 x 416 as an argument.
model prediction
model.prediction(image: CVPixelBuffer)You can get a real-time CVPixelBuffer using the ARFrame.capturedImage in ARSessionDeligate's session(_:didUpdate:) function.
Function called every frame
func session(_ session: ARSession, didUpdate frame: ARFrame) {
model.prediction(image: frame.capturedImage)
}Model Input Image Preprocessing
TinyYOLO-CoreML, which was a big reference for this project, uses
AVCaptureVideoDataOutputSampleBufferDelegaterather thanARSessionDelegate.
On the same iPhone, ARKit's ARSessionDelegate and AVFoundation's AVCaptureVideoDataOutputSampleBufferDelegate return different images.
// AVCaptureVideoDataOutputSampleBufferDelegate
CVPixelBuffer Height : 1280
CVPixelBuffer Width : 720
// ARSessionDelegate
CVPixelBuffer Height : 1440
CVPixelBuffer Width : 1920The ARSessionDelegate used in this project returns an image rotated to the left, so preprocessing is needed to rotate the image to the right and convert it to 416 x 416, the Model's input size.
For preprocessing, I'll share methods using two frameworks, Core Image and Vision.
✔︎ Outline
- Core Image Framework
- Vision Framework
Although not covered in this post, to improve performance I processed the image preprocessing in parallel using DispatchSemaphore and DispatchQueue. For details, please refer to TinyYOLO-CoreML.
Core Image Framework
Core Image is an image analysis and processing framework supported on iOS. Let's use Core Image to convert the CVPixelBuffer into a form suitable for the YOLO Model's input.
Preprocessing with the Core Image Framework
let ModelInputWidth = 416
let ModelInputHeight = 416
func getResizedPixelBufferByCoreImage(pixelBuffer: CVPixelBuffer) -> CVPixelBuffer {
var resizedPixelBuffer: CVPixelBuffer?
CVPixelBufferCreate(nil, ModelInputWidth, ModelInputHeight, kCVPixelFormatType_32BGRA, nil, &resizedPixelBuffer)
let ciImage = CIImage(cvPixelBuffer: pixelBuffer)
// Rotate
let rotatedImage = ciImage.oriented(forExifOrientation: Int32(CGImagePropertyOrientation.right.rawValue))
// Scale to YOLO input size
let sx = CGFloat(ModelInputWidth) / CGFloat(CVPixelBufferGetHeight(pixelBuffer))
let sy = CGFloat(ModelInputHeight) / CGFloat(CVPixelBufferGetWidth(pixelBuffer))
let scaleTransform = CGAffineTransform(scaleX: sx, y: sy)
let scaledImage = rotatedImage.transformed(by: scaleTransform)
// render : image into a pixel buffer.
ciContext.render(scaledImage, to: resizedPixelBuffer)
// Model Predict
predict(image: resizedPixelBuffer)
}The processed image is passed to the model.prediction function. output._13 is the output_names=['13'] entered when converting to an mlmodel with CoreML Tools.
YOLO model predict
let model = light_tiny_model()
func predict(image: CVPixelBuffer) throws -> [Prediction]? {
if let output = try? model.prediction(image: image) {
return computeBoundingBoxes(features: output._13)
} else {
return nil
}
}output.grid is a result of type MLMultiArray with a size of 13 x 13 x 30 per grid, and it's passed to the computeBoundingBoxes() function to post-process the result.
Vision Framework
I implemented the image preprocessing with the Core Image Framework above, but there's another way to implement it using the Vision Framework.
Vision Framework setup
let request: VNCoreMLRequest
// Initial setup
func setUpVision() {
guard let visionModel = try? VNCoreMLModel(for: yolo.model.model) else {
print("Error: could not create Vision model")
return
}
request = VNCoreMLRequest(model: visionModel, completionHandler: visionRequestDidComplete)
request.imageCropAndScaleOption = .scaleFill
}
// Function called on completion
func visionRequestDidComplete(request: VNRequest, error: Error?) {
guard let observations = request.results as? [VNCoreMLFeatureValueObservation] else { return }
// Find the result corresponding to 13 x 13 x 30
if observationsIndex == nil {
for (i, observation) in observations.enumerated() {
guard let feature = observation.featureValue.multiArrayValue else { continue }
if feature.count == featureCount {
self.observationsIndex = i
break
}
}
}
if observationsIndex != nil {
if let output = observations[observationsIndex!].featureValue.multiArrayValue {
computeBoundingBoxes(features: output)
}
}
}Image preprocessing with the Vision framework
func getResizedPixelBufferByVision(pixelBuffer: CVPixelBuffer, request: VNCoreMLRequest) {
// Pass .right as the orientation option to rotate to the right
let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: .right)
// Call visionRequestDidComplete() when done
handler.perform([request])
}output is a result of type MLMultiArray with a size of 13 x 13 x 30 per grid, and it's passed to the computeBoundingBoxes() function to post-process the result.
Model Output Postprocessing
The Model returns a 13 x 13 x 30 tensor per image.
N x N x (C + 5) x B)
- N x N : Grid
- C : Number of trained Objects (Classes)
- 5 : Bounding Box information of the detected Object (x, y, w, h, confidence)
- B : Number of boxes per Grid cell
If you display all the Bounding Boxes on screen as they are, you get roughly the following result.

An image showing the YOLO output
Source - https://machinethink.net
To filter the countless boxes down to only the results that correspond to actual object positions and draw clean Bounding Boxes like below, the output needs postprocessing.

An image showing the filtered YOLO output
Source - https://machinethink.net
✔︎ Outline
- Compute Bounding Boxes
- Drawing Bounding Boxes
Compute Bounding Boxes
The [분석] YOLO post explains the YOLO Model's output as follows.
- The input image is divided into an N X N grid.
- Each grid cell has B Bounding Boxes and a confidence score for each Bounding Box.
(If no object exists in the cell, the confidence score is 0) - Each grid cell has C conditional class probabilities.
- Each Bounding Box consists of x, y, w, h, confidence.
(x, y): The center point of the Bounding Box, given as a value relative to the range of the grid cell
(w, h): Given as values relative to the width and height of the whole image - Ex 1: If x is at the far left of the grid cell, x = 0; if y is in the middle of the grid cell, y = 0.5
- Ex 2: If the bbox's width is half of the image width, w = 0.5
The output above is organized using the computeBoundingBoxes() function below.
Bounding Box filtering
let anchors: [Float] = [1.08, 1.19, 3.42, 4.41, 6.63, 11.38, 9.42, 5.11, 16.62, 10.52]
func computeBoundingBoxes(features: MLMultiArray, featureCount: Int) -> [Prediction] {
var predictions = [Prediction]()
let blockSize: Float = 32
let gridHeight = 13
let gridWidth = 13
let boxesPerCell = 3
let numClasses = labels.count
let featurePointer = UnsafeMutablePointer<Double>(OpaquePointer(features.dataPointer))
let channelStride = features.strides[0].intValue
let yStride = features.strides[1].intValue
let xStride = features.strides[2].intValue
@inline(__always) func offset(_ channel: Int, _ x: Int, _ y: Int) -> Int {
return channel*channelStride + y*yStride + x*xStride
}
for cy in 0..< gridHeight {
for cx in 0..< gridWidth {
for b in 0..< boxesPerCell {
let channel = b*(numClasses + 5)
// x, y position on the Grid
let tx = Float(featurePointer[offset(channel , cx, cy)])
let ty = Float(featurePointer[offset(channel + 1, cx, cy)])
let tw = Float(featurePointer[offset(channel + 2, cx, cy)])
let th = Float(featurePointer[offset(channel + 3, cx, cy)])
let tc = Float(featurePointer[offset(channel + 4, cx, cy)])
// Center coordinates (x, y) of the box
let x = (Float(cx) + sigmoid(tx)) * blockSize
let y = (Float(cy) + sigmoid(ty)) * blockSize
// Width and height of the box
let w = exp(tw) * anchors[2*b ] * blockSize
let h = exp(th) * anchors[2*b + 1] * blockSize
// Probability that there's an object in the box
let confidence = sigmoid(tc)
var classes = [Float](repeating: 0, count: numClasses)
for c in 0..< numClasses {
classes[c] = Float(featurePointer[offset(channel + 5 + c, cx, cy)])
}
classes = softmax(classes)
// The class in the box
let (detectedClass, bestClassScore) = classes.argmax()
let confidenceInClass = bestClassScore * confidence
if confidenceInClass > confidenceThreshold {
let rect = CGRect(x: CGFloat(x - w/2), y: CGFloat(y - h/2),
width: CGFloat(w), height: CGFloat(h))
let prediction = Prediction(classIndex: detectedClass,
score: confidenceInClass,
rect: rect)
predictions.append(prediction)
}
}
}
}
/* Remove overlapping Bounding Boxes
* - boxes: Array of Bounding Boxes and scores
* - limit: Maximum number of boxes that can be selected
* - threshold: Criterion for judging whether boxes overlap
*/
return nonMaxSuppression(boxes: predictions,
limit: 10,
threshold: 0.5)
}For a detailed explanation of computeBoundingBoxes, please refer to Real-time object detection with YOLO.
The computeBoundingBoxes() function excludes unnecessary boxes and returns the final, reliable Prediction array.
A Prediction contains the Bounding Box, the class in the box, and the score.
struct Prediction {
let classIndex: Int
let score: Float
let rect: CGRect
}I implemented this by referring to TinyYOLO-CoreML, so please refer to that project for the full code.
Drawing Bounding Boxes
The image first obtained from ARSessionDelegate has a 16:12 ratio rather than 16:9, and I converted that image to 416 x 416 and fed it into the model.
Image size obtained by rotating right in ARSessionDelegate
CVPixelBuffer Height : 1920
CVPixelBuffer Width : 1440So, to draw the Bounding Boxes returned by the Model on the actual mobile screen, I implemented a getScreenRect() function to adjust the scale of the x, y, width, and height of the CGRect struct.

Bounding Box Rescale
let ModelInputWidth = 416
let ModelInputHeight = 416
func getScreenRect(prediction: Prediction, screenWidth: CGFloat, screenHeight: CGFloat) -> CGRect {
var rect = prediction.rect
let scaleX = screenWidth / CGFloat(ModelInputWidth)
let scaleY = screenHeight / CGFloat(ModelInputHeight)
let x1 = rect.origin.x
let x2 = rect.origin.x + rect.size.width
let xc = screenWidth/2
let wx1 = xc - x1
let wx2 = xc - x2
let swx1 = wx1 * 12 / 9
let swx2 = wx2 * 12 / 9
rect.origin.x = xc - swx1
rect.size.width = abs(swx1 - swx2)
rect.origin.x *= scaleX
rect.origin.y *= scaleY
rect.size.width *= scaleX
rect.size.height *= scaleY
return rect
}The final postprocessed result is displayed on screen in real time using UIBezierPath.
Draw Bounding Box
func show(frame: CGRect, label: String, color: UIColor) {
CATransaction.setDisableActions(true)
let path = UIBezierPath(rect: frame)
shapeLayer.path = path.cgPath
shapeLayer.strokeColor = color.cgColor
shapeLayer.isHidden = false
textLayer.string = label
textLayer.backgroundColor = color.cgColor
textLayer.isHidden = false
let attributes = [
NSAttributedString.Key.font: textLayer.font as Any
]
let textRect = label.boundingRect(with: CGSize(width: 400, height: 100),
options: .truncatesLastVisibleLine,
attributes: attributes, context: nil)
let textSize = CGSize(width: textRect.width + 12, height: textRect.height)
let textOrigin = CGPoint(x: frame.origin.x - 2, y: frame.origin.y - textSize.height)
textLayer.frame = CGRect(origin: textOrigin, size: textSize)
}Implementing Real-Time Light Detection with the YOLO Model
✔︎ Outline
- Getting the 3D coordinates of a light
- Placing and removing lights in real time
Getting the 3D Coordinates of a Light
Using the center coordinates of the Bounding Box detected by the YOLO Model and ARKit's hitTest(), you can get an object's 3D coordinates.
Getting 3D coordinates with the hitTest() function
func getARAnchorPosition(point: CGPoint, ResultType type: ARHitTestResult.ResultType = .featurePoint) -> SCNVector3? {
let hitTestResults = hitTest(point, types: type)
guard let hitTestResult = hitTestResults.first else { return nil }
let translation = hitTestResult.worldTransform.translation // 3D coordinates
let x = translation.x
let y = translation.y
let z = translation.z
return SCNVector3(x, y, z)
}Placing and Removing Lights in Real Time
The YOLO Model in this project was trained on a total of 5 classes. Among them, lamps and bulbs are split into separate classes so the ON/OFF state can be distinguished, which lets us track the light's state.

Every frame, the Model predicts the positions and types of the lights in the current frame. If a Bounding Box's center point lies within the Bounding Boxes of the next three consecutive frames and the same class is predicted, I judged that a light of that class really exists and implemented it to take action. For example, if a light in the ON state is recognized three times in a row, an SCNLight is placed at that position, and conversely, if a light in the OFF state is recognized, the SCNLight inside that last Bounding Box is removed.
The yellow bead on the screen is a virtual object visualized so you can see whether an SCNLight is placed.
Closing
At first I thought putting the YOLO Model on with CoreML would be the end of it, but handling the Model's input and output was harder than I expected. 😭
That wraps up the four-part series on building a more realistic AR app with deep learning. 🎉
Thank you for reading this long post.
Part 1. Building a More Realistic AR App with Deep Learning
Part 2. Building an iOS AR App with ARKit
Part 3. Creating a Custom YOLO v3 Model
✔︎ Part 4. Deploying a YOLO v3 Model on iOS with CoreML
Comments