ML Kit를 사용하면 이미지에서 인식된 객체에 라벨을 지정할 수 있습니다. ML Kit와 함께 제공되는 기본 모델은 400개 이상의 서로 다른 라벨을 지원합니다.
사용해 보기
- 샘플 앱을 살펴보고 이 API의 사용 예를 확인하세요.
시작하기 전에
- Podfile에 다음 ML Kit 포드를 추가합니다.
pod 'GoogleMLKit/ImageLabeling', '3.2.0'
- 프로젝트의 포드를 설치하거나 업데이트한 후
.xcworkspace
를 사용하여 Xcode 프로젝트를 엽니다. ML Kit는 Xcode 버전 12.4 이상에서 지원됩니다.
이제 이미지에 라벨을 지정할 수 있습니다.
1. 입력 이미지 준비
UIImage
또는 CMSampleBuffer
를 사용하여 VisionImage
객체를 만듭니다.
UIImage
를 사용하는 경우 다음 단계를 따르세요.
UIImage
로VisionImage
객체를 만듭니다. 올바른.orientation
를 지정해야 합니다.Swift
let image = VisionImage(image: UIImage) visionImage.orientation = image.imageOrientation
Objective-C
MLKVisionImage *visionImage = [[MLKVisionImage alloc] initWithImage:image]; visionImage.orientation = image.imageOrientation;
CMSampleBuffer
를 사용하는 경우 다음 단계를 따르세요.
-
CMSampleBuffer
에 포함된 이미지 데이터의 방향을 지정합니다.이미지 방향을 가져오는 방법은 다음과 같습니다.
Swift
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 } }
Objective-C
- (UIImageOrientation) imageOrientationFromDeviceOrientation:(UIDeviceOrientation)deviceOrientation cameraPosition:(AVCaptureDevicePosition)cameraPosition { switch (deviceOrientation) { case UIDeviceOrientationPortrait: return cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationLeftMirrored : UIImageOrientationRight; case UIDeviceOrientationLandscapeLeft: return cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationDownMirrored : UIImageOrientationUp; case UIDeviceOrientationPortraitUpsideDown: return cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationRightMirrored : UIImageOrientationLeft; case UIDeviceOrientationLandscapeRight: return cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationUpMirrored : UIImageOrientationDown; case UIDeviceOrientationUnknown: case UIDeviceOrientationFaceUp: case UIDeviceOrientationFaceDown: return UIImageOrientationUp; } }
CMSampleBuffer
객체와 방향을 사용하여VisionImage
객체를 만듭니다.Swift
let image = VisionImage(buffer: sampleBuffer) image.orientation = imageOrientation( deviceOrientation: UIDevice.current.orientation, cameraPosition: cameraPosition)
Objective-C
MLKVisionImage *image = [[MLKVisionImage alloc] initWithBuffer:sampleBuffer]; image.orientation = [self imageOrientationFromDeviceOrientation:UIDevice.currentDevice.orientation cameraPosition:cameraPosition];
2. 이미지 라벨러 구성 및 실행
이미지의 객체에 라벨을 지정하려면VisionImage
객체를 ImageLabeler
의 processImage()
메서드에 전달합니다.
- 먼저
ImageLabeler
의 인스턴스를 가져옵니다.
Swift
let labeler = ImageLabeler.imageLabeler() // Or, to set the minimum confidence required: // let options = ImageLabelerOptions() // options.confidenceThreshold = 0.7 // let labeler = ImageLabeler.imageLabeler(options: options)
Objective-C
MLKImageLabeler *labeler = [MLKImageLabeler imageLabeler]; // Or, to set the minimum confidence required: // MLKImageLabelerOptions *options = // [[MLKImageLabelerOptions alloc] init]; // options.confidenceThreshold = 0.7; // MLKImageLabeler *labeler = // [MLKImageLabeler imageLabelerWithOptions:options];
- 이제 이미지를
processImage()
메서드에 전달합니다.
Swift
labeler.process(image) { labels, error in guard error == nil, let labels = labels else { return } // Task succeeded. // ... }
Objective-C
[labeler processImage:image completion:^(NSArray*_Nullable labels, NSError *_Nullable error) { if (error != nil) { return; } // Task succeeded. // ... }];
3. 라벨이 지정된 객체 정보 가져오기
이미지에 라벨을 지정하는 데 성공하면 완료 핸들러가 ImageLabel
객체의 배열을 수신합니다. 각 ImageLabel
객체는 이미지에서 라벨이 지정된 항목을 나타냅니다. 기본 모델에서는 400개 이상의 다양한 라벨을 지원합니다.
각 라벨의 텍스트 설명, 모델이 지원하는 모든 라벨 간의 색인, 일치 신뢰도 점수를 가져올 수 있습니다. 예를 들면 다음과 같습니다.
Swift
for label in labels { let labelText = label.text let confidence = label.confidence let index = label.index }
Objective-C
for (MLKImageLabel *label in labels) { NSString *labelText = label.text; float confidence = label.confidence; NSInteger index = label.index; }
실시간 성능 개선을 위한 팁
실시간 애플리케이션에서 이미지 라벨을 지정하려는 경우 최상의 프레임 속도를 얻으려면 다음 가이드라인을 따르세요.
- 동영상 프레임을 처리하려면 이미지 라벨러의
results(in:)
동기 API를 사용합니다.AVCaptureVideoDataOutputSampleBufferDelegate
의captureOutput(_, didOutput:from:)
함수에서 이 메서드를 호출하여 주어진 동영상 프레임에서 결과를 동기식으로 가져옵니다.AVCaptureVideoDataOutput
의alwaysDiscardsLateVideoFrames
를true
로 유지하여 이미지 라벨러 호출을 제한합니다. 이미지 라벨러가 실행 중일 때 새 동영상 프레임이 제공되면 삭제됩니다. - 이미지 라벨러 출력을 사용하여 입력 이미지에서 그래픽을 오버레이하는 경우 먼저 ML Kit에서 결과를 가져온 후 이미지를 렌더링하고 단일 단계로 오버레이합니다. 이렇게 하면 처리된 입력 프레임마다 한 번만 디스플레이 표면에 렌더링됩니다. 예시는 ML Kit 빠른 시작 샘플의 updatePreviewOverlayViewWithLastFrame을 참조하세요.