-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathViewController.swift
1211 lines (1092 loc) · 42.3 KB
/
ViewController.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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import MLImage
import MLKit
import UIKit
/// Main view controller class.
@objc(ViewController)
class ViewController: UIViewController, UINavigationControllerDelegate {
/// A string holding current results from detection.
var resultsText = ""
/// An overlay view that displays detection annotations.
private lazy var annotationOverlayView: UIView = {
precondition(isViewLoaded)
let annotationOverlayView = UIView(frame: .zero)
annotationOverlayView.translatesAutoresizingMaskIntoConstraints = false
annotationOverlayView.clipsToBounds = true
return annotationOverlayView
}()
/// An image picker for accessing the photo library or camera.
var imagePicker = UIImagePickerController()
// Image counter.
var currentImage = 0
/// Initialized when one of the pose detector rows are chosen. Reset to `nil` when neither are.
private var poseDetector: PoseDetector? = nil
/// Initialized when a segmentation row is chosen. Reset to `nil` otherwise.
private var segmenter: Segmenter? = nil
/// The detector row with which detection was most recently run. Useful for inferring when to
/// reset detector instances which use a conventional lifecyle paradigm.
private var lastDetectorRow: DetectorPickerRow?
// MARK: - IBOutlets
@IBOutlet fileprivate weak var detectorPicker: UIPickerView!
@IBOutlet fileprivate weak var imageView: UIImageView!
@IBOutlet fileprivate weak var photoCameraButton: UIBarButtonItem!
@IBOutlet fileprivate weak var videoCameraButton: UIBarButtonItem!
@IBOutlet weak var detectButton: UIBarButtonItem!
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = UIImage(named: Constants.images[currentImage])
imageView.addSubview(annotationOverlayView)
NSLayoutConstraint.activate([
annotationOverlayView.topAnchor.constraint(equalTo: imageView.topAnchor),
annotationOverlayView.leadingAnchor.constraint(equalTo: imageView.leadingAnchor),
annotationOverlayView.trailingAnchor.constraint(equalTo: imageView.trailingAnchor),
annotationOverlayView.bottomAnchor.constraint(equalTo: imageView.bottomAnchor),
])
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
detectorPicker.delegate = self
detectorPicker.dataSource = self
let isCameraAvailable =
UIImagePickerController.isCameraDeviceAvailable(.front)
|| UIImagePickerController.isCameraDeviceAvailable(.rear)
if isCameraAvailable {
// `CameraViewController` uses `AVCaptureDevice.DiscoverySession` which is only supported for
// iOS 10 or newer.
if #available(iOS 10.0, *) {
videoCameraButton.isEnabled = true
}
} else {
photoCameraButton.isEnabled = false
}
let defaultRow = (DetectorPickerRow.rowsCount / 2) - 1
detectorPicker.selectRow(defaultRow, inComponent: 0, animated: false)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.isHidden = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.navigationBar.isHidden = false
}
// MARK: - IBActions
@IBAction func detect(_ sender: Any) {
clearResults()
let row = detectorPicker.selectedRow(inComponent: 0)
if let rowIndex = DetectorPickerRow(rawValue: row) {
resetManagedLifecycleDetectors(activeDetectorRow: rowIndex)
let shouldEnableClassification =
(rowIndex == .detectObjectsProminentWithClassifier)
|| (rowIndex == .detectObjectsMultipleWithClassifier)
|| (rowIndex == .detectObjectsCustomProminentWithClassifier)
|| (rowIndex == .detectObjectsCustomMultipleWithClassifier)
let shouldEnableMultipleObjects =
(rowIndex == .detectObjectsMultipleWithClassifier)
|| (rowIndex == .detectObjectsMultipleNoClassifier)
|| (rowIndex == .detectObjectsCustomMultipleWithClassifier)
|| (rowIndex == .detectObjectsCustomMultipleNoClassifier)
switch rowIndex {
case .detectFaceOnDevice:
detectFaces(image: imageView.image)
case .detectTextOnDevice, .detectTextChineseOnDevice, .detectTextDevanagariOnDevice,
.detectTextJapaneseOnDevice, .detectTextKoreanOnDevice:
detectTextOnDevice(
image: imageView.image, detectorType: rowIndex)
case .detectBarcodeOnDevice:
detectBarcodes(image: imageView.image)
case .detectImageLabelsOnDevice:
detectLabels(image: imageView.image, shouldUseCustomModel: false)
case .detectImageLabelsCustomOnDevice:
detectLabels(image: imageView.image, shouldUseCustomModel: true)
case .detectObjectsProminentNoClassifier, .detectObjectsProminentWithClassifier,
.detectObjectsMultipleNoClassifier, .detectObjectsMultipleWithClassifier:
let options = ObjectDetectorOptions()
options.shouldEnableClassification = shouldEnableClassification
options.shouldEnableMultipleObjects = shouldEnableMultipleObjects
options.detectorMode = .singleImage
detectObjectsOnDevice(in: imageView.image, options: options)
case .detectObjectsCustomProminentNoClassifier, .detectObjectsCustomProminentWithClassifier,
.detectObjectsCustomMultipleNoClassifier, .detectObjectsCustomMultipleWithClassifier:
guard
let localModelFilePath = Bundle.main.path(
forResource: Constants.localModelFile.name,
ofType: Constants.localModelFile.type
)
else {
print("Failed to find custom local model file.")
return
}
let localModel = LocalModel(path: localModelFilePath)
let options = CustomObjectDetectorOptions(localModel: localModel)
options.shouldEnableClassification = shouldEnableClassification
options.shouldEnableMultipleObjects = shouldEnableMultipleObjects
options.detectorMode = .singleImage
detectObjectsOnDevice(in: imageView.image, options: options)
case .detectPose, .detectPoseAccurate:
detectPose(image: imageView.image)
case .detectSegmentationMaskSelfie:
detectSegmentationMask(image: imageView.image)
}
} else {
print("No such item at row \(row) in detector picker.")
}
}
@IBAction func openPhotoLibrary(_ sender: Any) {
imagePicker.sourceType = .photoLibrary
present(imagePicker, animated: true)
}
@IBAction func openCamera(_ sender: Any) {
guard
UIImagePickerController.isCameraDeviceAvailable(.front)
|| UIImagePickerController
.isCameraDeviceAvailable(.rear)
else {
return
}
imagePicker.sourceType = .camera
present(imagePicker, animated: true)
}
@IBAction func changeImage(_ sender: Any) {
clearResults()
currentImage = (currentImage + 1) % Constants.images.count
imageView.image = UIImage(named: Constants.images[currentImage])
}
@IBAction func downloadOrDeleteModel(_ sender: Any) {
clearResults()
}
// MARK: - Private
/// Removes the detection annotations from the annotation overlay view.
private func removeDetectionAnnotations() {
for annotationView in annotationOverlayView.subviews {
annotationView.removeFromSuperview()
}
}
/// Clears the results text view and removes any frames that are visible.
private func clearResults() {
removeDetectionAnnotations()
self.resultsText = ""
}
private func showResults() {
let resultsAlertController = UIAlertController(
title: "Detection Results",
message: nil,
preferredStyle: .actionSheet
)
resultsAlertController.addAction(
UIAlertAction(title: "OK", style: .destructive) { _ in
resultsAlertController.dismiss(animated: true, completion: nil)
}
)
resultsAlertController.message = resultsText
resultsAlertController.popoverPresentationController?.barButtonItem = detectButton
resultsAlertController.popoverPresentationController?.sourceView = self.view
present(resultsAlertController, animated: true, completion: nil)
print(resultsText)
}
/// Updates the image view with a scaled version of the given image.
private func updateImageView(with image: UIImage) {
let orientation = UIApplication.shared.statusBarOrientation
var scaledImageWidth: CGFloat = 0.0
var scaledImageHeight: CGFloat = 0.0
switch orientation {
case .portrait, .portraitUpsideDown, .unknown:
scaledImageWidth = imageView.bounds.size.width
scaledImageHeight = image.size.height * scaledImageWidth / image.size.width
case .landscapeLeft, .landscapeRight:
scaledImageWidth = image.size.width * scaledImageHeight / image.size.height
scaledImageHeight = imageView.bounds.size.height
@unknown default:
fatalError()
}
weak var weakSelf = self
DispatchQueue.global(qos: .userInitiated).async {
// Scale image while maintaining aspect ratio so it displays better in the UIImageView.
var scaledImage = image.scaledImage(
with: CGSize(width: scaledImageWidth, height: scaledImageHeight)
)
scaledImage = scaledImage ?? image
guard let finalImage = scaledImage else { return }
DispatchQueue.main.async {
weakSelf?.imageView.image = finalImage
}
}
}
private func transformMatrix() -> CGAffineTransform {
guard let image = imageView.image else { return CGAffineTransform() }
let imageViewWidth = imageView.frame.size.width
let imageViewHeight = imageView.frame.size.height
let imageWidth = image.size.width
let imageHeight = image.size.height
let imageViewAspectRatio = imageViewWidth / imageViewHeight
let imageAspectRatio = imageWidth / imageHeight
let scale =
(imageViewAspectRatio > imageAspectRatio)
? imageViewHeight / imageHeight : imageViewWidth / imageWidth
// Image view's `contentMode` is `scaleAspectFit`, which scales the image to fit the size of the
// image view by maintaining the aspect ratio. Multiple by `scale` to get image's original size.
let scaledImageWidth = imageWidth * scale
let scaledImageHeight = imageHeight * scale
let xValue = (imageViewWidth - scaledImageWidth) / CGFloat(2.0)
let yValue = (imageViewHeight - scaledImageHeight) / CGFloat(2.0)
var transform = CGAffineTransform.identity.translatedBy(x: xValue, y: yValue)
transform = transform.scaledBy(x: scale, y: scale)
return transform
}
private func pointFrom(_ visionPoint: VisionPoint) -> CGPoint {
return CGPoint(x: visionPoint.x, y: visionPoint.y)
}
private func addContours(forFace face: Face, transform: CGAffineTransform) {
// Face
if let faceContour = face.contour(ofType: .face) {
for point in faceContour.points {
let transformedPoint = pointFrom(point).applying(transform)
UIUtilities.addCircle(
atPoint: transformedPoint,
to: annotationOverlayView,
color: UIColor.yellow,
radius: Constants.smallDotRadius
)
}
}
// Eyebrows
if let topLeftEyebrowContour = face.contour(ofType: .leftEyebrowTop) {
for point in topLeftEyebrowContour.points {
let transformedPoint = pointFrom(point).applying(transform)
UIUtilities.addCircle(
atPoint: transformedPoint,
to: annotationOverlayView,
color: UIColor.yellow,
radius: Constants.smallDotRadius
)
}
}
if let bottomLeftEyebrowContour = face.contour(ofType: .leftEyebrowBottom) {
for point in bottomLeftEyebrowContour.points {
let transformedPoint = pointFrom(point).applying(transform)
UIUtilities.addCircle(
atPoint: transformedPoint,
to: annotationOverlayView,
color: UIColor.yellow,
radius: Constants.smallDotRadius
)
}
}
if let topRightEyebrowContour = face.contour(ofType: .rightEyebrowTop) {
for point in topRightEyebrowContour.points {
let transformedPoint = pointFrom(point).applying(transform)
UIUtilities.addCircle(
atPoint: transformedPoint,
to: annotationOverlayView,
color: UIColor.yellow,
radius: Constants.smallDotRadius
)
}
}
if let bottomRightEyebrowContour = face.contour(ofType: .rightEyebrowBottom) {
for point in bottomRightEyebrowContour.points {
let transformedPoint = pointFrom(point).applying(transform)
UIUtilities.addCircle(
atPoint: transformedPoint,
to: annotationOverlayView,
color: UIColor.yellow,
radius: Constants.smallDotRadius
)
}
}
// Eyes
if let leftEyeContour = face.contour(ofType: .leftEye) {
for point in leftEyeContour.points {
let transformedPoint = pointFrom(point).applying(transform)
UIUtilities.addCircle(
atPoint: transformedPoint,
to: annotationOverlayView,
color: UIColor.yellow,
radius: Constants.smallDotRadius)
}
}
if let rightEyeContour = face.contour(ofType: .rightEye) {
for point in rightEyeContour.points {
let transformedPoint = pointFrom(point).applying(transform)
UIUtilities.addCircle(
atPoint: transformedPoint,
to: annotationOverlayView,
color: UIColor.yellow,
radius: Constants.smallDotRadius
)
}
}
// Lips
if let topUpperLipContour = face.contour(ofType: .upperLipTop) {
for point in topUpperLipContour.points {
let transformedPoint = pointFrom(point).applying(transform)
UIUtilities.addCircle(
atPoint: transformedPoint,
to: annotationOverlayView,
color: UIColor.yellow,
radius: Constants.smallDotRadius
)
}
}
if let bottomUpperLipContour = face.contour(ofType: .upperLipBottom) {
for point in bottomUpperLipContour.points {
let transformedPoint = pointFrom(point).applying(transform)
UIUtilities.addCircle(
atPoint: transformedPoint,
to: annotationOverlayView,
color: UIColor.yellow,
radius: Constants.smallDotRadius
)
}
}
if let topLowerLipContour = face.contour(ofType: .lowerLipTop) {
for point in topLowerLipContour.points {
let transformedPoint = pointFrom(point).applying(transform)
UIUtilities.addCircle(
atPoint: transformedPoint,
to: annotationOverlayView,
color: UIColor.yellow,
radius: Constants.smallDotRadius
)
}
}
if let bottomLowerLipContour = face.contour(ofType: .lowerLipBottom) {
for point in bottomLowerLipContour.points {
let transformedPoint = pointFrom(point).applying(transform)
UIUtilities.addCircle(
atPoint: transformedPoint,
to: annotationOverlayView,
color: UIColor.yellow,
radius: Constants.smallDotRadius
)
}
}
// Nose
if let noseBridgeContour = face.contour(ofType: .noseBridge) {
for point in noseBridgeContour.points {
let transformedPoint = pointFrom(point).applying(transform)
UIUtilities.addCircle(
atPoint: transformedPoint,
to: annotationOverlayView,
color: UIColor.yellow,
radius: Constants.smallDotRadius
)
}
}
if let noseBottomContour = face.contour(ofType: .noseBottom) {
for point in noseBottomContour.points {
let transformedPoint = pointFrom(point).applying(transform)
UIUtilities.addCircle(
atPoint: transformedPoint,
to: annotationOverlayView,
color: UIColor.yellow,
radius: Constants.smallDotRadius
)
}
}
}
private func addLandmarks(forFace face: Face, transform: CGAffineTransform) {
// Mouth
if let bottomMouthLandmark = face.landmark(ofType: .mouthBottom) {
let point = pointFrom(bottomMouthLandmark.position)
let transformedPoint = point.applying(transform)
UIUtilities.addCircle(
atPoint: transformedPoint,
to: annotationOverlayView,
color: UIColor.red,
radius: Constants.largeDotRadius
)
}
if let leftMouthLandmark = face.landmark(ofType: .mouthLeft) {
let point = pointFrom(leftMouthLandmark.position)
let transformedPoint = point.applying(transform)
UIUtilities.addCircle(
atPoint: transformedPoint,
to: annotationOverlayView,
color: UIColor.red,
radius: Constants.largeDotRadius
)
}
if let rightMouthLandmark = face.landmark(ofType: .mouthRight) {
let point = pointFrom(rightMouthLandmark.position)
let transformedPoint = point.applying(transform)
UIUtilities.addCircle(
atPoint: transformedPoint,
to: annotationOverlayView,
color: UIColor.red,
radius: Constants.largeDotRadius
)
}
// Nose
if let noseBaseLandmark = face.landmark(ofType: .noseBase) {
let point = pointFrom(noseBaseLandmark.position)
let transformedPoint = point.applying(transform)
UIUtilities.addCircle(
atPoint: transformedPoint,
to: annotationOverlayView,
color: UIColor.yellow,
radius: Constants.largeDotRadius
)
}
// Eyes
if let leftEyeLandmark = face.landmark(ofType: .leftEye) {
let point = pointFrom(leftEyeLandmark.position)
let transformedPoint = point.applying(transform)
UIUtilities.addCircle(
atPoint: transformedPoint,
to: annotationOverlayView,
color: UIColor.cyan,
radius: Constants.largeDotRadius
)
}
if let rightEyeLandmark = face.landmark(ofType: .rightEye) {
let point = pointFrom(rightEyeLandmark.position)
let transformedPoint = point.applying(transform)
UIUtilities.addCircle(
atPoint: transformedPoint,
to: annotationOverlayView,
color: UIColor.cyan,
radius: Constants.largeDotRadius
)
}
// Ears
if let leftEarLandmark = face.landmark(ofType: .leftEar) {
let point = pointFrom(leftEarLandmark.position)
let transformedPoint = point.applying(transform)
UIUtilities.addCircle(
atPoint: transformedPoint,
to: annotationOverlayView,
color: UIColor.purple,
radius: Constants.largeDotRadius
)
}
if let rightEarLandmark = face.landmark(ofType: .rightEar) {
let point = pointFrom(rightEarLandmark.position)
let transformedPoint = point.applying(transform)
UIUtilities.addCircle(
atPoint: transformedPoint,
to: annotationOverlayView,
color: UIColor.purple,
radius: Constants.largeDotRadius
)
}
// Cheeks
if let leftCheekLandmark = face.landmark(ofType: .leftCheek) {
let point = pointFrom(leftCheekLandmark.position)
let transformedPoint = point.applying(transform)
UIUtilities.addCircle(
atPoint: transformedPoint,
to: annotationOverlayView,
color: UIColor.orange,
radius: Constants.largeDotRadius
)
}
if let rightCheekLandmark = face.landmark(ofType: .rightCheek) {
let point = pointFrom(rightCheekLandmark.position)
let transformedPoint = point.applying(transform)
UIUtilities.addCircle(
atPoint: transformedPoint,
to: annotationOverlayView,
color: UIColor.orange,
radius: Constants.largeDotRadius
)
}
}
private func process(_ visionImage: VisionImage, with textRecognizer: TextRecognizer?) {
weak var weakSelf = self
textRecognizer?.process(visionImage) { text, error in
guard let strongSelf = weakSelf else {
print("Self is nil!")
return
}
guard error == nil, let text = text else {
let errorString = error?.localizedDescription ?? Constants.detectionNoResultsMessage
strongSelf.resultsText = "Text recognizer failed with error: \(errorString)"
strongSelf.showResults()
return
}
// Blocks.
for block in text.blocks {
let transformedRect = block.frame.applying(strongSelf.transformMatrix())
UIUtilities.addRectangle(
transformedRect,
to: strongSelf.annotationOverlayView,
color: UIColor.purple
)
// Lines.
for line in block.lines {
let transformedRect = line.frame.applying(strongSelf.transformMatrix())
UIUtilities.addRectangle(
transformedRect,
to: strongSelf.annotationOverlayView,
color: UIColor.orange
)
// Elements.
for element in line.elements {
let transformedRect = element.frame.applying(strongSelf.transformMatrix())
UIUtilities.addRectangle(
transformedRect,
to: strongSelf.annotationOverlayView,
color: UIColor.green
)
let label = UILabel(frame: transformedRect)
label.text = element.text
label.adjustsFontSizeToFitWidth = true
strongSelf.annotationOverlayView.addSubview(label)
}
}
}
strongSelf.resultsText += "\(text.text)\n"
strongSelf.showResults()
}
}
}
extension ViewController: UIPickerViewDataSource, UIPickerViewDelegate {
// MARK: - UIPickerViewDataSource
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return DetectorPickerRow.componentsCount
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return DetectorPickerRow.rowsCount
}
// MARK: - UIPickerViewDelegate
func pickerView(
_ pickerView: UIPickerView,
titleForRow row: Int,
forComponent component: Int
) -> String? {
return DetectorPickerRow(rawValue: row)?.description
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
clearResults()
}
}
// MARK: - UIImagePickerControllerDelegate
extension ViewController: UIImagePickerControllerDelegate {
func imagePickerController(
_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]
) {
// Local variable inserted by Swift 4.2 migrator.
let info = convertFromUIImagePickerControllerInfoKeyDictionary(info)
clearResults()
if let pickedImage =
info[
convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)]
as? UIImage
{
updateImageView(with: pickedImage)
}
dismiss(animated: true)
}
}
/// Extension of ViewController for On-Device detection.
extension ViewController {
// MARK: - Vision On-Device Detection
/// Detects faces on the specified image and draws a frame around the detected faces using
/// On-Device face API.
///
/// - Parameter image: The image.
func detectFaces(image: UIImage?) {
guard let image = image else { return }
// Create a face detector with options.
// [START config_face]
let options = FaceDetectorOptions()
options.landmarkMode = .all
options.classificationMode = .all
options.performanceMode = .accurate
options.contourMode = .all
// [END config_face]
// [START init_face]
let faceDetector = FaceDetector.faceDetector(options: options)
// [END init_face]
// Initialize a `VisionImage` object with the given `UIImage`.
let visionImage = VisionImage(image: image)
visionImage.orientation = image.imageOrientation
// [START detect_faces]
weak var weakSelf = self
faceDetector.process(visionImage) { faces, error in
guard let strongSelf = weakSelf else {
print("Self is nil!")
return
}
guard error == nil, let faces = faces, !faces.isEmpty else {
// [START_EXCLUDE]
let errorString = error?.localizedDescription ?? Constants.detectionNoResultsMessage
strongSelf.resultsText = "On-Device face detection failed with error: \(errorString)"
strongSelf.showResults()
// [END_EXCLUDE]
return
}
// Faces detected
// [START_EXCLUDE]
faces.forEach { face in
let transform = strongSelf.transformMatrix()
let transformedRect = face.frame.applying(transform)
UIUtilities.addRectangle(
transformedRect,
to: strongSelf.annotationOverlayView,
color: UIColor.green
)
strongSelf.addLandmarks(forFace: face, transform: transform)
strongSelf.addContours(forFace: face, transform: transform)
}
strongSelf.resultsText = faces.map { face in
let headEulerAngleX = face.hasHeadEulerAngleX ? face.headEulerAngleX.description : "NA"
let headEulerAngleY = face.hasHeadEulerAngleY ? face.headEulerAngleY.description : "NA"
let headEulerAngleZ = face.hasHeadEulerAngleZ ? face.headEulerAngleZ.description : "NA"
let leftEyeOpenProbability =
face.hasLeftEyeOpenProbability
? face.leftEyeOpenProbability.description : "NA"
let rightEyeOpenProbability =
face.hasRightEyeOpenProbability
? face.rightEyeOpenProbability.description : "NA"
let smilingProbability =
face.hasSmilingProbability
? face.smilingProbability.description : "NA"
let output = """
Frame: \(face.frame)
Head Euler Angle X: \(headEulerAngleX)
Head Euler Angle Y: \(headEulerAngleY)
Head Euler Angle Z: \(headEulerAngleZ)
Left Eye Open Probability: \(leftEyeOpenProbability)
Right Eye Open Probability: \(rightEyeOpenProbability)
Smiling Probability: \(smilingProbability)
"""
return "\(output)"
}.joined(separator: "\n")
strongSelf.showResults()
// [END_EXCLUDE]
}
// [END detect_faces]
}
func detectSegmentationMask(image: UIImage?) {
guard let image = image else { return }
// Initialize a `VisionImage` object with the given `UIImage`.
let visionImage = VisionImage(image: image)
visionImage.orientation = image.imageOrientation
guard let segmenter = self.segmenter else {
return
}
weak var weakSelf = self
segmenter.process(visionImage) { mask, error in
guard let strongSelf = weakSelf else {
print("Self is nil!")
return
}
guard error == nil, let mask = mask else {
let errorString = error?.localizedDescription ?? Constants.detectionNoResultsMessage
strongSelf.resultsText = "Segmentation failed with error: \(errorString)"
strongSelf.showResults()
return
}
guard let imageBuffer = UIUtilities.createImageBuffer(from: image) else {
let errorString = "Failed to create image buffer from UIImage"
strongSelf.resultsText = "Segmentation failed with error: \(errorString)"
strongSelf.showResults()
return
}
UIUtilities.applySegmentationMask(
mask: mask, to: imageBuffer,
backgroundColor: UIColor.purple.withAlphaComponent(Constants.segmentationMaskAlpha),
foregroundColor: nil)
let maskedImage = UIUtilities.createUIImage(from: imageBuffer, orientation: .up)
let imageView = UIImageView()
imageView.frame = strongSelf.annotationOverlayView.bounds
imageView.contentMode = .scaleAspectFit
imageView.image = maskedImage
strongSelf.annotationOverlayView.addSubview(imageView)
strongSelf.resultsText = "Segmentation Succeeded"
strongSelf.showResults()
}
}
/// Detects poses on the specified image and draw pose landmark points and line segments using
/// the On-Device face API.
///
/// - Parameter image: The image.
func detectPose(image: UIImage?) {
guard let image = image else { return }
guard let inputImage = MLImage(image: image) else {
print("Failed to create MLImage from UIImage.")
return
}
inputImage.orientation = image.imageOrientation
if let poseDetector = self.poseDetector {
poseDetector.process(inputImage) { poses, error in
guard error == nil, let poses = poses, !poses.isEmpty else {
let errorString = error?.localizedDescription ?? Constants.detectionNoResultsMessage
self.resultsText = "Pose detection failed with error: \(errorString)"
self.showResults()
return
}
let transform = self.transformMatrix()
// Pose detected. Currently, only single person detection is supported.
poses.forEach { pose in
let poseOverlayView = UIUtilities.createPoseOverlayView(
forPose: pose,
inViewWithBounds: self.annotationOverlayView.bounds,
lineWidth: Constants.lineWidth,
dotRadius: Constants.smallDotRadius,
positionTransformationClosure: { (position) -> CGPoint in
return self.pointFrom(position).applying(transform)
}
)
self.annotationOverlayView.addSubview(poseOverlayView)
self.resultsText = "Pose Detected"
self.showResults()
}
}
}
}
/// Detects barcodes on the specified image and draws a frame around the detected barcodes using
/// On-Device barcode API.
///
/// - Parameter image: The image.
func detectBarcodes(image: UIImage?) {
guard let image = image else { return }
// Define the options for a barcode detector.
// [START config_barcode]
let format = BarcodeFormat.all
let barcodeOptions = BarcodeScannerOptions(formats: format)
// [END config_barcode]
// Create a barcode scanner.
// [START init_barcode]
let barcodeScanner = BarcodeScanner.barcodeScanner(options: barcodeOptions)
// [END init_barcode]
// Initialize a `VisionImage` object with the given `UIImage`.
let visionImage = VisionImage(image: image)
visionImage.orientation = image.imageOrientation
// [START detect_barcodes]
weak var weakSelf = self
barcodeScanner.process(visionImage) { features, error in
guard let strongSelf = weakSelf else {
print("Self is nil!")
return
}
guard error == nil, let features = features, !features.isEmpty else {
// [START_EXCLUDE]
let errorString = error?.localizedDescription ?? Constants.detectionNoResultsMessage
strongSelf.resultsText = "On-Device barcode detection failed with error: \(errorString)"
strongSelf.showResults()
// [END_EXCLUDE]
return
}
// [START_EXCLUDE]
features.forEach { feature in
let transformedRect = feature.frame.applying(strongSelf.transformMatrix())
UIUtilities.addRectangle(
transformedRect,
to: strongSelf.annotationOverlayView,
color: UIColor.green
)
}
strongSelf.resultsText = features.map { feature in
return "DisplayValue: \(feature.displayValue ?? ""), RawValue: "
+ "\(feature.rawValue ?? ""), Frame: \(feature.frame)"
}.joined(separator: "\n")
strongSelf.showResults()
// [END_EXCLUDE]
}
// [END detect_barcodes]
}
/// Detects labels on the specified image using On-Device label API.
///
/// - Parameter image: The image.
/// - Parameter shouldUseCustomModel: Whether to use the custom image labeling model.
func detectLabels(image: UIImage?, shouldUseCustomModel: Bool) {
guard let image = image else { return }
// [START config_label]
var options: CommonImageLabelerOptions!
if shouldUseCustomModel {
guard
let localModelFilePath = Bundle.main.path(
forResource: Constants.localModelFile.name,
ofType: Constants.localModelFile.type
)
else {
self.resultsText = "On-Device label detection failed because custom model was not found."
self.showResults()
return
}
let localModel = LocalModel(path: localModelFilePath)
options = CustomImageLabelerOptions(localModel: localModel)
} else {
options = ImageLabelerOptions()
}
options.confidenceThreshold = NSNumber(floatLiteral: Constants.labelConfidenceThreshold)
// [END config_label]
// [START init_label]
let onDeviceLabeler = ImageLabeler.imageLabeler(options: options)
// [END init_label]
// Initialize a `VisionImage` object with the given `UIImage`.
let visionImage = VisionImage(image: image)
visionImage.orientation = image.imageOrientation
// [START detect_label]
weak var weakSelf = self
onDeviceLabeler.process(visionImage) { labels, error in
guard let strongSelf = weakSelf else {
print("Self is nil!")
return
}
guard error == nil, let labels = labels, !labels.isEmpty else {
// [START_EXCLUDE]
let errorString = error?.localizedDescription ?? Constants.detectionNoResultsMessage
strongSelf.resultsText = "On-Device label detection failed with error: \(errorString)"
strongSelf.showResults()
// [END_EXCLUDE]
return
}
// [START_EXCLUDE]
strongSelf.resultsText = labels.map { label -> String in
return "Label: \(label.text), Confidence: \(label.confidence), Index: \(label.index)"
}.joined(separator: "\n")
strongSelf.showResults()
// [END_EXCLUDE]
}
// [END detect_label]
}
/// Detects text on the specified image and draws a frame around the recognized text using the
/// On-Device text recognizer.
///
/// - Parameter image: The image.
private func detectTextOnDevice(image: UIImage?, detectorType: DetectorPickerRow) {
guard let image = image else { return }
// [START init_text]
var options: CommonTextRecognizerOptions
if detectorType == .detectTextChineseOnDevice {
options = ChineseTextRecognizerOptions.init()
} else if detectorType == .detectTextDevanagariOnDevice {
options = DevanagariTextRecognizerOptions.init()
} else if detectorType == .detectTextJapaneseOnDevice {
options = JapaneseTextRecognizerOptions.init()
} else if detectorType == .detectTextKoreanOnDevice {
options = KoreanTextRecognizerOptions.init()
} else {
options = TextRecognizerOptions.init()
}
let onDeviceTextRecognizer = TextRecognizer.textRecognizer(options: options)
// [END init_text]
// Initialize a `VisionImage` object with the given `UIImage`.
let visionImage = VisionImage(image: image)
visionImage.orientation = image.imageOrientation
self.resultsText += "Running On-Device Text Recognition...\n"
process(visionImage, with: onDeviceTextRecognizer)
}
/// Detects objects on the specified image and draws a frame around them.
///
/// - Parameter image: The image.
/// - Parameter options: The options for object detector.
private func detectObjectsOnDevice(in image: UIImage?, options: CommonObjectDetectorOptions) {
guard let image = image else { return }
// Initialize a `VisionImage` object with the given `UIImage`.
let visionImage = VisionImage(image: image)