3

In Swift, is there an easy way to find the focal length of the currently using camera? I am working on an iOS application and I need to use the focal length (in pixels or in mm) of iOS cameras. I found documentation from Apple about the focal length, but there is no information about how to obtain it. Here are two places I have visited:

I have also checked this question but it doesn't seem to solve my problem. I know that the focal length can be calculated using the Field of View as follows:

focal_length_pixels = (image_diagonal_pixels/2)/tan(FOV/2)

but again, there are no guides in computing that quantity.

Could you please help? Thanks.

lenhhoxung
  • 2,530
  • 2
  • 30
  • 61
  • 1
    I hope given link will help you https://stackoverflow.com/questions/13190932/how-to-find-out-focal-length-of-camera-in-ios-and-what-is-the-sensor-height – Prags Oct 23 '17 at 10:09
  • you can not use 'image_diagonal_pixels' for calculation because videoFieldOfView is not diagonal (it represents horizontal) (see https://developer.apple.com/documentation/avfoundation/avcapturedeviceformat/1624569-videofieldofview?language=objc) – Taku Koyahata May 08 '18 at 03:12

3 Answers3

3

This function is for those who have the same problem like me before. Basically, we'll have to take a picture, then use the captured picture to detect the focal length:

    // delegate method for the image picker
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        let metadata = info[UIImagePickerControllerMediaMetadata] as? NSDictionary
        let exifdata = metadata!["{Exif}"] as! NSDictionary

        // focal length
        let focalLength = exifdata["FocalLength"] as! Double

        print("Focal length \(focalLength)")
    }
lenhhoxung
  • 2,530
  • 2
  • 30
  • 61
0

I don't think there is any API function for the focal length of avfoundation. instead, you can get other info like lens aperture, dimensions, megapixel by calculating resolution, the field of view in degrees.

camera.lensAperture

camera.activeFormat.videoFieldOfView

camera.activeFormat.formatDescription
{
    let dimensions=CMVideoFormatDescriptionGetDimensions(formatdescription)
}
Piotr Labunski
  • 1,638
  • 4
  • 19
  • 26
Saurav_Sharma
  • 130
  • 1
  • 10
-1

You can use MDLCamera class. First you have to import the class.

import ModelIO

Then use it like below

print("focal length: \(MDLCamera().focalLength)")

Btw you can put it in AppDelegate class.

ugurcmk
  • 702
  • 6
  • 10
  • When I call MDLCamera().focalLength in iPhone5 , it returns 23.5513268. This is different from its specification. – Taku Koyahata May 08 '18 at 04:32
  • and with changing target emulator, MDLCamera().focalLength always returns same values . sensorAspect,fieldOfView, and sensorVerticalAperture too. It seems returning just virtual default values – Taku Koyahata May 08 '18 at 05:15