iOS 5+ 提供 CIDetector(CoreImage 框架)僅能完成第 2 步的**臉部檢測**(定位臉框、眼睛、嘴巴),**不包含面紋提取與比對**。完整識別需引入 OpenCV、Face.com 等第三方庫。
CIContext *context = [CIContext contextWithOptions:nil];
UIImage *inputImage = _inputImageView.image;
CIImage *ciImage = [CIImage imageWithCGImage:inputImage.CGImage];
// 高精度檢測
NSDictionary *opts = @{CIDetectorAccuracy: CIDetectorAccuracyHigh};
CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeFace
context:context
options:opts];
NSArray *features = [detector featuresInImage:ciImage];
UIView *overlay = [[UIView alloc] initWithFrame:_inputImageView.frame];
[self.view addSubview:overlay];
for (CIFaceFeature *face in features) {
// 臉框
UIView *faceView = [[UIView alloc] initWithFrame:face.bounds];
faceView.layer.borderWidth = 1;
faceView.layer.borderColor = [UIColor orangeColor].CGColor;
[overlay addSubview:faceView];
// 左眼
if (face.hasLeftEyePosition) {
UIView *v = [[UIView alloc] initWithFrame:CGRectMake(face.leftEyePosition.x-5, face.leftEyePosition.y-5, 10, 10)];
v.backgroundColor = [UIColor greenColor]; [overlay addSubview:v];
}
// 右眼
if (face.hasRightEyePosition) { /* 同左眼 */ }
// 嘴巴
if (face.hasMouthPosition) { /* 同左眼 */ }
}
// CoreImage 坐標系 Y 軸反轉,需縮放修正
overlay.transform = CGAffineTransformMakeScale(1, -1);
CIDetectorTypeFace 僅檢測人臉,另有 CIDetectorTypeRectangle(矩形)、CIDetectorTypeQRCode(二維碼)等。CIDetectorAccuracyLow(快)、CIDetectorAccuracyHigh(準)。CIFaceFeature 含 bounds、hasLeftEyePosition、leftEyePosition、hasRightEyePosition、rightEyePosition、hasMouthPosition、mouthPosition。transform = CGAffineTransformMakeScale(1, -1) 修正。| 庫 | 特點 | 適用場景 |
|---|---|---|
| OpenCV | 功能全、跨平台、C++ 核心、需橋接 | 離線、高性能、自定義訓練 |
| Face.com (已停止) | 雲端 API、準確率高 | 聯網、不想自建模型 |
| Vision Framework (iOS 11+) | 系統級、支援面紋比對、易用 | 現代 iOS 專案首選 |