ตรวจจับวัตถุในภาพด้วยโมเดลที่ได้รับการฝึก AutoML บนแพลตฟอร์ม Apple

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

มีสองวิธีในการผสานรวมโมเดลที่ได้รับการฝึกจาก AutoML Vision Edge คุณสามารถรวมโมเดลเข้าด้วยกันโดยการคัดลอกไฟล์ของโมเดลลงในโปรเจ็กต์ Xcode ของคุณ หรือคุณสามารถดาวน์โหลดแบบไดนามิกได้จาก Firebase

ตัวเลือกการรวมโมเดล
รวมอยู่ในแอปของคุณ
  • โมเดลนี้เป็นส่วนหนึ่งของชุดรวม
  • รุ่นนี้สามารถใช้งานได้ทันทีแม้ในขณะที่อุปกรณ์ Apple ออฟไลน์อยู่ก็ตาม
  • ไม่จำเป็นต้องมีโปรเจ็กต์ Firebase
โฮสต์ด้วย Firebase
  • โฮสต์โมเดลโดยการอัปโหลดไปยัง Firebase Machine Learning
  • ลดขนาดชุดแอป
  • ดาวน์โหลดแบบจำลองตามความต้องการ
  • พุชการอัปเดตโมเดลโดยไม่ต้องเผยแพร่แอปของคุณซ้ำ
  • การทดสอบ A/B อย่างง่ายดายด้วย Firebase Remote Config
  • ต้องมีโปรเจ็กต์ Firebase

ก่อนที่คุณจะเริ่ม

  1. หากคุณต้องการดาวน์โหลดโมเดล ตรวจสอบ ให้แน่ใจว่าคุณ ได้เพิ่ม Firebase ลงในโปรเจ็กต์ Apple ของคุณ หากคุณยังไม่ได้ดำเนินการ สิ่งนี้ไม่จำเป็นเมื่อคุณรวมโมเดลเข้าด้วยกัน

  2. รวมไลบรารี TensorFlow และ Firebase ไว้ใน Podfile ของคุณ:

    หากต้องการรวมโมเดลเข้ากับแอปของคุณ:

    สวิฟท์

    pod 'TensorFlowLiteSwift'
    

    วัตถุประสงค์-C

    pod 'TensorFlowLiteObjC'
    

    สำหรับการดาวน์โหลดโมเดลแบบไดนามิกจาก Firebase ให้เพิ่มการพึ่งพา Firebase/MLModelInterpreter :

    สวิฟท์

    pod 'TensorFlowLiteSwift'
    pod 'Firebase/MLModelInterpreter'
    

    วัตถุประสงค์-C

    pod 'TensorFlowLiteObjC'
    pod 'Firebase/MLModelInterpreter'
    
  3. หลังจากที่คุณติดตั้งหรืออัปเดต Pod ของโปรเจ็กต์แล้ว ให้เปิดโปรเจ็กต์ Xcode โดยใช้ .xcworkspace

1. โหลดโมเดล

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

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

นอกจากนี้ โปรดดูไฟล์ tflite_metadata.json ที่สร้างขึ้นควบคู่ไปกับโมเดล คุณต้องมีสองค่า:

  • ขนาดอินพุตของโมเดล นี่คือ 320x320 โดยค่าเริ่มต้น
  • การตรวจจับสูงสุดของโมเดล นี่คือ 40 โดยค่าเริ่มต้น

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

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

สวิฟท์

let remoteModel = CustomRemoteModel(
    name: "your_remote_model"  // The name you assigned in the Google Cloud console.
)

วัตถุประสงค์-C

FIRCustomRemoteModel *remoteModel = [[FIRCustomRemoteModel alloc]
                                     initWithName:@"your_remote_model"];

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

สวิฟท์

let downloadProgress = ModelManager.modelManager().download(
    remoteModel,
    conditions: ModelDownloadConditions(
        allowsCellularAccess: true,
        allowsBackgroundDownloading: true
    )
)

วัตถุประสงค์-C

FIRModelDownloadConditions *conditions =
        [[FIRModelDownloadConditions alloc] initWithAllowsCellularAccess:YES
                                             allowsBackgroundDownloading:YES];
NSProgress *progress = [[FIRModelManager modelManager] downloadModel:remoteModel
                                                          conditions:conditions];

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

สร้างเครื่องตรวจจับวัตถุจากแบบจำลองของคุณ

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

หากคุณมีเฉพาะโมเดลที่รวมอยู่ในเครื่อง เพียงสร้างล่ามจากไฟล์โมเดล:

สวิฟท์

guard let modelPath = Bundle.main.path(
    forResource: "model",
    ofType: "tflite"
) else {
  print("Failed to load the model file.")
  return true
}
let interpreter = try Interpreter(modelPath: modelPath)
try interpreter.allocateTensors()

วัตถุประสงค์-C

NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"model"
                                                      ofType:@"tflite"];

NSError *error;
TFLInterpreter *interpreter = [[TFLInterpreter alloc] initWithModelPath:modelPath
                                                                  error:&error];
if (error != NULL) { return; }

[interpreter allocateTensorsWithError:&error];
if (error != NULL) { return; }

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

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

สวิฟท์

var modelPath: String?
if ModelManager.modelManager().isModelDownloaded(remoteModel) {
    ModelManager.modelManager().getLatestModelFilePath(remoteModel) { path, error in
        guard error == nil else { return }
        guard let path = path else { return }
        modelPath = path
    }
} else {
    modelPath = Bundle.main.path(
        forResource: "model",
        ofType: "tflite"
    )
}

guard modelPath != nil else { return }
let interpreter = try Interpreter(modelPath: modelPath)
try interpreter.allocateTensors()

วัตถุประสงค์-C

__block NSString *modelPath;
if ([[FIRModelManager modelManager] isModelDownloaded:remoteModel]) {
    [[FIRModelManager modelManager] getLatestModelFilePath:remoteModel
                                                completion:^(NSString * _Nullable filePath,
                                                             NSError * _Nullable error) {
        if (error != NULL) { return; }
        if (filePath == NULL) { return; }
        modelPath = filePath;
    }];
} else {
    modelPath = [[NSBundle mainBundle] pathForResource:@"model"
                                                ofType:@"tflite"];
}

NSError *error;
TFLInterpreter *interpreter = [[TFLInterpreter alloc] initWithModelPath:modelPath
                                                                  error:&error];
if (error != NULL) { return; }

[interpreter allocateTensorsWithError:&error];
if (error != NULL) { return; }

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

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

สวิฟท์

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]
    // ...
}

วัตถุประสงค์-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. เตรียมภาพที่นำเข้า

ถัดไป คุณต้องเตรียมรูปภาพสำหรับล่าม TensorFlow Lite

  1. ครอบตัดและปรับขนาดรูปภาพตามขนาดอินพุตของโมเดล ตามที่ระบุไว้ในไฟล์ tflite_metadata.json (ค่าเริ่มต้นคือ 320x320 พิกเซล) คุณสามารถทำได้ด้วย Core Image หรือไลบรารีบุคคลที่สาม

  2. คัดลอกข้อมูลภาพลงใน Data (วัตถุ NSData ):

    สวิฟท์

    guard let image: CGImage = // Your input image
    guard let context = CGContext(
      data: nil,
      width: image.width, height: image.height,
      bitsPerComponent: 8, bytesPerRow: image.width * 4,
      space: CGColorSpaceCreateDeviceRGB(),
      bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue
    ) else {
      return nil
    }
    
    context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))
    guard let imageData = context.data else { return nil }
    
    var inputData = Data()
    for row in 0 ..< 320 {    // Model takes 320x320 pixel images as input
      for col in 0 ..< 320 {
        let offset = 4 * (col * context.width + row)
        // (Ignore offset 0, the unused alpha channel)
        var red = imageData.load(fromByteOffset: offset+1, as: UInt8.self)
        var green = imageData.load(fromByteOffset: offset+2, as: UInt8.self)
        var blue = imageData.load(fromByteOffset: offset+3, as: UInt8.self)
    
        inputData.append(&red, count: 1)
        inputData.append(&green, count: 1)
        inputData.append(&blue, count: 1)
      }
    }
    

    วัตถุประสงค์-C

    CGImageRef image = // Your input image
    long imageWidth = CGImageGetWidth(image);
    long imageHeight = CGImageGetHeight(image);
    CGContextRef context = CGBitmapContextCreate(nil,
                                                 imageWidth, imageHeight,
                                                 8,
                                                 imageWidth * 4,
                                                 CGColorSpaceCreateDeviceRGB(),
                                                 kCGImageAlphaNoneSkipFirst);
    CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), image);
    UInt8 *imageData = CGBitmapContextGetData(context);
    
    NSMutableData *inputData = [[NSMutableData alloc] initWithCapacity:0];
    
    for (int row = 0; row < 300; row++) {
      for (int col = 0; col < 300; col++) {
        long offset = 4 * (row * imageWidth + col);
        // (Ignore offset 0, the unused alpha channel)
        UInt8 red = imageData[offset+1];
        UInt8 green = imageData[offset+2];
        UInt8 blue = imageData[offset+3];
    
        [inputData appendBytes:&red length:1];
        [inputData appendBytes:&green length:1];
        [inputData appendBytes:&blue length:1];
      }
    }
    

3. เรียกใช้เครื่องตรวจจับวัตถุ

จากนั้น ส่งข้อมูลที่เตรียมไว้ให้กับล่าม:

สวิฟท์

try interpreter.copy(inputData, toInputAt: 0)
try interpreter.invoke()

วัตถุประสงค์-C

TFLTensor *input = [interpreter inputTensorAtIndex:0 error:&error];
if (error != nil) { return; }

[input copyData:inputData error:&error];
if (error != nil) { return; }

[interpreter invokeWithError:&error];
if (error != nil) { return; }

4. รับข้อมูลเกี่ยวกับวัตถุที่ตรวจพบ

หากการตรวจจับวัตถุสำเร็จ โมเดลจะสร้างเอาต์พุตสามอาร์เรย์จาก 40 องค์ประกอบ (หรืออะไรก็ตามที่ระบุไว้ในไฟล์ tflite_metadata.json ) แต่ละรายการ แต่ละองค์ประกอบสอดคล้องกับวัตถุที่มีศักยภาพหนึ่งรายการ อาร์เรย์แรกคืออาร์เรย์ของกล่องขอบเขต ประการที่สอง อาร์เรย์ของป้ายกำกับ และประการที่สาม คืออาร์เรย์ของค่าความเชื่อมั่น หากต้องการรับเอาต์พุตของโมเดล:

สวิฟท์

var output = try interpreter.output(at: 0)
let boundingBoxes =
    UnsafeMutableBufferPointer<Float32>.allocate(capacity: 4 * 40)
output.data.copyBytes(to: boundingBoxes)

output = try interpreter.output(at: 1)
let labels =
    UnsafeMutableBufferPointer<Float32>.allocate(capacity: 40)
output.data.copyBytes(to: labels)

output = try interpreter.output(at: 2)
let probabilities =
    UnsafeMutableBufferPointer<Float32>.allocate(capacity: 40)
output.data.copyBytes(to: probabilities)

วัตถุประสงค์-C

TFLTensor *output = [interpreter outputTensorAtIndex:0 error:&error];
if (error != nil) { return; }
NSData *boundingBoxes = [output dataWithError:&error];
if (error != nil) { return; }

output = [interpreter outputTensorAtIndex:1 error:&error];
if (error != nil) { return; }
NSData *labels = [output dataWithError:&error];
if (error != nil) { return; }

output = [interpreter outputTensorAtIndex:2 error:&error];
if (error != nil) { return; }
NSData *probabilities = [output dataWithError:&error];
if (error != nil) { return; }

จากนั้น คุณสามารถรวมเอาต์พุตป้ายกำกับเข้ากับพจนานุกรมป้ายกำกับของคุณได้:

สวิฟท์

guard let labelPath = Bundle.main.path(
    forResource: "dict",
    ofType: "txt"
) else { return true }
let fileContents = try? String(contentsOfFile: labelPath)
guard let labelText = fileContents?.components(separatedBy: "\n") else { return true }

for i in 0 ..< 40 {
    let top = boundingBoxes[0 * i]
    let left = boundingBoxes[1 * i]
    let bottom = boundingBoxes[2 * i]
    let right = boundingBoxes[3 * i]

    let labelIdx = Int(labels[i])
    let label = labelText[labelIdx]
    let confidence = probabilities[i]

    if confidence > 0.66 {
        print("Object found: \(label) (confidence: \(confidence))")
        print("  Top-left: (\(left),\(top))")
        print("  Bottom-right: (\(right),\(bottom))")
    }
}

วัตถุประสงค์-C

NSString *labelPath = [NSBundle.mainBundle pathForResource:@"dict"
                                                    ofType:@"txt"];
NSString *fileContents = [NSString stringWithContentsOfFile:labelPath
                                                   encoding:NSUTF8StringEncoding
                                                      error:&error];
if (error != nil || fileContents == NULL) { return; }
NSArray<NSString*> *labelText = [fileContents componentsSeparatedByString:@"\n"];

for (int i = 0; i < 40; i++) {
    Float32 top, right, bottom, left;
    Float32 labelIdx;
    Float32 confidence;

    [boundingBoxes getBytes:&top range:NSMakeRange(16 * i + 0, 4)];
    [boundingBoxes getBytes:&left range:NSMakeRange(16 * i + 4, 4)];
    [boundingBoxes getBytes:&bottom range:NSMakeRange(16 * i + 8, 4)];
    [boundingBoxes getBytes:&right range:NSMakeRange(16 * i + 12, 4)];

    [labels getBytes:&labelIdx range:NSMakeRange(4 * i, 4)];
    [probabilities getBytes:&confidence range:NSMakeRange(4 * i, 4)];

    if (confidence > 0.5f) {
        NSString *label = labelText[(int)labelIdx];
        NSLog(@"Object detected: %@", label);
        NSLog(@"  Confidence: %f", confidence);
        NSLog(@"  Top-left: (%f,%f)", left, top);
        NSLog(@"  Bottom-right: (%f,%f)", right, bottom);
    }
}

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

หากคุณต้องการติดป้ายกำกับรูปภาพในแอปพลิเคชันแบบเรียลไทม์ ให้ปฏิบัติตามหลักเกณฑ์เหล่านี้เพื่อให้ได้อัตราเฟรมที่ดีที่สุด:

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