Skip to content
TheChatArchiveThe Chat Archive
chatgpt-4o-latest-20250326· OpenAIHugging Face LMArena Human Preference 140K

아이폰의 Portrait mode (SHALLOW DEPTH OF FIELD) 를 api 로 구현하는 방법을 설명해.

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Qwenqwen3-235b-a22b-no-thinking’s answer.
  1. User

    아이폰의 Portrait mode (SHALLOW DEPTH OF FIELD) 를 api 로 구현하는 방법을 설명해.

  2. Assistant

    iOS에서 Portrait Mode처럼 shallow depth of field(얕은 피사계 심도) 효과를 구현하려면, Apple이 제공하는 다양한 **카메라 및 이미지 프레임워크(API)**를 활용할 수 있습니다.

    Portrait Mode는 주로 사람이나 피사체를 배경과 분리해서 초점을 맞춘 뒤, 배경을 흐리게(blur) 만들어주는 기능입니다. iPhone은 이 기능을 위해 듀얼 혹은 트루-뎁스 카메라를 활용하며, 소프트웨어적으로 심도(depth) 정보를 추출하고, 이를 이용해서 배경을 블러 처리합니다.


    🎯 주요 기술 스택 목록

    기능API/도구버전
    사진 촬영AVFoundation (AVCaptureSession)iOS 10+
    심도 정보AVDepthData, depthDataMapiOS 11+
    이미지 처리Core Image, Metal, VisioniOS 11+
    인물/배경 구분Vision의 사람/객체 인식iOS 13+
    실시간 효과 추가ARKit, Core Image FiltersiOS 11+

    ✅ 구현 방법 개요 (Depth 기반 Portrait Mode 구현)

    1. AVCaptureSession 구성

    let captureSession = AVCaptureSession()
    captureSession.sessionPreset = .photo
    

    2. Depth 지원되는 카메라 선택

    듀얼 카메라가 있는 경우(예: iPhone 7 Plus 이상/Face ID 장치), depth 정보를 수집할 수 있음.

    guard let device = AVCaptureDevice.default(.builtInDualCamera, for: .video, position: .back) else {
        print("Depth 지원 안됨")
        return
    }
    

    3. Photo Output 설정 및 Depth 활성화

    let photoOutput = AVCapturePhotoOutput()
    photoOutput.isDepthDataDeliveryEnabled = photoOutput.isDepthDataDeliverySupported
    session.addOutput(photoOutput)
    

    4. 사진 촬영 시 Depth 포함 요청

    let photoSettings = AVCapturePhotoSettings()
    photoSettings.isDepthDataDeliveryEnabled = true
    photoOutput.capturePhoto(with: photoSettings, delegate: self)
    

    5. capture delegate에서 depthData 가져오기

    func photoOutput(_ output: AVCapturePhotoOutput,
                     didFinishProcessingPhoto photo: AVCapturePhoto,
                     error: Error?) {
        
        if let depthData = photo.depthData {
            let depthMap = depthData.depthDataMap  // CVPixelBuffer
            processImageWithDepth(photo: photo, depthMap: depthMap)
        }
    }
    

    🔧 Depth Map을 이용한 Blur 효과 적용

    방법 1: Core Image (CIImage + CIFilter 사용)

    func processImageWithDepth(photo: AVCapturePhoto, depthMap: CVPixelBuffer) {
        let ciImage = CIImage(cvPixelBuffer: photo.pixelBuffer!)
        let ciDepth = CIImage(cvPixelBuffer: depthMap)
        
        // Normalize depth map (선택사항)
        let normalizedDepth = ciDepth.applyingFilter("CIColorControls", parameters: [
            "inputContrast": 1.0,
            "inputBrightness": 0.0
        ])
    
        // Apply Gaussian blur to background
        let blurred = ciImage.applyingFilter("CIMaskedVariableBlur", parameters: [
            "inputMask": normalizedDepth,
            "inputRadius": 15
        ])
    
        let context = CIContext()
        if let cgImage = context.createCGImage(blurred, from: blurred.extent) {
            let resultUIImage = UIImage(cgImage: cgImage)
            // --> 결과 이미지 표시
        }
    }
    

    방법 2: Metal / Custom Shader Blur

    성능 향상이나 커스텀 처리를 원할 경우 Metal로 직접 구현 가능.

    • Depth map을 분석해, 일정 피사거리보다 멀면 blur kernel을 적용
    • Metal Performance Shaders (MPS) 사용 가능

    ⭐ Advanced: 얕은 심도 감지 없이 구현 (Vision + AI 기반)

    iPhone에서 depth sensor가 없는 기기에서도 Portrait 효과 시뮬레이션을 구현하고 싶다면, Vision과 Core ML로 사람 실루엣 감지 → 배경 마스킹 → 블러 처리 방식으로 처리할 수 있습니다.

    예:

    let request = VNGeneratePersonSegmentationRequest()
    request.qualityLevel = .accurate
    request.outputPixelFormat = kCVPixelFormatType_OneComponent8
    

    이렇게 해서 나온 segmentation mask를 활용해 CIMaskedVariableBlur나 Metal로 배경 블러를 줄 수 있습니다.


    🎥 리얼타임 처리: Live Portrait 효과 구현

    • AVFoundation의 AVCaptureVideoDataOutput을 이용해 실시간 프레임 처리
    • 각 프레임에서 depth map 추출 및 segmentation 마스크 적용
    • 실시간으로 background blur를 적용하여 Portrait Video 모드 구현 가능

    📱 iOS Portrait Mode 관련 API 비교

    기능지원 여부API
    True depth map 추출✅AVCapturePhotoOutput + depthData
    Depth map 기반 blur✅Core Image / Metal
    사람 감지 기반 blur (non-depth)✅Vision + CoreML
    실시간 처리✅AVCaptureVideoDataOutput + Vision
    Portrait Lighting 효과❌ (private API)기기 자체 내장 효과로, API 미공개

    🧠 주의 사항

    • Depth map은 레퍼런스 포인트 외의 거리에서 정확도가 떨어질 수 있음 (예: 유리, 반사가 있는 배경)
    • AVCapturePhotoOutput의 isDepthDataDeliveryEnabled는 기기에 따라 다름
    • iPhone SE 시리즈, 일부 기기에서는 지원하지 않음

    🔚 요약

    구현 요소사용 기술
    심도 인식AVCapturePhotoOutput.depthData
    배경 흐림 효과Core Image (CIMaskedVariableBlur)
    대체(비-Depth 기기)Vision + 사람 분리(segmentation)
    실시간 촬영AVCaptureVideoDataOutput + Metal
    추가 기능Core ML 모델을 통한 객체 분리, 얼굴 인식 등

    필요하다면 이후의 예제로:

    • 실시간 Portrait Mode 구현
    • Depth map 시각화
    • iPhone 모델별 지원 여부 리스트

    도 제공 가능합니다. 원하시면 말씀해주세요!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.