The Quick start project demonstrate recognising food items from an image, either by taking a photo using the camera or selecting an image from the gallery.
Once the Passio SDK status is isReadyForDetection, we can start capturing image or picking it from gallery. Implement following code for asking user for Camera permission. Once user grants the permission, we can configure the camera for capturing images.
importAVFoundation
funcaskForCapturePermission() {if AVCaptureDevice.authorizationStatus(for: .video)== .authorized {configureCamera() } else { AVCaptureDevice.requestAccess(for: .video) { granted in DispatchQueue.main.async {if granted { self.configureCamera() } else { self.statusLabel.text="Please grant permission from Settings to use camera." } } } }}
Take a Picture
Above the viewDidLoad method, where you create variables you want to be accessible anywhere in the ViewController file, create the following Instance Variables
var captureSession: AVCaptureSession!var stillImageOutput: AVCapturePhotoOutput!var videoPreviewLayer: AVCaptureVideoPreviewLayer!
Set up the Camera session and configure Input and Output
funcconfigureCamera() { statusLabel.text="Setting up camera..." captureSession =AVCaptureSession() captureSession.sessionPreset = .photoguardlet backCamera = AVCaptureDevice.default(for: .video)else { statusLabel.text="Unable to access back camera!"return }do {let input =tryAVCaptureDeviceInput(device: backCamera) stillImageOutput =AVCapturePhotoOutput()if captureSession.canAddInput(input)&& captureSession.canAddOutput(stillImageOutput) { captureSession.addInput(input) captureSession.addOutput(stillImageOutput)setupLivePreview() } }catchleterror { statusLabel.text="Error Unable to initialize back camera: \(error.localizedDescription)" }}
Configure the Live Preview and start the Session on the background thread
On click of capture button, provide a setting and a deleget to deliver the capturedPhoto to. This delegate will be this ViewController so we also need to conform to the protocol AVCapturePhotoCaptureDelegate
PHPhotoLibrary.requestAuthorization() { status in DispatchQueue.main.async {if status == .authorized { self.presentImagePicker() } else {// Permission denied by user. } }}
Present the PHPickerViewController with configuration
funcpresentImagePicker() {var configuration =PHPickerConfiguration() configuration.selectionLimit =1// or any number configuration.filter = .imageslet picker =PHPickerViewController(configuration: configuration) picker.isModalInPresentation =true picker.delegate = self DispatchQueue.main.async { self.present(picker, animated:true) }}
Implement the delegate for getting user picked images
The following function is responsible for sending a captured image to the Passio SDK for remote image recognition . It sends image to a remote server for recognition, and after receiving the response it updates the table view which will present a list of recognised food.