ติดป้ายกำกับรูปภาพด้วยโมเดลที่ฝึกด้วย AutoML บน iOS

หลังจากที่ฝึกโมเดลของคุณเองโดยใช้ AutoML Vision Edge แล้ว คุณจะใช้โมเดลดังกล่าวในแอปเพื่อติดป้ายกำกับรูปภาพได้

ก่อนเริ่มต้น

  1. หากยังไม่ได้เพิ่ม Firebase ลงในแอป โปรดทำตามขั้นตอนในคู่มือเริ่มต้นใช้งาน
  2. รวมไลบรารี ML Kit ไว้ใน Podfile ดังนี้
    pod 'Firebase/MLVision', '6.25.0'
    pod 'Firebase/MLVisionAutoML', '6.25.0'
    
    หลังจากติดตั้งหรืออัปเดตพ็อดของโปรเจ็กต์แล้ว อย่าลืมเปิดโปรเจ็กต์ Xcode โดยใช้ .xcworkspace
  3. ในแอป ให้นำเข้า Firebase ดังนี้

    Swift

    import Firebase

    Objective-C

    @import Firebase;

1. โหลดโมเดล

ML Kit จะเรียก��ช้โมเดลที่ AutoML สร้างขึ้นบนอุปกรณ์ ��ย่า��������������ม คุณกำหนดค่า ML Kit ให้โหลดโมเดลจากระยะไกลจาก Firebase, จากพื้นที่เก็บข้อมูลในเครื่อง หรือทั้ง 2 อย่างก็ได้

การโฮสต์โมเดลใน Firebase จะช่วยให้คุณอัปเดตโมเดลได้โดยไม่ต้องเผยแพร่แอปเวอร์ชันใหม่ รวมทั้งใช้การกำหนดค่าระยะไกลและการทดสอบ A/B เพื่อแสดงโมเดลต่างๆ แก่ผู้ใช้กลุ่มต่างๆ แบบไดนามิกได้

หากเลือกระบุโมเดลโดยการโฮสต์โมเดลด้วย Firebase เท่านั้น โดยไม่รวมเข้ากับแอป ให้ลดขนาดการดาวน์โหลดเริ่มต้นของแอปได้ แต่โปรดทราบว่าหากโมเดลไม่ได้รวมมากับแอป ฟังก์ชันที่เกี่ยวข้องกับโมเดลจะใช้งานไม่ได้จนกว่าแอปจะดาวน์โหลดโมเดลเป็นครั้งแรก

การรวมโมเดลกับแอปจะทำให้ฟีเจอร์ ML ของแอปยังคงทำงานได้เมื่อโมเดลที่โฮสต์โดย Firebase ไม่พร้อมใช้งาน

กำหนดค่าแหล่งที่มาของโมเดลที่โฮสต์กับ Firebase

หากต้องการใช้โมเดลที่โฮสต์จากระยะไกล ให้สร้างออบเจ็กต์ AutoMLRemoteModel โดยระบุชื่อที่คุณกำหนดให้กับโมเดลเมื่อเผยแพร่

Swift

let remoteModel = AutoMLRemoteModel(
    name: "your_remote_model"  // The name you assigned in the Firebase console.
)

Objective-C

FIRAutoMLRemoteModel *remoteModel = [[FIRAutoMLRemoteModel alloc]
    initWithName:@"your_remote_model"];  // The name you assigned in the Firebase console.

จากนั้นเริ่มงานการดาวน์โหลดโมเดล โดยระบุเงื่อนไขที่คุณต้องการอนุญาตให้ดาวน์โหลด หากโมเดลไม่ได้อยู่ในอุปกรณ์หรือหากมีโมเดลเวอร์ชันใหม่กว่า งานจะดาวน์โหลดโมเดลแบบไม่พร้อมกันจาก Firebase

Swift

let downloadConditions = ModelDownloadConditions(
  allowsCellularAccess: true,
  allowsBackgroundDownloading: true
)

let downloadProgress = ModelManager.modelManager().download(
  remoteModel,
  conditions: downloadConditions
)

Objective-C

FIRModelDownloadConditions *downloadConditions =
    [[FIRModelDownloadConditions alloc] initWithAllowsCellularAccess:YES
                                         allowsBackgroundDownloading:YES];

NSProgress *downloadProgress =
    [[FIRModelManager modelManager] downloadRemoteModel:remoteModel
                                             conditions:downloadConditions];

แอปจำนวนมากเริ่มงานดาวน์โหลดในโค้ดการเริ่มต้น แต่คุณ ทำได้ทุกเมื่อก่อนที่จะต้องใช้โมเดล

กำหนดค่าต้นทางของโมเดลในเครื่อง

วิธีการรวมโมเดลกับแอปมีดังนี้

  1. แยกโมเดลและข้อมูลเมตาจากชุดไฟล์ Zip ที่คุณดาวน์โหลดจากคอนโซล Firebase ลงในโฟลเดอร์ โดยทำดังนี้
    your_model_directory
      |____dict.txt
      |____manifest.json
      |____model.tflite
    
    ทั้ง 3 ไฟล์ต้องอยู่ในโฟลเดอร์เดียวกัน เราขอแนะนำให้คุณใช้ไฟล์ขณะที่ดาวน์โหลดโดยไม่ต้องแก้ไข (รวมถึงชื่อไฟล์)
  2. คัดลอกโฟลเดอร์ไปยังโปรเจ็กต์ Xcode และอย่าลืมเลือกสร้างการอ้างอิงโฟลเดอร์ เมื่อคัดลอกแล้ว ไฟล์โมเดลและข้อมูลเมตาจะรวมอยู่ใน App Bundle และพร้อมใช้งานสำหรับ ML Kit
  3. สร้างออบเจ็กต์ AutoMLLocalModel โดยระบุเส้นทางไปยังไฟล์ Manifest ของโมเดล ดังนี้

    Swift

    guard let manifestPath = Bundle.main.path(
        forResource: "manifest",
        ofType: "json",
        inDirectory: "your_model_directory"
    ) else { return true }
    let localModel = AutoMLLocalModel(manifestPath: manifestPath)
    

    Objective-C

    NSString *manifestPath = [NSBundle.mainBundle pathForResource:@"manifest"
                                                           ofType:@"json"
                                                      inDirectory:@"your_model_directory"];
    FIRAutoMLLocalModel *localModel = [[FIRAutoMLLocalModel alloc] initWithManifestPath:manifestPath];
    

สร้างเครื่องมือติดป้ายกำกับรูปภาพจากโมเดล

หลังจากที่กำหนดค่าแหล่งที่มาของโมเดลแล้ว ให้สร้างออบเจ็กต์ VisionImageLabeler จากหนึ่งในแหล่งที่มาของโมเดล

หากคุณมีเฉพาะโมเดลที่รวมภายในเครื่อง ก็เพียงสร้างผู้ติดป้ายกำกับจากออบเจ็กต์ AutoMLLocalModel และกำหนดค่าเกณฑ์คะแนนความเชื่อมั่นที่ต้องการ (ดูประเมินโมเดลของคุณ)

Swift

let options = VisionOnDeviceAutoMLImageLabelerOptions(localModel: localModel)
options.confidenceThreshold = 0  // Evaluate your model in the Firebase console
                                 // to determine an appropriate value.
let labeler = Vision.vision().onDeviceAutoMLImageLabeler(options: options)

Objective-C

FIRVisionOnDeviceAutoMLImageLabelerOptions *options =
    [[FIRVisionOnDeviceAutoMLImageLabelerOptions alloc] initWithLocalModel:localModel];
options.confidenceThreshold = 0;  // Evaluate your model in the Firebase console
                                  // to determine an appropriate value.
FIRVisionImageLabeler *labeler =
    [[FIRVision vision] onDeviceAutoMLImageLabelerWithOptions:options];

หากมีโมเดลที่โฮสต์จากระยะไกล คุณจะต้องตรวจสอบว่ามีการดาวน์โหลดโมเดลแล้วก่อนที่จะเรียกใช้ คุณตรวจสอบสถานะของงานดาวน์โหลดโมเดลได้โดยใช้เมธอด isModelDownloaded(remoteModel:) ของตัวจัดการโมเดล

แม้ว่าคุณจะต้องยืนยันเรื่องนี้ก่อนเรียกใช้ผู้ติดป้ายกำกับเท่านั้น แต่หากคุณมีทั้งโมเดลที่โฮสต์จากระยะไกลและโมเดลที่รวมภายในเครื่อง ก็อาจทำให้ดำเนินการตรวจสอบนี้เมื่อเริ่มต้น VisionImageLabeler โดยสร้างเครื่องมือติดป้ายกำกับจากโมเดลระยะไกลหากมีการดาวน์โหลดไว้แล้ว หรือจากโมเดลในเครื่องหากไม่เป็นเช่นนั้น

Swift

var options: VisionOnDeviceAutoMLImageLabelerOptions?
if (ModelManager.modelManager().isModelDownloaded(remoteModel)) {
  options = VisionOnDeviceAutoMLImageLabelerOptions(remoteModel: remoteModel)
} else {
  options = VisionOnDeviceAutoMLImageLabelerOptions(localModel: localModel)
}
options.confidenceThreshold = 0  // Evaluate your model in the Firebase console
                                 // to determine an appropriate value.
let labeler = Vision.vision().onDeviceAutoMLImageLabeler(options: options)

Objective-C

VisionOnDeviceAutoMLImageLabelerOptions *options;
if ([[FIRModelManager modelManager] isModelDownloaded:remoteModel]) {
  options = [[FIRVisionOnDeviceAutoMLImageLabelerOptions alloc] initWithRemoteModel:remoteModel];
} else {
  options = [[FIRVisionOnDeviceAutoMLImageLabelerOptions alloc] initWithLocalModel:localModel];
}
options.confidenceThreshold = 0.0f;  // Evaluate your model in the Firebase console
                                     // to determine an appropriate value.
FIRVisionImageLabeler *labeler = [[FIRVision vision] onDeviceAutoMLImageLabelerWithOptions:options];

หากคุณมีเฉพาะโมเดลที่โฮสต์จากระยะไกล คุณควรปิดใช้ฟังก์ชันที่เกี่ยวข้องกับโมเดล เช่น เป็นสีเทาหรือซ่อนบางส่วนของ UI จนกว่าจะยืนยันว่าดาวน์โหลดโมเดลแล้ว

คุณดูสถานะการดาวน์โหลดโมเดลได้โดยแนบผู้สังเกตการณ์เข้ากับศูนย์การแจ้งเตือนเริ่มต้น อย่าลืมใช้การอ้างอิงที่ไม่รัดกุมไปยัง self ในบล็อกผู้สังเกตการณ์ เนื่องจากการดาวน์โหลดอาจใช้เวลาสักครู่ และออบเจ็กต์เริ่มต้นจะพร้อมใช้งานได้ในขณะที่การดาวน์โหลดเสร็จสิ้น ตัวอย่างเช่น

Swift

NotificationCenter.default.addObserver(
    forName: .firebaseMLModelDownloadDidSucceed,
    object: nil,
    queue: nil
) { [weak self] notification in
    guard let strongSelf = self,
        let userInfo = notification.userInfo,
        let model = userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue]
            as? RemoteModel,
        model.name == "your_remote_model"
        else { return }
    // The model was downloaded and is available on the device
}

NotificationCenter.default.addObserver(
    forName: .firebaseMLModelDownloadDidFail,
    object: nil,
    queue: nil
) { [weak self] notification in
    guard let strongSelf = self,
        let userInfo = notification.userInfo,
        let model = userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue]
            as? RemoteModel
        else { return }
    let error = userInfo[ModelDownloadUserInfoKey.error.rawValue]
    // ...
}

Objective-C

__weak typeof(self) weakSelf = self;

[NSNotificationCenter.defaultCenter
    addObserverForName:FIRModelDownloadDidSucceedNotification
                object:nil
                 queue:nil
            usingBlock:^(NSNotification *_Nonnull note) {
              if (weakSelf == nil | note.userInfo == nil) {
                return;
              }
              __strong typeof(self) strongSelf = weakSelf;

              FIRRemoteModel *model = note.userInfo[FIRModelDownloadUserInfoKeyRemoteModel];
              if ([model.name isEqualToString:@"your_remote_model"]) {
                // The model was downloaded and is available on the device
              }
            }];

[NSNotificationCenter.defaultCenter
    addObserverForName:FIRModelDownloadDidFailNotification
                object:nil
                 queue:nil
            usingBlock:^(NSNotification *_Nonnull note) {
              if (weakSelf == nil | note.userInfo == nil) {
                return;
              }
              __strong typeof(self) strongSelf = weakSelf;

              NSError *error = note.userInfo[FIRModelDownloadUserInfoKeyError];
            }];

2. เตรียมรูปภาพอินพุต

จากนั้น สำหรับแต่ละรูปภาพที่ต้องการติดป้ายกำกับ ให้สร้างออบเจ็กต์ VisionImage โดยใช้ตัวเลือกใดตัวเลือกหนึ่งที่อธิบายไว้ในส่วนนี้และส่งต่อไปยังอินสแตนซ์ของ VisionImageLabeler (ตามที่อธิบายไว้ในส่วนถัดไป)

สร้างออบเจ็กต์ VisionImage โดยใช้ UIImage หรือ CMSampleBufferRef

วิธีใช้ UIImage

  1. หากจำเป็น ให้หมุนรูปภาพเพื่อให้พร็อพเพอร์ตี้ imageOrientation เป็น .up
  2. สร้างออบเจ็กต์ VisionImage โดยใช้ UIImage ที่หมุนอย่างถูกต้อง และไม่ระบุข้อมูลเมตาการหมุนเวียน ระบบจะใช้ค่าเริ่มต้นซึ่งก็คือ .topLeft

    Swift

    let image = VisionImage(image: uiImage)

    Objective-C

    FIRVisionImage *image = [[FIRVisionImage alloc] initWithImage:uiImage];

วิธีใช้ CMSampleBufferRef

  1. สร้างออบเจ็กต์ VisionImageMetadata ที่ระบุการวางแนวของข้อมูลรูปภาพที่อยู่ในบัฟเฟอร์ CMSampleBufferRef

    วิธีดูการวางแนวรูปภาพ

    Swift

    func imageOrientation(
        deviceOrientation: UIDeviceOrientation,
        cameraPosition: AVCaptureDevice.Position
        ) -> VisionDetectorImageOrientation {
        switch deviceOrientation {
        case .portrait:
            return cameraPosition == .front ? .leftTop : .rightTop
        case .landscapeLeft:
            return cameraPosition == .front ? .bottomLeft : .topLeft
        case .portraitUpsideDown:
            return cameraPosition == .front ? .rightBottom : .leftBottom
        case .landscapeRight:
            return cameraPosition == .front ? .topRight : .bottomRight
        case .faceDown, .faceUp, .unknown:
            return .leftTop
        }
    }

    Objective-C

    - (FIRVisionDetectorImageOrientation)
        imageOrientationFromDeviceOrientation:(UIDeviceOrientation)deviceOrientation
                               cameraPosition:(AVCaptureDevicePosition)cameraPosition {
      switch (deviceOrientation) {
        case UIDeviceOrientationPortrait:
          if (cameraPosition == AVCaptureDevicePositionFront) {
            return FIRVisionDetectorImageOrientationLeftTop;
          } else {
            return FIRVisionDetectorImageOrientationRightTop;
          }
        case UIDeviceOrientationLandscapeLeft:
          if (cameraPosition == AVCaptureDevicePositionFront) {
            return FIRVisionDetectorImageOrientationBottomLeft;
          } else {
            return FIRVisionDetectorImageOrientationTopLeft;
          }
        case UIDeviceOrientationPortraitUpsideDown:
          if (cameraPosition == AVCaptureDevicePositionFront) {
            return FIRVisionDetectorImageOrientationRightBottom;
          } else {
            return FIRVisionDetectorImageOrientationLeftBottom;
          }
        case UIDeviceOrientationLandscapeRight:
          if (cameraPosition == AVCaptureDevicePositionFront) {
            return FIRVisionDetectorImageOrientationTopRight;
          } else {
            return FIRVisionDetectorImageOrientationBottomRight;
          }
        default:
          return FIRVisionDetectorImageOrientationTopLeft;
      }
    }

    จากนั้นสร้างออบเจ็กต์ข้อมูลเมตา ดังนี้

    Swift

    let cameraPosition = AVCaptureDevice.Position.back  // Set to the capture device you used.
    let metadata = VisionImageMetadata()
    metadata.orientation = imageOrientation(
        deviceOrientation: UIDevice.current.orientation,
        cameraPosition: cameraPosition
    )

    Objective-C

    FIRVisionImageMetadata *metadata = [[FIRVisionImageMetadata alloc] init];
    AVCaptureDevicePosition cameraPosition =
        AVCaptureDevicePositionBack;  // Set to the capture device you used.
    metadata.orientation =
        [self imageOrientationFromDeviceOrientation:UIDevice.currentDevice.orientation
                                     cameraPosition:cameraPosition];
  2. สร้างออบเจ็กต์ VisionImage โดยใช้ออบเจ็กต์ CMSampleBufferRef และข้อมูลเมตาการหมุน ดังนี้

    Swift

    let image = VisionImage(buffer: sampleBuffer)
    image.metadata = metadata

    Objective-C

    FIRVisionImage *image = [[FIRVisionImage alloc] initWithBuffer:sampleBuffer];
    image.metadata = metadata;

3. เรียกใช้เครื่องมือติดป้ายกำกับรูปภาพ

หากต้องการติดป้ายกำกับออบเจ็กต์ในรูปภาพ ให้ส่งออบเจ็กต์ VisionImage ไปยังเมธอด process() ของ VisionImageLabeler ดังนี้

Swift

labeler.process(image) { labels, error in
    guard error == nil, let labels = labels else { return }

    // Task succeeded.
    // ...
}

Objective-C

[labeler
    processImage:image
      completion:^(NSArray<FIRVisionImageLabel *> *_Nullable labels, NSError *_Nullable error) {
        if (error != nil || labels == nil) {
          return;
        }

        // Task succeeded.
        // ...
      }];

หากการติดป้ายกำกับรูปภาพสำเร็จ ระบบจะส่งอาร์เรย์ของออบเจ็กต์ VisionImageLabel ไปยังเครื่องจัดการเสร็จสมบูรณ์ จากวัตถุแต่ละอย่าง คุณจะเห็นข้อมูล เกี่ยวกับองค์ประกอบที่รู้จักในรูปภาพ

ตัวอย่างเช่น

Swift

for label in labels {
    let labelText = label.text
    let confidence = label.confidence
}

Objective-C

for (FIRVisionImageLabel *label in labels) {
  NSString *labelText = label.text;
  NSNumber *confidence = label.confidence;
}

เคล็ดลับในการปรับปรุงประสิทธิภาพแบบเรียลไทม์

  • กดคันเร่งไปยังตัวตรวจจับ หากมีเฟรมวิดีโอใหม่ขณะที่ตัวตรวจจับทำงานอยู่ ให้วางเฟรมดังกล่าว
  • หากคุณกำลังใ��้เอาต์พุตของเครื่องมือตรวจจับเพื่อวางซ้อนกราฟิกบนรูปภาพอินพุต ให้รับผลลัพธ์จาก ML Kit ก่อน จากนั้นจึงแสดงผลรูปภาพและการวางซ้อนในขั้นตอนเดียว การทำเช่นนี้จะทําให้คุณแสดงผลบนพื้นผิวจอแสดงผลเพียงครั้งเดียวสําหรับเฟรมอินพุตแต่ละเฟรม โปรดดูคลาส previewOverlayView และ FIRDetectionOverlayView ในแอปตัวอย่าง Showcase