首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

iOS 人臉識別入門:CIDetector 檢測臉部特徵與開源庫對比

     編輯:C++ 入門

人臉識別流程

  1. 建立面紋庫:採集照片/視頻 → 提取面紋編碼 → 存入數據庫。
  2. 獲取當前面相:實時採集 → 生成面紋編碼。
  3. 比對識別:當前面紋與庫中比對,判斷身份。

iOS 5+ 提供 CIDetector(CoreImage 框架)僅能完成第 2 步的**臉部檢測**(定位臉框、眼睛、嘴巴),**不包含面紋提取與比對**。完整識別需引入 OpenCV、Face.com 等第三方庫。

CIDetector 使用代碼

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。
  • CoreImage 座標系原點在左下,UIKit 在左上,需 transform = CGAffineTransformMakeScale(1, -1) 修正。

第三方庫對比

總結

CIDetector 是 iOS 內建的輕量級臉部**檢測**工具,適合「找臉、框臉、取五官位置」等場景。若需完整「人臉識別」(Who is this?),請使用 Vision Framework(iOS 11+)或集成 OpenCV/dlib 進行面紋提取與比對。選型原則:優先系統框架,次之成熟開源庫,最後考慮雲端 API。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
庫特點適用場景
OpenCV功能全、跨平台、C++ 核心、需橋接離線、高性能、自定義訓練
Face.com (已停止)雲端 API、準確率高聯網、不想自建模型
Vision Framework (iOS 11+)系統級、支援面紋比對、易用現代 iOS 專案首選