Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add autofocus to AVCaptureSession? SWIFT

I'm using AVFoundation to recognize text and perform OCR. How do I add autofocus? I don't want to have the yellow square thing when user taps the screen, I just want it to automatically focus on the object, a credit card for example.

Here is my session code.

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()

}
like image 648
mawnch Avatar asked Sep 18 '16 22:09

mawnch


2 Answers

On my 6S the default camera focus mode is .ContinuousAutoFocus, which continuously focuses on whatever is taking up most of the camera's field of vision. Sounds like that's what you want.

You can check if your camera supports auto focus like so:

camera.isFocusModeSupported(.ContinuousAutoFocus)

and if it's not already set, set it like so:

try! camera.lockForConfiguration()
camera.focusMode = .ContinuousAutoFocus
camera.unlockForConfiguration()
like image 80
Rhythmic Fistman Avatar answered Oct 19 '22 22:10

Rhythmic Fistman


Here is what I did:

 //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()
 }
like image 12
Droid Chris Avatar answered Oct 19 '22 23:10

Droid Chris