-
Notifications
You must be signed in to change notification settings - Fork 22
/
VisionCameraFaceDetector.swift
311 lines (267 loc) · 8.25 KB
/
VisionCameraFaceDetector.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
import VisionCamera
import Foundation
import MLKitFaceDetection
import MLKitVision
import CoreML
import UIKit
import AVFoundation
import SceneKit
@objc(VisionCameraFaceDetector)
public class VisionCameraFaceDetector: FrameProcessorPlugin {
// device display data
private let screenBounds = UIScreen.main.bounds
// detection props
private var context = CIContext(options: nil)
private var faceDetector: FaceDetector! = nil
private var runLandmarks = false
private var runClassifications = false
private var runContours = false
private var trackingEnabled = false
private var returnOriginal = false
private var convertFrame = false
public override init(
proxy: VisionCameraProxyHolder,
options: [AnyHashable : Any]! = [:]
) {
super.init(proxy: proxy, options: options)
let config = getConfig(withArguments: options)
// initializes faceDetector on creation
let minFaceSize = 0.15
let optionsBuilder = FaceDetectorOptions()
optionsBuilder.performanceMode = .fast
optionsBuilder.landmarkMode = .none
optionsBuilder.contourMode = .none
optionsBuilder.classificationMode = .none
optionsBuilder.minFaceSize = minFaceSize
optionsBuilder.isTrackingEnabled = false
if config?["performanceMode"] as? String == "accurate" {
optionsBuilder.performanceMode = .accurate
}
if config?["landmarkMode"] as? String == "all" {
runLandmarks = true
optionsBuilder.landmarkMode = .all
}
if config?["classificationMode"] as? String == "all" {
runClassifications = true
optionsBuilder.classificationMode = .all
}
if config?["contourMode"] as? String == "all" {
runContours = true
optionsBuilder.contourMode = .all
}
let minFaceSizeParam = config?["minFaceSize"] as? Double
if minFaceSizeParam != nil && minFaceSizeParam != minFaceSize {
optionsBuilder.minFaceSize = CGFloat(minFaceSizeParam!)
}
if config?["trackingEnabled"] as? Bool == true {
trackingEnabled = true
optionsBuilder.isTrackingEnabled = true
}
faceDetector = FaceDetector.faceDetector(options: optionsBuilder)
// also check about returing frame settings
returnOriginal = config?["returnOriginal"] as? Bool == true
convertFrame = config?["convertFrame"] as? Bool == true
}
func getConfig(
withArguments arguments: [AnyHashable: Any]!
) -> [String:Any]! {
if arguments.count > 0 {
let config = arguments.map { dictionary in
Dictionary(uniqueKeysWithValues: dictionary.map { (key, value) in
(key as? String ?? "", value)
})
}
return config
}
return nil
}
func processBoundingBox(
from face: Face,
scaleX: CGFloat,
scaleY: CGFloat
) -> [String:Any] {
let boundingBox = face.frame
return [
"width": boundingBox.width * scaleX,
"height": boundingBox.height * scaleY,
"x": boundingBox.origin.x * scaleX,
"y": boundingBox.origin.y * scaleY
]
}
func processLandmarks(
from face: Face,
scaleX: CGFloat,
scaleY: CGFloat
) -> [String:[String: CGFloat?]] {
let faceLandmarkTypes = [
FaceLandmarkType.leftCheek,
FaceLandmarkType.leftEar,
FaceLandmarkType.leftEye,
FaceLandmarkType.mouthBottom,
FaceLandmarkType.mouthLeft,
FaceLandmarkType.mouthRight,
FaceLandmarkType.noseBase,
FaceLandmarkType.rightCheek,
FaceLandmarkType.rightEar,
FaceLandmarkType.rightEye
]
let faceLandmarksTypesStrings = [
"LEFT_CHEEK",
"LEFT_EAR",
"LEFT_EYE",
"MOUTH_BOTTOM",
"MOUTH_LEFT",
"MOUTH_RIGHT",
"NOSE_BASE",
"RIGHT_CHEEK",
"RIGHT_EAR",
"RIGHT_EYE"
];
var faceLandMarksTypesMap: [String: [String: CGFloat?]] = [:]
for i in 0..<faceLandmarkTypes.count {
let landmark = face.landmark(ofType: faceLandmarkTypes[i]);
let position = [
"x": landmark?.position.x ?? 0.0 * scaleX,
"y": landmark?.position.y ?? 0.0 * scaleY
]
faceLandMarksTypesMap[faceLandmarksTypesStrings[i]] = position
}
return faceLandMarksTypesMap
}
func processFaceContours(
from face: Face,
scaleX: CGFloat,
scaleY: CGFloat
) -> [String:[[String:CGFloat]]] {
let faceContoursTypes = [
FaceContourType.face,
FaceContourType.leftCheek,
FaceContourType.leftEye,
FaceContourType.leftEyebrowBottom,
FaceContourType.leftEyebrowTop,
FaceContourType.lowerLipBottom,
FaceContourType.lowerLipTop,
FaceContourType.noseBottom,
FaceContourType.noseBridge,
FaceContourType.rightCheek,
FaceContourType.rightEye,
FaceContourType.rightEyebrowBottom,
FaceContourType.rightEyebrowTop,
FaceContourType.upperLipBottom,
FaceContourType.upperLipTop
]
let faceContoursTypesStrings = [
"FACE",
"LEFT_CHEEK",
"LEFT_EYE",
"LEFT_EYEBROW_BOTTOM",
"LEFT_EYEBROW_TOP",
"LOWER_LIP_BOTTOM",
"LOWER_LIP_TOP",
"NOSE_BOTTOM",
"NOSE_BRIDGE",
"RIGHT_CHEEK",
"RIGHT_EYE",
"RIGHT_EYEBROW_BOTTOM",
"RIGHT_EYEBROW_TOP",
"UPPER_LIP_BOTTOM",
"UPPER_LIP_TOP"
];
var faceContoursTypesMap: [String:[[String:CGFloat]]] = [:]
for i in 0..<faceContoursTypes.count {
let contour = face.contour(ofType: faceContoursTypes[i]);
var pointsArray: [[String:CGFloat]] = []
if let points = contour?.points {
for point in points {
let currentPointsMap = [
"x": point.x * scaleX,
"y": point.y * scaleY,
]
pointsArray.append(currentPointsMap)
}
faceContoursTypesMap[faceContoursTypesStrings[i]] = pointsArray
}
}
return faceContoursTypesMap
}
func convertFrameToBase64(
_ frame: Frame
) -> Any! {
guard let imageBuffer = CMSampleBufferGetImageBuffer(frame.buffer) else {
print("Failed to get CVPixelBuffer!")
return nil
}
let ciImage = CIImage(cvPixelBuffer: imageBuffer)
guard let cgImage = context.createCGImage(ciImage, from: ciImage.extent) else {
print("Failed to create CGImage!")
return nil
}
let image = UIImage(cgImage: cgImage)
let imageData = image.jpegData(compressionQuality: 100)
return imageData?.base64EncodedString() ?? ""
}
public override func callback(
_ frame: Frame,
withArguments arguments: [AnyHashable: Any]?
) -> Any? {
var result: [String: Any] = [:]
do {
let image = VisionImage(buffer: frame.buffer)
image.orientation = .up
let scaleX = screenBounds.size.width / CGFloat(frame.width)
let scaleY = screenBounds.size.height / CGFloat(frame.height)
var faceList: [Any] = []
let faces: [Face] = try faceDetector!.results(in: image)
for face in faces {
var map: [String: Any] = [:]
if runLandmarks {
map["landmarks"] = processLandmarks(
from: face,
scaleX: scaleX,
scaleY: scaleY
)
}
if runClassifications {
map["leftEyeOpenProbability"] = face.leftEyeOpenProbability
map["rightEyeOpenProbability"] = face.rightEyeOpenProbability
map["smilingProbability"] = face.smilingProbability
}
if runContours {
map["contours"] = processFaceContours(
from: face,
scaleX: scaleX,
scaleY: scaleY
)
}
if trackingEnabled {
map["trackingId"] = face.trackingID
}
map["rollAngle"] = face.headEulerAngleZ
map["pitchAngle"] = face.headEulerAngleX
map["yawAngle"] = face.headEulerAngleY
map["bounds"] = processBoundingBox(
from: face,
scaleX: scaleX,
scaleY: scaleY
)
faceList.append(map)
}
var frameMap: [String: Any] = [:]
if returnOriginal {
frameMap["original"] = frame
}
if convertFrame {
frameMap["converted"] = convertFrameToBase64(frame)
}
result = returnOriginal || convertFrame ? [
"faces": faceList,
"frame": frameMap
] : [
"faces": faceList
]
} catch let error {
print("Error processing face detection: \(error)")
}
return result
}
}