iOS 自定义相机近距离拍照模糊,无法自动聚焦。

自定义相机AVCaptureDevice近距离拍照模糊,无法聚焦问题。

问题描述

最近在写iOS身份证识别demo的时候发现,使用iPhone14Pro近距离识别的时候,身份证距离手机摄像头20CM以内,非常模糊根本看不清,各种办法都尝试了就是不行。

问题分析、决绝:

在 iPhone 14 Pro 上,近距离拍摄时,系统会自动切换到微距模式,这通常是使用超广角镜头(Ultra Wide Camera)来实现的。具体来说:
1.  主镜头(Wide Angle Camera):焦距通常适用于中等距离(通常约为 20-30 cm),如果拍摄距离太近,主镜头可能无法对焦清晰。
2.  超广角镜头(Ultra Wide Camera):焦距更近,能够支持更短的拍摄距离(通常大约 2-5 cm),因此在进行近距离拍摄时,系统会自动切换到这个镜头。
3.  远摄镜头(Telephoto Camera):用于远距离拍摄,不适合近距离对焦。
因此,在近距离拍摄时,iPhone 14 Pro 会使用 超广角镜头 来实现微距拍摄。如果你使用的是第三方应用(比如自己开发的应用),并且没有实现镜头切换功能,可能会遇到无法自动切换镜头的问题。

代码展示OC

- (AVCaptureDevice *)device {
    if (_device == nil) {
        // 获取所有可用的摄像头(包括主镜头、超广角镜头和远摄镜头)
        NSArray *devices = [AVCaptureDeviceDiscoverySession
                            discoverySessionWithDeviceTypes:@[AVCaptureDeviceTypeBuiltInWideAngleCamera, 
                                                              AVCaptureDeviceTypeBuiltInUltraWideCamera, 
                                                              AVCaptureDeviceTypeBuiltInTelephotoCamera]
                            mediaType:AVMediaTypeVideo
                            position:AVCaptureDevicePositionBack].devices;
        
        // 遍历摄像头设备,选择超广角镜头
        AVCaptureDevice *selectedDevice = nil;
        for (AVCaptureDevice *device in devices) {
            if ([device.deviceType isEqualToString:AVCaptureDeviceTypeBuiltInUltraWideCamera]) {
                selectedDevice = device;
                break;
            }
        }
        
        // 如果找到了超广角镜头
        if (selectedDevice) {
            NSError *error = nil;
            if ([selectedDevice lockForConfiguration:&error]) {
                // 进行相关的配置(例如对焦、曝光、白平衡等)
                if ([selectedDevice isSmoothAutoFocusSupported]) {
                    selectedDevice.smoothAutoFocusEnabled = YES;
                }
                if ([selectedDevice isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus]) {
                    selectedDevice.focusMode = AVCaptureFocusModeContinuousAutoFocus;
                }
                if ([selectedDevice isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure]) {
                    selectedDevice.exposureMode = AVCaptureExposureModeContinuousAutoExposure;
                }
                if ([selectedDevice isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance]) {
                    selectedDevice.whiteBalanceMode = AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance;
                }
                [selectedDevice unlockForConfiguration];
            }
            
            // 设置为选中的超广角镜头
            _device = selectedDevice;
        } else {
            NSLog(@"未找到超广角镜头");
        }
    }
    
    return _device;
}

- (AVCaptureSession *)session {
    if (_session == nil) {
        _session = [[AVCaptureSession alloc] init];
        _session.sessionPreset = AVCaptureSessionPresetHigh;
        
        NSError *error = nil;
        // 使用选中的超广角镜头作为输入设备
        AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:&error];
        
        if (error) {
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [self alertControllerWithTitle:@"没有摄像设备" message:error.localizedDescription okAction:okAction cancelAction:nil];
        } else {
            if ([_session canAddInput:input]) {
                [_session addInput:input];
            }
            
            if ([_session canAddOutput:self.videoDataOutput]) {
                [_session addOutput:self.videoDataOutput];
            }
            
            if ([_session canAddOutput:self.metadataOutput]) {
                [_session addOutput:self.metadataOutput];
                // 设置需要检测的元数据类型,例如 AVMetadataObjectTypeFace(人脸)、AVMetadataObjectTypeQRCode(二维码)等。
                self.metadataOutput.metadataObjectTypes = @[AVMetadataObjectTypeFace];
            }
        }
    }
    
    return _session;
}

代码展示Swift

var device: AVCaptureDevice? {
    if _device == nil {
        // 获取所有可用摄像头(包括主镜头、超广角镜头和远摄镜头)
        let discoverySession = AVCaptureDevice.DiscoverySession(
            deviceTypes: [.builtInWideAngleCamera, .builtInUltraWideCamera, .builtInTelephotoCamera],
            mediaType: .video,
            position: .back
        )
        let devices = discoverySession.devices
        
        // 遍历摄像头设备,选择超广角镜头
        var selectedDevice: AVCaptureDevice?
        for device in devices {
            if device.deviceType == .builtInUltraWideCamera {
                selectedDevice = device
                break
            }
        }
        
        // 如果找到超广角镜头
        if let selectedDevice = selectedDevice {
            do {
                try selectedDevice.lockForConfiguration()
                // 配置自动对焦、曝光和白平衡等
                if selectedDevice.isSmoothAutoFocusSupported {
                    selectedDevice.isSmoothAutoFocusEnabled = true
                }
                if selectedDevice.isFocusModeSupported(.continuousAutoFocus) {
                    selectedDevice.focusMode = .continuousAutoFocus
                }
                if selectedDevice.isExposureModeSupported(.continuousAutoExposure) {
                    selectedDevice.exposureMode = .continuousAutoExposure
                }
                if selectedDevice.isWhiteBalanceModeSupported(.continuousAutoWhiteBalance) {
                    selectedDevice.whiteBalanceMode = .continuousAutoWhiteBalance
                }
                selectedDevice.unlockForConfiguration()
            } catch {
                print("配置超广角镜头失败:\(error)")
            }
            _device = selectedDevice
        } else {
            print("未找到超广角镜头")
        }
    }
    return _device
}

var session: AVCaptureSession? {
    if _session == nil {
        _session = AVCaptureSession()
        _session?.sessionPreset = .high
        
        do {
            // 使用选中的超广角镜头作为输入设备
            let input = try AVCaptureDeviceInput(device: device ?? AVCaptureDevice())
            
            if _session?.canAddInput(input) == true {
                _session?.addInput(input)
            }
            
            if let videoOutput = videoDataOutput, _session?.canAddOutput(videoOutput) == true {
                _session?.addOutput(videoOutput)
            }
            
            if let metadataOutput = metadataOutput, _session?.canAddOutput(metadataOutput) == true {
                _session?.addOutput(metadataOutput)
                // 设置需要检测的元数据类型,例如人脸检测或二维码检测
                metadataOutput.metadataObjectTypes = [.face]
            }
        } catch {
            showAlert(title: "没有摄像设备", message: error.localizedDescription)
        }
    }
    return _session
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,277评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,689评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,624评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,356评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,402评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,292评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,135评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,992评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,429评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,636评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,785评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,492评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,092评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,723评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,858评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,891评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,713评论 2 354

推荐阅读更多精彩内容