AutoML Vision Edge에서 학습된 모델을 통합하는 방법에는 두 가지가 있습니다. 모델의 파일을 Xcode 프로젝트에 복사하여 모델을 번들로 묶거나 Firebase에서 동적으로 다운로드할 수 있습니다.
모델 번들 옵션 | |
---|---|
앱에 번들 |
|
Firebase로 호스팅 |
|
시작하기 전에
Podfile에 ML Kit 라이브러리를 포함합니다.
앱과 모델을 번들로 묶는 경우:
pod 'GoogleMLKit/ImageLabelingCustom'
Firebase에서 모델을 동적으로 다운로드하려면
LinkFirebase
종속성을 추가합니다.pod 'GoogleMLKit/ImageLabelingCustom' pod 'GoogleMLKit/LinkFirebase'
프로젝트의 Pod를 설치하거나 업데이트한 후
.xcworkspace
를 사용하여 Xcode 프로젝트를 엽니다. ML Kit는 Xcode 버전 12.2 이상에서 지원됩니다.모델을 다운로드 하려면 Android 프로젝트에 Firebase를 아직 추가하지 않은 경우 추가 해야 합니다. 모델을 번들로 묶을 때는 필요하지 않습니다.
1. 모델 로드
로컬 모델 소스 구성
모델을 앱과 번들로 묶으려면 다음 안내를 따르세요.
Firebase 콘솔에서 다운로드한 zip 아카이브에서 모델과 해당 메타데이터를 폴더로 추출합니다.
your_model_directory |____dict.txt |____manifest.json |____model.tflite
세 파일 모두 같은 폴더에 있어야 합니다. 파일명을 포함하여 수정 없이 다운로드 받은 그대로 사용하는 것을 권장합니다.
폴더를 Xcode 프로젝트에 복사하고 폴더 참조 생성 을 선택하도록 주의하십시오. 모델 파일과 메타데이터는 앱 번들에 포함되며 ML Kit에서 사용할 수 있습니다.
모델 매니페스트 파일의 경로를 지정하여
LocalModel
개체를 만듭니다.빠른
guard let manifestPath = Bundle.main.path( forResource: "manifest", ofType: "json", inDirectory: "your_model_directory" ) else { return true } let localModel = LocalModel(manifestPath: manifestPath)
오브젝티브-C
NSString *manifestPath = [NSBundle.mainBundle pathForResource:@"manifest" ofType:@"json" inDirectory:@"your_model_directory"]; MLKLocalModel *localModel = [[MLKLocalModel alloc] initWithManifestPath:manifestPath];
Firebase 호스팅 모델 소스 구성
원격으로 호스팅되는 모델을 사용하려면 모델을 게시할 때 할당한 이름을 지정하여 CustomRemoteModel
개체를 만듭니다.
빠른
// Initialize the model source with the name you assigned in
// the Firebase console.
let remoteModelSource = FirebaseModelSource(name: "your_remote_model")
let remoteModel = CustomRemoteModel(remoteModelSource: remoteModelSource)
오브젝티브-C
// Initialize the model source with the name you assigned in
// the Firebase console.
MLKFirebaseModelSource *firebaseModelSource =
[[MLKFirebaseModelSource alloc] initWithName:@"your_remote_model"];
MLKCustomRemoteModel *remoteModel =
[[MLKCustomRemoteModel alloc] initWithRemoteModelSource:firebaseModelSource];
그런 다음 다운로드를 허용할 조건을 지정하여 모델 다운로드 작업을 시작합니다. 모델이 기기에 없거나 최신 버전의 모델을 사용할 수 있는 경우 작업은 Firebase에서 모델을 비동기식으로 다운로드합니다.
빠른
let downloadConditions = ModelDownloadConditions(
allowsCellularAccess: true,
allowsBackgroundDownloading: true
)
let downloadProgress = ModelManager.modelManager().download(
remoteModel,
conditions: downloadConditions
)
오브젝티브-C
MLKModelDownloadConditions *downloadConditions =
[[MLKModelDownloadConditions alloc] initWithAllowsCellularAccess:YES
allowsBackgroundDownloading:YES];
NSProgress *downloadProgress =
[[MLKModelManager modelManager] downloadRemoteModel:remoteModel
conditions:downloadConditions];
많은 앱이 초기화 코드에서 다운로드 작업을 시작하지만 모델을 사용하기 전에 언제든지 시작할 수 있습니다.
모델에서 이미지 라벨러 만들기
모델 소스를 구성한 후 그 중 하나에서 ImageLabeler
개체를 만듭니다.
로컬 번들 모델만 있는 경우 LocalModel
개체에서 레이블러를 만들고 필요한 신뢰도 점수 임계값을 구성하기만 하면 됩니다( 모델 평가 참조).
빠른
let options = CustomImageLabelerOptions(localModel: localModel)
options.confidenceThreshold = NSNumber(value: 0.0) // Evaluate your model in the Cloud console
// to determine an appropriate value.
let imageLabeler = ImageLabeler.imageLabeler(options)
오브젝티브-C
CustomImageLabelerOptions *options =
[[CustomImageLabelerOptions alloc] initWithLocalModel:localModel];
options.confidenceThreshold = @(0.0f); // Evaluate your model in the Cloud console
// to determine an appropriate value.
MLKImageLabeler *imageLabeler =
[MLKImageLabeler imageLabelerWithOptions:options];
원격으로 호스트되는 모델이 있는 경우 실행하기 전에 다운로드되었는지 확인해야 합니다. 모델 관리자의 isModelDownloaded(remoteModel:)
메소드를 사용하여 모델 다운로드 작업의 상태를 확인할 수 있습니다.
라벨러를 실행하기 전에 이것을 확인하기만 하면 되지만, 원격 호스팅 모델과 로컬 번들 모델이 모두 있는 경우 ImageLabeler
를 인스턴스화할 때 이 검사를 수행하는 것이 합리적일 수 있습니다. 다운로드되고 그렇지 않은 경우 로컬 모델에서 다운로드됩니다.
빠른
var options: CustomImageLabelerOptions
if (ModelManager.modelManager().isModelDownloaded(remoteModel)) {
options = CustomImageLabelerOptions(remoteModel: remoteModel)
} else {
options = CustomImageLabelerOptions(localModel: localModel)
}
options.confidenceThreshold = NSNumber(value: 0.0) // Evaluate your model in the Firebase console
// to determine an appropriate value.
let imageLabeler = ImageLabeler.imageLabeler(options: options)
오브젝티브-C
MLKCustomImageLabelerOptions *options;
if ([[MLKModelManager modelManager] isModelDownloaded:remoteModel]) {
options = [[MLKCustomImageLabelerOptions alloc] initWithRemoteModel:remoteModel];
} else {
options = [[MLKCustomImageLabelerOptions alloc] initWithLocalModel:localModel];
}
options.confidenceThreshold = @(0.0f); // Evaluate your model in the Firebase console
// to determine an appropriate value.
MLKImageLabeler *imageLabeler =
[MLKImageLabeler imageLabelerWithOptions:options];
원격으로 호스팅되는 모델만 있는 경우 모델이 다운로드되었음을 확인할 때까지 모델 관련 기능(예: UI 일부를 회색으로 표시하거나 숨기기)을 비활성화해야 합니다.
기본 알림 센터에 관찰자를 연결하여 모델 다운로드 상태를 얻을 수 있습니다. 다운로드에 시간이 걸릴 수 있고 다운로드가 완료될 때 원래 개체가 해제될 수 있으므로 관찰자 블록에서 self
에 대한 약한 참조를 사용해야 합니다. 예를 들어:
빠른
NotificationCenter.default.addObserver(
forName: .mlkitMLModelDownloadDidSucceed,
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: .mlkitMLModelDownloadDidFail,
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:MLKModelDownloadDidSucceedNotification
object:nil
queue:nil
usingBlock:^(NSNotification *_Nonnull note) {
if (weakSelf == nil | note.userInfo == nil) {
return;
}
__strong typeof(self) strongSelf = weakSelf;
MLKRemoteModel *model = note.userInfo[MLKModelDownloadUserInfoKeyRemoteModel];
if ([model.name isEqualToString:@"your_remote_model"]) {
// The model was downloaded and is available on the device
}
}];
[NSNotificationCenter.defaultCenter
addObserverForName:MLKModelDownloadDidFailNotification
object:nil
queue:nil
usingBlock:^(NSNotification *_Nonnull note) {
if (weakSelf == nil | note.userInfo == nil) {
return;
}
__strong typeof(self) strongSelf = weakSelf;
NSError *error = note.userInfo[MLKModelDownloadUserInfoKeyError];
}];
2. 입력 이미지 준비
UIImage
또는 CMSampleBufferRef
를 사용하여 VisionImage
개체를 만듭니다.
UIImage
를 사용하는 경우 다음 단계를 따르세요.
-
UIImage
를 사용하여VisionImage
객체를 만듭니다. 올바른.orientation
을 지정했는지 확인하십시오.빠른
let image = VisionImage(image: uiImage) visionImage.orientation = image.imageOrientation
오브젝티브-C
MLKVisionImage *visionImage = [[MLKVisionImage alloc] initWithImage:image]; visionImage.orientation = image.imageOrientation;
CMSampleBufferRef
를 사용하는 경우 다음 단계를 따르세요.
CMSampleBufferRef
버퍼에 포함된 이미지 데이터의 방향을 지정합니다.이미지 방향을 얻으려면:
빠른
func imageOrientation( deviceOrientation: UIDeviceOrientation, cameraPosition: AVCaptureDevice.Position ) -> UIImage.Orientation { switch deviceOrientation { case .portrait: return cameraPosition == .front ? .leftMirrored : .right case .landscapeLeft: return cameraPosition == .front ? .downMirrored : .up case .portraitUpsideDown: return cameraPosition == .front ? .rightMirrored : .left case .landscapeRight: return cameraPosition == .front ? .upMirrored : .down case .faceDown, .faceUp, .unknown: return .up } }
오브젝티브-C
- (UIImageOrientation) imageOrientationFromDeviceOrientation:(UIDeviceOrientation)deviceOrientation cameraPosition:(AVCaptureDevicePosition)cameraPosition { switch (deviceOrientation) { case UIDeviceOrientationPortrait: return position == AVCaptureDevicePositionFront ? UIImageOrientationLeftMirrored : UIImageOrientationRight; case UIDeviceOrientationLandscapeLeft: return position == AVCaptureDevicePositionFront ? UIImageOrientationDownMirrored : UIImageOrientationUp; case UIDeviceOrientationPortraitUpsideDown: return position == AVCaptureDevicePositionFront ? UIImageOrientationRightMirrored : UIImageOrientationLeft; case UIDeviceOrientationLandscapeRight: return position == AVCaptureDevicePositionFront ? UIImageOrientationUpMirrored : UIImageOrientationDown; case UIDeviceOrientationUnknown: case UIDeviceOrientationFaceUp: case UIDeviceOrientationFaceDown: return UIImageOrientationUp; } }
-
CMSampleBufferRef
개체 및 방향을 사용하여VisionImage
개체를 만듭니다.빠른
let image = VisionImage(buffer: sampleBuffer) image.orientation = imageOrientation( deviceOrientation: UIDevice.current.orientation, cameraPosition: cameraPosition)
오브젝티브-C
MLKVisionImage *image = [[MLKVisionImage alloc] initWithBuffer:sampleBuffer]; image.orientation = [self imageOrientationFromDeviceOrientation:UIDevice.currentDevice.orientation cameraPosition:cameraPosition];
3. 이미지 라벨러 실행
비동기적으로:
빠른
imageLabeler.process(image) { labels, error in
guard error == nil, let labels = labels, !labels.isEmpty else {
// Handle the error.
return
}
// Show results.
}
오브젝티브-C
[imageLabeler
processImage:image
completion:^(NSArray<MLKImageLabel *> *_Nullable labels,
NSError *_Nullable error) {
if (label.count == 0) {
// Handle the error.
return;
}
// Show results.
}];
동기:
빠른
var labels: [ImageLabel]
do {
labels = try imageLabeler.results(in: image)
} catch let error {
// Handle the error.
return
}
// Show results.
오브젝티브-C
NSError *error;
NSArray<MLKImageLabel *> *labels =
[imageLabeler resultsInImage:image error:&error];
// Show results or handle the error.
4. 레이블이 지정된 개체에 대한 정보 가져오기
이미지 레이블 지정 작업이 성공하면ImageLabel
배열이 반환됩니다. 각 ImageLabel
은 이미지에 레이블이 지정된 것을 나타냅니다. 각 레이블의 텍스트 설명(TensorFlow Lite 모델 파일의 메타데이터에서 사용 가능한 경우), 신뢰도 점수 및 색인을 얻을 수 있습니다. 예를 들어: 빠른
for label in labels {
let labelText = label.text
let confidence = label.confidence
let index = label.index
}
오브젝티브-C
for (MLKImageLabel *label in labels) {
NSString *labelText = label.text;
float confidence = label.confidence;
NSInteger index = label.index;
}
실시간 성능 향상을 위한 팁
실시간 응용 프로그램에서 이미지에 레이블을 지정하려면 다음 지침에 따라 최상의 프레임 속도를 얻으십시오.
- 감지기에 대한 호출을 조절합니다. 감지기가 실행되는 동안 새 비디오 프레임을 사용할 수 있게 되면 프레임을 삭제합니다.
- 감지기의 출력을 사용하여 입력 이미지에 그래픽을 오버레이하는 경우 먼저 결과를 얻은 다음 이미지를 렌더링하고 한 번에 오버레이합니다. 이렇게 하면 각 입력 프레임에 대해 한 번만 디스플레이 표면에 렌더링됩니다. 예제는 쇼케이스 샘플 앱의 previewOverlayView 및 FIRDetectionOverlayView 클래스를 참조하세요.