使用MLModel检测物体时出现内存崩溃问题求助
内存崩溃排查:CreateML冰球检测模型结合摄像头帧处理
我用CreateML训练了一个冰球检测的MLModel,通过手机摄像头采集视频,把每一帧转成CGImage后跑检测。一开始出现内存崩溃,我先停掉了并行运行的轨迹检测功能,但问题没解决。用工具监控内存时,发现我的应用自身内存占用小且稳定,反而是「其他进程」内存超限,这让我搞不懂问题出在哪。后来我又删掉了过滤置信度低于0.5的检测结果的for循环,还是没用。我是MLModel和机器学习的新手,希望能得到排查方向的指引。需要更多细节我可以补充,下面是核心代码(约100行),重点看initializeCaptureSession和captureOutput方法。
// 初始化捕捉会话 func initializeCaptureSession() { captureSession = AVCaptureSession() captureSession.sessionPreset = .high guard let videoDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) else { return } do { let videoInput = try AVCaptureDeviceInput(device: videoDevice) if captureSession.canAddInput(videoInput) { captureSession.addInput(videoInput) } let videoOutput = AVCaptureVideoDataOutput() videoOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "videoQueue")) if captureSession.canAddOutput(videoOutput) { captureSession.addOutput(videoOutput) } captureSession.startRunning() } catch { print(error.localizedDescription) } } // 帧处理回调 func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return } let ciImage = CIImage(cvImageBuffer: imageBuffer) guard let cgImage = CIContext(options: nil).createCGImage(ciImage, from: ciImage.extent) else { return } // 加载MLModel并检测 do { let model = try IceHockeyDetector(configuration: MLModelConfiguration()) let prediction = try model.prediction(image: cgImage) // 原过滤代码已移除 // for object in prediction.detections where object.confidence > 0.5 { // // 处理检测结果 // } } catch { print(error.localizedDescription) } }
排查方向建议
- MLModel初始化时机问题:当前每次
captureOutput回调都会重新初始化IceHockeyDetector,重复加载模型会导致CoreML相关系统进程内存累积。建议把模型初始化移到类的初始化方法中,只加载一次。 - CIContext复用:每次创建
CIContext(options: nil)会额外消耗资源,全局复用一个CIContext实例,避免重复创建。 - CGImage内存管理:CGImage属于Core Foundation对象,ARC不会自动回收,处理完后手动调用
cgImage.release(),或者用autoreleasepool包裹帧处理逻辑,加速内存回收。 - 摄像头队列优先级:检查
videoQueue的QoS设置,避免高优先级队列抢占系统资源,可设置为.userInitiated或.utility级别。 - CoreML运行配置:创建MLModel时,通过
MLModelConfiguration指定computeUnits,比如.cpuAndGPU或.cpuOnly,避免GPU内存占用过高触发系统进程内存超限。
内容的提问来源于stack exchange,提问作者Alex Aghajanov
相关产品推荐
相关产品推荐

