下面是一个使用Core ML在iOS应用中加载YOLOv8模型,读取本地JPG图片,并进行推理以获取骨架坐标的具体示例。这将包括如何绘制结果并释放模型资源。
1. 准备工作
确保你已经将训练好的YOLOv8模型转换为Core ML格式(.mlmodel)并添加到你的Xcode项目中。这里我们假设你已经有了一个名为 YOLOv8.mlmodel 的文件。
2. 创建Swift文件
创建一个新的Swift文件,比如 ObjectDetectionViewController.swift:
import UIKit
import CoreML
import Vision
class ObjectDetectionViewController: UIViewController {
// MARK: - Properties
private var model: YOLOv8!
// MARK: - UI Components
private let imageView = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadModel()
performInference()
}
// MARK: - Setup UI
private func setupUI() {
view.backgroundColor = .white
imageView.frame = view.bounds
imageView.contentMode = .scaleAspectFit
view.addSubview(imageView)
}
// MARK: - Load Model
private func loadModel() {
do {
let configuration = MLModelConfiguration()
model = try YOLOv8(configuration: configuration)
} catch {
print("Error loading model: \(error)")
}
}
// MARK: - Perform Inference
private func performInference() {
guard let imagePath = Bundle.main.path(forResource: "example", ofType: "jpg"),
let inputImage = UIImage(contentsOfFile: imagePath),
let ciImage = CIImage(image: inputImage) else {
print("Failed to load image.")
return
}
// Prepare the request to run inference using Vision framework.
guard let resizedImage = resizeImage(image: ciImage, targetSize: CGSize(width: 640, height: 640)) else { return }
do {
let predictionInput = YOLOv8Input(image: resizedImage)
let output = try model.prediction(input: predictionInput)
drawBoundingBoxes(onImage: inputImage, outputData: output)
} catch {
print("Prediction failed with error \(error).")
}
releaseModelResources()
}
// Resize Image Function (for Core ML Input Size Requirement)
private func resizeImage(image: CIImage, targetSize size: CGSize) -> CIImage? {
return image.transformed(by:
CGAffineTransform(scaleX:size.width / image.extent.width,
y:size.height / image.extent.height))
}
// Draw bounding boxes on the original UIImage and display it in the UIImageView.
private func drawBoundingBoxes(onImage originalImage: UIImage, outputData results : YOLOv8Output) {
UIGraphicsBeginImageContext(originalImage.size)
originalImage.draw(at: CGPoint.zero)
for bbox in results.boundingBoxes {
let rect = CGRect(x:bbox.origin.x * originalImage.size.width,
y:bbox.origin.y * originalImage.size.height,
width:bbox.width * originalImage.size.width,
height:bbox.height * originalImage.size.height)
UIColor.red.setStroke()
UIRectFrame(rect)
}
let drawn_image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let drawn_image = drawn_image {
DispatchQueue.main.async { [weak self] in
self?.imageView.image = drawn_image
}
}
}
// Release Model Resources After Use.
private func releaseModelResources() {
model = nil
}
}
3. 使用说明
- 导入模型:确保在项目中导入相应的YOLOv8 Core ML模型。
- 本地图片:在你的项目中包含一张名为
example.jpg的测试图像。 - UIViewController设置:可以直接使用这个控制器来测试,你需要在Storyboard或代码中设置它作为根视图控制器。
注意事项:
- 权限问题:如果要访问相册中的图片,请记得在Info.plist中配置相关权限。
- 性能优化:考虑到实时推理需求时,可能需要调整输入尺寸和处理逻辑。
- 准确性:请根据实际情况检查输出数据结构,并适当处理不同模型输出参数。
以上是一个基本的示例,展示了如何在iOS上使用Core ML加载YOLOv8模型,执行推理,并绘制结果。希望这对你有所帮助!
内容由零声教学AI助手提供,问题来源于学员提问




