我正在努力在iOS应用程序中实现人脸识别。我收到了很多标签,例如“眼镜”或“微笑”,但没有看到一个实际的变量告诉我这是一张人脸(以及什么程度的置信度)。
我缺少什么变量,我们如何使用该功能?
答案 0 :(得分:0)
我认为您可能没有使用正确的特征类型,因为看来您是在获取标签而不是面部特征。
我建议您查看Detecting Faces和Face Detection Tutorial文档,在其中可以找到详细信息和一些有用的示例,可以将它们用作参考,以进一步了解detecting faces的过程使用 Vision API 。
答案 1 :(得分:0)
您可以按照几个步骤从图像中检测人脸。
创建您的URLRequest
func createRequest() -> URLRequest? {
// Create your request URL
if let url = URL(string: "YOUR_API_KEY") {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue(Bundle.main.bundleIdentifier ?? "", forHTTPHeaderField: "X- Ios-Bundle-Identifier")
let jsonRequest = [
"requests": [
"features": [
[
"type": "FACE_DETECTION",
"maxResults": 10 //change as per your requirement
]
]
]
]
let jsonData = try? JSONSerialization.data(withJSONObject: jsonRequest)
request.httpBody = jsonData
return request
}
return nil
}
在后台线程中运行请求
let task: URLSessionDataTask = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "")
return
}
print(data)// Analyze with this data
}
task.resume()
分析数据(如果要更新任何UI组件,请在主线程上进行分析)
DispatchQueue.main.async(execute: {
do {
guard let json =
try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { return }
guard let responses = json["responses"] as? NSArray else { return }
if responses.count > 0 {
guard let response = responses.firstObject as? [String: Any] else { return }
guard let faceAnnotations = response["faceAnnotations"] as? NSArray else {
print(false, "No face detected, please try another photo.")
return
}
if faceAnnotations.count > 0 {
print("Face successfully detected: \(faceAnnotations.count)")
} else {
print("No face detected, please try another photo.")
}
} else {
print("Error while face detection process, please try again.")
}
} catch {
print("Error while face detection process, please try again.")
}
})