You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS 16的Subject Detection功能是否开放对应的开发者API?

iOS 16主体检测API说明

iOS 16及后续版本中,Apple已经将你提到的主体检测(subject detection/isolation)能力通过Vision框架对外开放,你之前可能没注意到iOS 16新增的相关请求类型。

核心API:VNGenerateForegroundInstanceMaskRequest

这个请求专门用于检测图片中的前景主体(包括人物、动物、物体等),会返回每个主体的实例掩码(mask)和对应的边界框(bounding box),完全满足你获取UIImage主体边界、自定义视觉效果的需求。

简单实现示例

以下是一段基础的代码示例,展示如何用该API获取主体边界:

import Vision
import UIKit

func detectSubjectBounds(in image: UIImage) async throws -> [CGRect] {
    guard let cgImage = image.cgImage else { throw NSError(domain: "ImageError", code: 0) }
    
    let request = VNGenerateForegroundInstanceMaskRequest()
    let handler = VNImageRequestHandler(cgImage: cgImage)
    
    return try await withCheckedThrowingContinuation { continuation in
        handler.perform([request]) { error in
            if let error = error {
                continuation.resume(throwing: error)
                return
            }
            
            guard let results = request.results as? [VNForegroundInstanceMaskObservation] else {
                continuation.resume(returning: [])
                return
            }
            
            // 将归一化的boundingBox转换为UIImage实际坐标
            let imageSize = image.size
            let bounds = results.map { observation in
                let normalizedRect = observation.boundingBox
                return CGRect(
                    x: normalizedRect.origin.x * imageSize.width,
                    y: (1 - normalizedRect.origin.y - normalizedRect.size.height) * imageSize.height,
                    width: normalizedRect.size.width * imageSize.width,
                    height: normalizedRect.size.height * imageSize.height
                )
            }
            
            continuation.resume(returning: bounds)
        }
    }
}

关键注意点

  • 该API仅支持iOS 16.0+、iPadOS 16.0+
  • 返回的boundingBox是归一化坐标(取值0-1),需要根据UIImage的实际尺寸转换为屏幕/视图坐标
  • 如果图片中有多个主体,会返回多个VNForegroundInstanceMaskObservation实例,每个对应一个主体
  • 建议在后台队列执行检测操作,避免阻塞主线程影响UI流畅度

内容的提问来源于stack exchange,提问作者user366126

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 08:40:50