Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually set exposure for iOS camera in Swift

I understand that the camera in iOS automatically adjusts exposure continuously when capturing video and photos.

Questions:

How can I turn off the camera's automatic exposure?

In Swift code, how can I set the exposure for the camera to "zero" so that exposure is completely neutral to the surroundings and not compensating for light?

like image 669
user4806509 Avatar asked Jul 20 '17 01:07

user4806509


2 Answers

You can set the exposure mode by setting the "AVCaptureExposureMode" property. Documentation here.

var exposureMode: AVCaptureDevice.ExposureMode { get set }

3 things you gotta take into consideration.

1) Check if the device actually supports this with "isExposureModeSupported"

2) You have to "lock for configuration" before adjusting the exposure. Documentation here.

3) The exposure is adjusted by setting an ISO and a duration. You can't just set it to "0"

ISO:

This property returns the sensor's sensitivity to light by means of a gain value applied to the signal. Only exposure duration values between minISO and maxISO are supported. Higher values will result in noisier images. The property value can be read at any time, regardless of exposure mode, but can only be set using the setExposureModeCustom(duration:iso:completionHandler:) method.

like image 132
Pochi Avatar answered Nov 11 '22 08:11

Pochi


If you need only min, current and max exposure values, then you can use the following:

Swift 5

    import AVFoundation

    enum Esposure {
        case min, normal, max
        
        func value(device: AVCaptureDevice) -> Float {
            switch self {
            case .min:
                return device.activeFormat.minISO
            case .normal:
                return AVCaptureDevice.currentISO
            case .max:
                return device.activeFormat.maxISO
            }
        }
    }

    func set(exposure: Esposure) {
        guard let device = AVCaptureDevice.default(for: AVMediaType.video) else { return }
        if device.isExposureModeSupported(.custom) {
            do{
                try device.lockForConfiguration()
                device.setExposureModeCustom(duration: AVCaptureDevice.currentExposureDuration, iso: exposure.value(device: device)) { (_) in
                    print("Done Esposure")
                }
                device.unlockForConfiguration()
            }
            catch{
                print("ERROR: \(String(describing: error.localizedDescription))")
            }
        }
    }
like image 36
Alexander Volkov Avatar answered Nov 11 '22 08:11

Alexander Volkov