Apple प्लैटफ़ॉर्म पर AutoML के ट्रेनिंग वाले मॉडल की मदद से, इमेज में मौजूद ऑब्जेक्ट पहचानें

AutoML Vision Edge इस्तेमाल करके, अपने मॉडल को ट्रेनिंग देने के बाद, तो अपने ऐप्लिकेशन में इसका इस्तेमाल करके इमेज में मौजूद ऑब्जेक्ट का पता लगाया जा सकता है.

AutoML Vision Edge से ट्रेन किए गए मॉडल को इंटिग्रेट करने के दो तरीके हैं. आप अपने Xcode प्रोजेक्ट में मॉडल की फ़ाइलों की कॉपी बनाकर, मॉडल को बंडल करें या इसे Firebase से डाइनैमिक तौर पर डाउनलोड कर सकता है.

मॉडल बंडलिंग के विकल्प
आपके ऐप्लिकेशन में शामिल
  • मॉडल, बंडल का हिस्सा है
  • Apple डिवाइस के ऑफ़लाइन होने पर भी, मॉडल तुरंत उपलब्ध हो जाता है
  • Firebase प्रोजेक्ट की ज़रूरत नहीं होती है
Firebase के साथ होस्ट किया गया
  • मॉडल को होस्ट करने के लिए, इसे Firebase मशीन लर्निंग
  • ऐप्लिकेशन बंडल का साइज़ कम करता है
  • मॉडल को मांग पर डाउनलोड किया जाता है
  • अपने ऐप्लिकेशन को फिर से पब्लिश किए बिना, मॉडल के अपडेट पुश करें
  • Firebase रिमोट कॉन्फ़िगरेशन की मदद से आसान A/B टेस्टिंग
  • Firebase प्रोजेक्ट होना ज़रूरी है

शुरू करने से पहले

  1. अगर आपको कोई मॉडल डाउनलोड करना है, तो पक्का करें कि अपने Apple प्रोजेक्ट में Firebase जोड़ें, अगर आपने पहले से ऐसा नहीं किया है. जब आप बंडल को बंडल करते हैं, तो इसकी ज़रूरत नहीं होती है model.

  2. अपनी Podfile में TensorFlow और Firebase लाइब्रेरी शामिल करें:

    अपने ऐप्लिकेशन के साथ किसी मॉडल को बंडल करने के लिए:

    Swift

    pod 'TensorFlowLiteSwift'
    

    Objective-C

    pod 'TensorFlowLiteObjC'
    

    Firebase से मॉडल को डाइनैमिक तौर पर डाउनलोड करने के लिए, Firebase/MLModelInterpreter डिपेंडेंसी:

    Swift

    pod 'TensorFlowLiteSwift'
    pod 'Firebase/MLModelInterpreter'
    

    Objective-C

    pod 'TensorFlowLiteObjC'
    pod 'Firebase/MLModelInterpreter'
    
  3. अपने प्रोजेक्ट के Pods को इंस्टॉल या अपडेट करने के बाद, अपना Xcode प्रोजेक्ट खोलें इसके .xcworkspace का इस्तेमाल कर रहा है.

1. मॉडल लोड करें

लोकल मॉडल सोर्स कॉन्फ़िगर करना

मॉडल को अपने ऐप्लिकेशन के साथ बंडल करने के लिए, अपने Xcode प्रोजेक्ट में मॉडल और लेबल फ़ाइल को कॉपी करें. ऐसा करते समय, ऐसा करने पर, फ़ोल्डर के रेफ़रंस बनाएं. मॉडल फ़ाइल और लेबल इसे ऐप्लिकेशन बंडल में शामिल किया जाएगा.

साथ ही, tflite_metadata.json फ़ाइल को देखें, जो model. आपको दो वैल्यू की ज़रूरत होगी:

  • मॉडल के इनपुट डाइमेंशन. वीडियो का साइज़ डिफ़ॉल्ट रूप से 320x320 होता है.
  • मॉडल के ज़्यादा से ज़्यादा डिटेक्शन. डिफ़ॉल्ट रूप से यह संख्या 40 होती है.

Firebase से होस्ट किए गए मॉडल सोर्स को कॉन्फ़िगर करना

रिमोट तरीके से होस्ट किए गए मॉडल का इस्तेमाल करने के लिए, CustomRemoteModel बनाएं ऑब्जेक्ट है, जो उस नाम को दर्ज करता है जिसे आपने मॉडल को प्रकाशित करते समय असाइन किया था:

Swift

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

Objective-C

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

इसके बाद, उन शर्तों को तय करते हुए मॉडल डाउनलोड टास्क शुरू करें जिनमें आपको को डाउनलोड करने की अनुमति देनी है. अगर मॉडल डिवाइस पर नहीं है या नया डिवाइस है, तो मॉडल का वर्शन उपलब्ध है, तो टास्क एसिंक्रोनस रूप से Firebase से मिला मॉडल:

Swift

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

Objective-C

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

कई ऐप्लिकेशन अपने इनिशलाइज़ेशन कोड में डाउनलोड का काम शुरू करते हैं, लेकिन आपके द्वारा मॉडल का उपयोग करने की आवश्यकता से पहले किसी भी समय ऐसा कर सकते है.

अपने मॉडल से ऑब्जेक्ट डिटेक्टर बनाएं

मॉडल सोर्स को कॉन्फ़िगर करने के बाद, TensorFlow Lite Interpreter बनाएं ऑब्जेक्ट को ढूंढने में मदद मिलती है.

अगर आपके पास सिर्फ़ लोकल-बंडल किया गया मॉडल है, तो मॉडल फ़ाइल:

Swift

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()

Objective-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 को इंस्टैंशिएट करते समय यह जांच करना सही रहेगा: कोई रिमोट मॉडल की मदद से, अगर उसे डाउनलोड किया गया है और लोकल मॉडल से उसका अनुवाद किया गया है नहीं तो.

Swift

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()

Objective-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; }

अगर आपके पास सिर्फ़ रिमोट तौर पर होस्ट किया गया मॉडल है, तो आपको मॉडल से जुड़ी सेटिंग बंद करनी चाहिए सुविधा—उदाहरण के लिए, आपके यूज़र इंटरफ़ेस (यूआई) के किसी हिस्से को धूसर करना या छिपाना—जब तक तो यह पुष्टि की जाती है कि मॉडल डाउनलोड किया गया है.

ऑब्ज़र्वर को डिफ़ॉल्ट में अटैच करके मॉडल डाउनलोड स्थिति का पता लगाया जा सकता है सूचना केंद्र. पक्का करें कि ऑब्ज़र्वर में, 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. इनपुट इमेज तैयार करें

इसके बाद, आपको TensorFlow Lite के अनुवादक के लिए अपनी इमेज तैयार करनी होंगी.

  1. इमेज को मॉडल के इनपुट डाइमेंशन के हिसाब से काटें और स्केल करें, जैसा कि यहां बताया गया है tflite_metadata.json फ़ाइल (डिफ़ॉल्ट रूप से 320x320 पिक्सल). यह किया जा सकता है कोर इमेज या तीसरे पक्ष की लाइब्रेरी के साथ

  2. इमेज के डेटा को Data (NSData ऑब्जेक्ट) में कॉपी करें:

    Swift

    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)
      }
    }
    

    Objective-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. ऑब्जेक्ट डिटेक्टर चलाएं

इसके बाद, तैयार इनपुट को अनुवादक को पास करें:

Swift

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

Objective-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 फ़ाइल में बताया गया था) है. हर एलिमेंट एक संभावित ऑब्जेक्ट से जुड़ा होता है. पहला अरे बाउंडिंग बॉक्स का कलेक्शन है; दूसरा, लेबल का कलेक्शन; तीसरा, कॉन्फ़िडेंस वैल्यू का कलेक्शन. मॉडल के आउटपुट पाने के लिए:

Swift

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)

Objective-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; }

इसके बाद, लेबल के आउटपुट को लेबल डिक्शनरी के साथ जोड़ें:

Swift

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))")
    }
}

Objective-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 उदाहरण के लिए शोकेस सैंपल ऐप्लिकेशन में क्लास.