techno
techno

Reputation: 6500

Detecting face in Swift

I'm a novice to Swift Programming. I'm trying to accomplish face detection using core Graphics. So far I have written the following.

let ciimage=CIImage(contentsOf: "/Users/me/Desktop/test.jpg");            
let accuracy = [CIDetectorAccuracy: CIDetectorAccuracyHigh]
let faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: accuracy)


 for face in faces as! [CIFaceFeature] {

 print("Found bounds are \(face.bounds)")
            }

I don't know how to create a cimage from local file.It seems I need to input a URL.. what am I doing wrong, please advice.

UPDATE:

I Have Updated my code referring to the answer provided

let userDirectory = FileManager.default.homeDirectoryForCurrentUser
let desktopDirectory = userDirectory.appendingPathComponent("Desktop")
let pictureUrl = desktopDirectory.appendingPathComponent("test").appendingPathExtension("jpg")

let image = CIImage(contentsOf: pictureUrl)

let faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])
let faces = faceDetector?.features(in: image!) as! [CIFaceFeature]
print("Number of faces: \(faces.count)")

On execution this does not produce any results.

Upvotes: 0

Views: 150

Answers (1)

David Pasztor
David Pasztor

Reputation: 54706

You should use FileManager to retrieve system URL's.

guard let desktopDirectory = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first else {return}
let pictureUrl = desktopDirectory.appendingPathComponent("test").appendingPathExtension("jpg")

let image = CIImage(contentsOf: pictureUrl)

Upvotes: 1

Related Questions