如何从AVFoundation获得光照值?

时间:2017-01-29 13:18:37

标签: ios swift

我使用Swift 3并使用相机AVFoundation

谁知道有没有办法知道光的容量?

我知道其中一种方法是使用环境光传感器,但它并不鼓励,最终应用程序无法在市场中使用

我发现问题非常接近我需要的问题

detecting if iPhone is in a dark room

那个人解释说我可以使用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];
}

但我是iOS的新手,并且不知道如何在Swift中转换此代码

提前致谢!

2 个答案:

答案 0 :(得分:8)

以下代码实现在Swift 3.x

可以使用相机的EXIF数据获得近似光度值(以单位勒克斯为单位)。请参考以下链接。 Using a camera as a lux meter

此处,AVFoundation中sampleBuffer方法的captureOutput值用于从相机帧中提取EXIF数据。

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

请注意CalibrationConstant的值可以根据申请进行校准,如参考文献中所述。

答案 1 :(得分:0)

按照以下步骤从捕获的图像中获取EXIF数据。

  • 从样本缓冲区中获取图像数据。
  

让imageData =   AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)

  • 使用以下帮助函数获取您需要的EXIF数据
func getEXIFFromImage(image:NSData) -> NSDictionary {
    let imageSourceRef = CGImageSourceCreateWithData(image, nil);
    let currentProperties = CGImageSourceCopyPropertiesAtIndex(imageSourceRef!, 0, nil)
    let mutableDict = NSMutableDictionary(dictionary: currentProperties!)
    return mutableDict
}