iOS에서 **Portrait Mode(Shallow Depth of Field, 인물 모드)**를 API로 구현하는 것은 Apple의 Vision, AVFoundation, 그리고 Core Image 프레임워크를 활용하여 가능합니다. 이 기능은 일반적으로 Dual 카메라(광각 + 망원) 또는 TrueDepth 카메라(전면)를 사용하는 장치에서만 가능하며, Apple은 이를 위해 **Depth Data(Depth Map)**를 제공합니다.
아래는 Portrait Mode를 구현하는 기본적인 흐름과 API 사용 방법입니다.
📱 아이폰 Portrait Mode API 구현 가이드
🔧 1. 필요한 프레임워크
AVFoundation: 카메라 제어 및 데이터 캡처
Vision: 얼굴 감지 및 심도 추정
CoreImage: 필터 적용 및 렌더링
Photos (선택적): 사진 저장
📌 1. AVCaptureSession 설정
import AVFoundation
let captureSession = AVCaptureSession()
captureSession.sessionPreset = .photo
guard let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) else { return }
do {
let input = try AVCaptureDeviceInput(device: device)
if captureSession.canAddInput(input) {
captureSession.addInput(input)
}
} catch {
print("Error setting device input: $error)")
}
📌 2. Depth Data 사용 설정 (Portrait Mode)
Depth Data를 사용하려면 AVCapturePhotoOutput에 Depth Data Delivery 옵션을 활성화해야 합니다.
let photoOutput = AVCapturePhotoOutput()
// Depth Data 활성화
if photoOutput.isDepthDataDeliverySupported {
photoOutput.isDepthDataDeliveryEnabled = true
}
if captureSession.canAddOutput(photoOutput) {
captureSession.addOutput(photoOutput)
}
📌 3. 사진 캡처 및 Depth Data 처리
let photoSettings = AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecType.jpeg])
photoSettings.isDepthDataDeliveryEnabled = true
photoOutput.capturePhoto(with: photoSettings, delegate: self)
AVCapturePhotoCaptureDelegate를 구현하여 데이터를 받습니다.
extension ViewController: AVCapturePhotoCaptureDelegate {
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
guard let imageData = photo.fileDataRepresentation() else { return }
let image = UIImage(data: imageData)
// Depth Map 처리
if let depthData = photo.depthData {
let depthPixelBuffer = depthData.depthDataMap
// 후처리 또는 블러 적용
}
}
}
📌 4. Depth Map으로 Portrait Effect 적용 (Shallow DOF)
Depth Map은 CVPixelBuffer 형식으로 제공됩니다. 이를 사용해 배경 블러 효과를 적용할 수 있습니다.
✅ 방법 1: Core Image 필터 사용
import CoreImage
func applyPortraitEffect(from image: UIImage, depthMap: CVPixelBuffer) {
let ciImage = CIImage(image: image)!
let depthImage = CIImage(cvPixelBuffer: depthMap)
// Gaussian Blur 필터 적용
let blurFilter = CIFilter(name: "CIGaussianBlur")!
blurFilter.setValue(ciImage, forKey: kCIInputImageKey)
blurFilter.setValue(10, forKey: kCIInputRadiusKey) // 블러 강도
let blurredImage = blurFilter.outputImage!
// Blend with original using depth map
let blendFilter = CIFilter(name: "CIBlendWithMask")!
blendFilter.setValue(blurredImage, forKey: kCIInputBackgroundImageKey)
blendFilter.setValue(ciImage, forKey: kCIInputImageKey)
blendFilter.setValue(depthImage, forKey: kCIInputMaskImageKey)
let resultImage = blendFilter.outputImage!
// 결과 렌더링
let context = CIContext()
if let cgImage = context.createCGImage(resultImage, from: resultImage.extent) {
let portraitImage = UIImage(cgImage: cgImage)
// portraitImage 사용
}
}
📌 5. TrueDepth 카메라 (전면) 지원
TrueDepth 카메라를 사용하면 전면 카메라에서도 Depth Data를 캡처할 수 있습니다.
guard let device = AVCaptureDevice.default(.builtInTrueDepthCamera, for: .video, position: .front) else { return }
TrueDepth는 Face ID 센서를 활용하여 정확한 얼굴 깊이 정보를 제공하므로, 전면 인물 사진에서도 효과적인 Portrait Mode를 구현할 수 있습니다.
📌 6. 추가: Vision Framework을 통한 얼굴 감지
Depth Data가 없는 경우, Vision을 사용해 얼굴 영역을 감지하고 그에 따라 블러를 적용할 수 있습니다.
import Vision
let request = VNDetectFaceRectanglesRequest { request, error in
guard let results = request.results as? [VNFaceObservation] else { return }
for face in results {
let boundingBox = face.boundingBox
// 블러를 적용할 영역 계산
}
}
✅ 지원 조건 정리
| 조건 | 내용 |
|---|
| 하드웨어 지원 | iPhone 7 Plus 이상 (Dual 카메라), iPhone X 이상 (TrueDepth) |
| iOS 버전 | iOS 11 이상 (Depth Data API 제공) |
| API 사용 | AVCapturePhotoOutput, AVDepthData, Core Image |
| 기능 제한 | 일부 기기에서는 Depth Data를 지원하지 않음 |
💡 참고: Apple 샘플 코드
📌 결론
Portrait Mode(Shallow Depth of Field)를 API로 구현하려면, AVCapturePhotoOutput을 통해 Depth Data를 받아 Core Image로 블러 효과를 적용하는 것이 기본 흐름입니다. TrueDepth 카메라 또는 Dual 카메라가 필요한 기능이므로, 기기 호환성을 반드시 확인해야 합니다.
필요하다면, Depth Data가 없는 기기에서는 Vision Framework을 이용한 얼굴 감지 기반의 가상 Portrait 효과도 구현할 수 있습니다.
원하신다면, 위 코드를 기반으로 SwiftUI 또는 UIKit 기반의 전체 예제 프로젝트도 제공해드릴 수 있습니다.