如何将自动对焦添加到 AVCaptureSession? SWIFT

How to add autofocus to AVCaptureSession? SWIFT

我正在使用 AVFoundation 来识别文本和执行 OCR。如何添加自动对焦?我不想在用户点击屏幕时出现黄色方块,我只希望它自动聚焦在物体上,例如信用卡。

这是我的会话代码。

func setupSession() {
  session = AVCaptureSession()
  session.sessionPreset = AVCaptureSessionPresetHigh

  let camera = AVCaptureDevice
     .defaultDeviceWithMediaType(AVMediaTypeVideo)

  do { input = try AVCaptureDeviceInput(device: camera) } catch { return }

  output = AVCaptureStillImageOutput()
  output.outputSettings = [ AVVideoCodecKey: AVVideoCodecJPEG ]

  guard session.canAddInput(input)
     && session.canAddOutput(output) else { return }

  session.addInput(input)
  session.addOutput(output)

  previewLayer = AVCaptureVideoPreviewLayer(session: session)

  previewLayer!.videoGravity = AVLayerVideoGravityResizeAspect
  previewLayer!.connection?.videoOrientation = .Portrait

  view.layer.addSublayer(previewLayer!)

  session.startRunning()

}

在我的 6S 上,默认的相机对焦模式是 .ContinuousAutoFocus,它会持续对焦在相机视野的大部分区域。听起来这就是你想要的。

您可以像这样检查您的相机是否支持自动对焦:

camera.isFocusModeSupported(.ContinuousAutoFocus)

如果尚未设置,请像这样设置:

try! camera.lockForConfiguration()
camera.focusMode = .ContinuousAutoFocus
camera.unlockForConfiguration()

这是我所做的:

 //get instance of phone camera
 let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
 //try to enable auto focus
 if(captureDevice!.isFocusModeSupported(.continuousAutoFocus)) {
     try! captureDevice!.lockForConfiguration()
     captureDevice!.focusMode = .continuousAutoFocus
     captureDevice!.unlockForConfiguration()
 }