Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get light value from AVFoundation?

Tags:

ios

swift

I work with Swift 3 and I use camera AVFoundation

Who know is there any way to know capacity of light?

I know that one of the approach is use ambient light sensor, but it is don't encourage and eventually apps doesn't allows in market

I found question very close to that I need

detecting if iPhone is in a dark room

And that guy explains that I can use ImageIO framework, read the metadata that's coming in with each frame of the video feed

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
  CFDictionaryRef metadataDict = CMCopyDictionaryOfAttachments(NULL, sampleBuffer, kCMAttachmentMode_ShouldPropagate);
  NSDictionary *metadata = [[NSMutableDictionary alloc] initWithDictionary:(__bridge NSDictionary*)metadataDict];
  CFRelease(metadataDict);
  NSDictionary *exifMetadata = [[metadata objectForKey:(NSString *)kCGImagePropertyExifDictionary] mutableCopy];
  float brightnessValue = [[exifMetadata objectForKey:(NSString *)kCGImagePropertyExifBrightnessValue]  floatValue];
}

But I am a rookie in iOS and don't know how to convert this code in Swift

Thanks in advance!

like image 290
Aleksey Timoshchenko Avatar asked Dec 14 '22 01:12

Aleksey Timoshchenko


1 Answers

Following code implementation is in Swift 3.x

It is possible to get an approximate luminosity value(measured in unit lux) using the EXIF data of the camera. Please refer to the following link. Using a camera as a lux meter

Here the sampleBuffer value of captureOutput method in AVFoundation is used to extract the EXIF data from camera frames.

func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {

    //Retrieving EXIF data of camara frame buffer
    let rawMetadata = CMCopyDictionaryOfAttachments(nil, sampleBuffer, CMAttachmentMode(kCMAttachmentMode_ShouldPropagate))
    let metadata = CFDictionaryCreateMutableCopy(nil, 0, rawMetadata) as NSMutableDictionary
    let exifData = metadata.value(forKey: "{Exif}") as? NSMutableDictionary

    let FNumber : Double = exifData?["FNumber"] as! Double
    let ExposureTime : Double = exifData?["ExposureTime"] as! Double
    let ISOSpeedRatingsArray = exifData!["ISOSpeedRatings"] as? NSArray
    let ISOSpeedRatings : Double = ISOSpeedRatingsArray![0] as! Double
    let CalibrationConstant : Double = 50 

    //Calculating the luminosity
    let luminosity : Double = (CalibrationConstant * FNumber * FNumber ) / ( ExposureTime * ISOSpeedRatings )  

    print(luminosity)}

Please note that the value of CalibrationConstant can be calibrated according the application as explained in the reference.

like image 127
AnuradhaH Avatar answered Jan 02 '23 20:01

AnuradhaH