Android에서 ML Kit를 사용하여 바코드 스캔

ML Kit를 사용하여 바코드를 인식하고 디코딩할 수 있습니다.

특성번들로 묶이지 않음번들
구현모델이 Google Play 서비스를 통해 동적으로 다운로드됩니다.모델이 빌드 시간에 앱에 정적으로 연결됩니다.
앱 크기크기가 약 200KB 증가합니다.크기가 약 2.4MB 증가합니다.
초기화 시간처음 사용하기 전에 모델이 다운로드될 때까지 기다려야 할 수도 있습니다.모델을 즉시 사용할 수 있습니다.

사용해 보기

시작하기 전에

  1. 프로젝트 수준 build.gradle 파일의 buildscriptallprojects 섹션에 Google의 Maven 저장소가 포함되어야 합니다.

  2. 모듈의 앱 수준 Gradle 파일(일반적으로 app/build.gradle)에 ML Kit Android 라이브러리의 종속 항목을 추가합니다. 필요에 따라 다음 종속 항목 중 하나를 선택합니다.

    모델을 앱과 번들로 묶는 방법은 다음과 같습니다.

    dependencies {
      // ...
      // Use this dependency to bundle the model with your app
      implementation 'com.google.mlkit:barcode-scanning:17.2.0'
    }
    

    Google Play 서비스에서 모델을 사용하는 경우:

    dependencies {
      // ...
      // Use this dependency to use the dynamically downloaded model in Google Play Services
      implementation 'com.google.android.gms:play-services-mlkit-barcode-scanning:18.3.0'
    }
    
  3. Google Play 서비스에서 모델을 사용하기로 선택한 경우 Play 스토어에서 앱이 설치된 후 기기에 모델을 자동으로 다운로드하도록 앱을 구성할 수 있습니다. 이를 위해 다음 선언을 앱의 AndroidManifest.xml 파일에 추가합니다.

    <application ...>
          ...
          <meta-data
              android:name="com.google.mlkit.vision.DEPENDENCIES"
              android:value="barcode" >
          <!-- To use multiple models: android:value="barcode,model2,model3" -->
    </application>
    

    Google Play 서비스 ModuleInstallClient API를 통해 모델 가용성을 명시적으로 확인하고 다운로드를 요청할 수도 있습니다.

    설치 시 모델 다운로드를 사용 설정하지 않거나 명시적 다운로드를 요청하지 않으면 스캐너를 처음 실행할 때 모델이 다운로드됩니다. 다운로드가 완료되기 전에 요청하면 결과가 생성되지 않습니다.

입력 이미지 가이드라인

  • ML Kit가 바코드를 정확하게 읽으려면 입력 이미지에 충분한 픽셀 데이터로 표시된 바코드가 있어야 합니다.

    많은 바코드가 가변 크기 페이로드를 지원하므로 특정 픽셀 데이터 요구사항은 바코드 유형과 바코드에 인코딩된 데이터 양에 따라 달라집니다. 일반적으로 바코드의 의미 있는 최소 단위는 너비가 2픽셀 이상이어야 하며 2차원 코드의 경우 높이가 2픽셀 이상이어야 합니다.

    예를 들어 EAN-13 바코드는 너비가 1, 2, 3 또는 4단위인 막대와 공백으로 구성되므로 EAN-13 바코드 이미지에는 너비가 2, 4, 6, 8픽셀 이상인 막대와 공간이 있는 것이 좋습니다. EAN-13 바코드는 너비가 총 95단위이므로 바코드의 너비는 190픽셀 이상이어야 합니다.

    PDF417과 같은 밀도 형식은 ML Kit에서 안정적으로 읽으려면 더 큰 픽셀 크기가 필요합니다. 예를 들어 PDF417 코드는 한 행에 17단위 너비의 '단어'를 최대 34개 포함할 수 있으며, 너비는 1156픽셀 이상인 것이 이상적입니다.

  • 이미지 초점이 잘 맞지 않으면 스캔 정확도에 영향을 줄 수 있습니다. 앱이 허용 가능한 결과를 얻지 못하는 경우 사용자에게 이미지를 다시 캡처하도록 요청합니다.

  • 일반적인 애플리케이션의 경우 카메라에서 더 멀리 떨어진 곳에서도 바코드를 스캔할 수 있도록 1280x720 또는 1920x1080과 같은 고해상도 이미지를 제공하는 것이 좋습니다.

    그러나 지연 시간이 중요한 애플리케이션에서는 낮은 해상도에서 이미지를 캡처하되 바코드가 입력 이미지의 대부분을 차지하도록 하면 성능을 개선할 수 있습니다. 실시간 성능 향상을 위한 팁도 참조하세요.

1. 바코드 스캐너 구성

읽으려는 바코드 형식을 알고 있는 경우 해당 형식만 감지하도록 구성하여 바코드 감지기의 속도를 높일 수 있습니다.

예를 들어 Aztec 코드와 QR 코드만 인식하려면 다음 예와 같이 BarcodeScannerOptions 객체를 빌드합니다.

Kotlin

val options = BarcodeScannerOptions.Builder()
        .setBarcodeFormats(
                Barcode.FORMAT_QR_CODE,
                Barcode.FORMAT_AZTEC)
        .build()

Java

BarcodeScannerOptions options =
        new BarcodeScannerOptions.Builder()
        .setBarcodeFormats(
                Barcode.FORMAT_QR_CODE,
                Barcode.FORMAT_AZTEC)
        .build();

지원되는 형식은 다음과 같습니다.

  • Code 128 (FORMAT_CODE_128)
  • Code 39 (FORMAT_CODE_39)
  • Code 93 (FORMAT_CODE_93)
  • Codabar (FORMAT_CODABAR)
  • EAN-13 (FORMAT_EAN_13)
  • EAN-8 (FORMAT_EAN_8)
  • ITF (FORMAT_ITF)
  • UPC-A (FORMAT_UPC_A)
  • UPC-E (FORMAT_UPC_E)
  • QR 코드 (FORMAT_QR_CODE)
  • PDF417 (FORMAT_PDF417)
  • Aztec (FORMAT_AZTEC)
  • Data Matrix (FORMAT_DATA_MATRIX)

번들 모델 17.1.0 및 번들 해제된 모델 18.2.0부터는 enableAllPotentialBarcodes()를 호출하여 디코딩할 수 없는 잠재적 바코드도 모두 반환할 수 있습니다. 예를 들어 카메라를 확대하여 반환된 경계 상자의 바코드 이미지를 더 선명하게 얻는 등 추가 감지를 용이하게 하는 데 사용할 수 있습니다.

Kotlin

val options = BarcodeScannerOptions.Builder()
        .setBarcodeFormats(...)
        .enableAllPotentialBarcodes() // Optional
        .build()

Java

BarcodeScannerOptions options =
        new BarcodeScannerOptions.Builder()
        .setBarcodeFormats(...)
        .enableAllPotentialBarcodes() // Optional
        .build();

Further on, starting from bundled library 17.2.0 and unbundled library 18.3.0, a new feature called auto-zoom has been introduced to further enhance the barcode scanning experience. With this feature enabled, the app is notified when all barcodes within the view are too distant for decoding. As a result, the app can effortlessly adjust the camera's zoom ratio to the recommended setting provided by the library, ensuring optimal focus and readability. This feature will significantly enhance the accuracy and success rate of barcode scanning, making it easier for apps to capture information precisely.

To enable auto-zooming and customize the experience, you can utilize the setZoomSuggestionOptions() method along with your own ZoomCallback handler and desired maximum zoom ratio, as demonstrated in the code below.

Kotlin

val options = BarcodeScannerOptions.Builder()
        .setBarcodeFormats(...)
        .setZoomSuggestionOptions(
            new ZoomSuggestionOptions.Builder(zoomCallback)
                .setMaxSupportedZoomRatio(maxSupportedZoomRatio)
                .build()) // Optional
        .build()

Java

BarcodeScannerOptions options =
        new BarcodeScannerOptions.Builder()
        .setBarcodeFormats(...)
        .setZoomSuggestionOptions(
            new ZoomSuggestionOptions.Builder(zoomCallback)
                .setMaxSupportedZoomRatio(maxSupportedZoomRatio)
                .build()) // Optional
        .build();

zoomCallback is required to be provided to handle whenever the library suggests a zoom should be performed and this callback will always be called on the main thread.

The following code snippet shows an example of defining a simple callback.

Kotlin

fun setZoom(ZoomRatio: Float): Boolean {
    if (camera.isClosed()) return false
    camera.getCameraControl().setZoomRatio(zoomRatio)
    return true
}

Java

boolean setZoom(float zoomRatio) {
    if (camera.isClosed()) {
        return false;
    }
    camera.getCameraControl().setZoomRatio(zoomRatio);
    return true;
}

maxSupportedZoomRatio is related to the camera hardware, and different camera libraries have different ways to fetch it (see the javadoc of the setter method). In case this is not provided, an unbounded zoom ratio might be produced by the library which might not be supported. Refer to the setMaxSupportedZoomRatio() method introduction to see how to get the max supported zoom ratio with different Camera libraries.

When auto-zooming is enabled and no barcodes are successfully decoded within the view, BarcodeScanner triggers your zoomCallback with the requested zoomRatio. If the callback correctly adjusts the camera to this zoomRatio, it is highly probable that the most centered potential barcode will be decoded and returned.

A barcode may remain undecodable even after a successful zoom-in. In such cases, BarcodeScanner may either invoke the callback for another round of zoom-in until the maxSupportedZoomRatio is reached, or provide an empty list (or a list containing potential barcodes that were not decoded, if enableAllPotentialBarcodes() was called) to the OnSuccessListener (which will be defined in step 4. Process the image).

2. Prepare the input image

To recognize barcodes in an image, create an InputImage object from either a Bitmap, media.Image, ByteBuffer, byte array, or a file on the device. Then, pass the InputImage object to the BarcodeScanner's process method.

You can create an InputImage object from different sources, each is explained below.

Using a media.Image

To create an InputImage object from a media.Image object, such as when you capture an image from a device's camera, pass the media.Image object and the image's rotation to InputImage.fromMediaImage().

If you use the CameraX library, the OnImageCapturedListener and ImageAnalysis.Analyzer classes calculate the rotation value for you.

Kotlin

private class YourImageAnalyzer : ImageAnalysis.Analyzer {

    override fun analyze(imageProxy: ImageProxy) {
        val mediaImage = imageProxy.image
        if (mediaImage != null) {
            val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)
            // Pass image to an ML Kit Vision API
            // ...
        }
    }
}

Java

private class YourAnalyzer implements ImageAnalysis.Analyzer {

    @Override
    public void analyze(ImageProxy imageProxy) {
        Image mediaImage = imageProxy.getImage();
        if (mediaImage != null) {
          InputImage image =
                InputImage.fromMediaImage(mediaImage, imageProxy.getImageInfo().getRotationDegrees());
          // Pass image to an ML Kit Vision API
          // ...
        }
    }
}

이미지 회전 각도를 제공하는 카메라 라이브러리를 사용하지 않는 경우 기기의 카메라 센서 방향과 기기 회전 각도에서 이미지 회전 각도를 계산할 수 있습니다.

Kotlin

private val ORIENTATIONS = SparseIntArray()

init {
    ORIENTATIONS.append(Surface.ROTATION_0, 0)
    ORIENTATIONS.append(Surface.ROTATION_90, 90)
    ORIENTATIONS.append(Surface.ROTATION_180, 180)
    ORIENTATIONS.append(Surface.ROTATION_270, 270)
}

/**
 * Get the angle by which an image must be rotated given the device's current
 * orientation.
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Throws(CameraAccessException::class)
private fun getRotationCompensation(cameraId: String, activity: Activity, isFrontFacing: Boolean): Int {
    // Get the device's current rotation relative to its "native" orientation.
    // Then, from the ORIENTATIONS table, look up the angle the image must be
    // rotated to compensate for the device's rotation.
    val deviceRotation = activity.windowManager.defaultDisplay.rotation
    var rotationCompensation = ORIENTATIONS.get(deviceRotation)

    // Get the device's sensor orientation.
    val cameraManager = activity.getSystemService(CAMERA_SERVICE) as CameraManager
    val sensorOrientation = cameraManager
            .getCameraCharacteristics(cameraId)
            .get(CameraCharacteristics.SENSOR_ORIENTATION)!!

    if (isFrontFacing) {
        rotationCompensation = (sensorOrientation + rotationCompensation) % 360
    } else { // back-facing
        rotationCompensation = (sensorOrientation - rotationCompensation + 360) % 360
    }
    return rotationCompensation
}

Java

private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
static {
    ORIENTATIONS.append(Surface.ROTATION_0, 0);
    ORIENTATIONS.append(Surface.ROTATION_90, 90);
    ORIENTATIONS.append(Surface.ROTATION_180, 180);
    ORIENTATIONS.append(Surface.ROTATION_270, 270);
}

/**
 * Get the angle by which an image must be rotated given the device's current
 * orientation.
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private int getRotationCompensation(String cameraId, Activity activity, boolean isFrontFacing)
        throws CameraAccessException {
    // Get the device's current rotation relative to its "native" orientation.
    // Then, from the ORIENTATIONS table, look up the angle the image must be
    // rotated to compensate for the device's rotation.
    int deviceRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
    int rotationCompensation = ORIENTATIONS.get(deviceRotation);

    // Get the device's sensor orientation.
    CameraManager cameraManager = (CameraManager) activity.getSystemService(CAMERA_SERVICE);
    int sensorOrientation = cameraManager
            .getCameraCharacteristics(cameraId)
            .get(CameraCharacteristics.SENSOR_ORIENTATION);

    if (isFrontFacing) {
        rotationCompensation = (sensorOrientation + rotationCompensation) % 360;
    } else { // back-facing
        rotationCompensation = (sensorOrientation - rotationCompensation + 360) % 360;
    }
    return rotationCompensation;
}

그런 다음 media.Image 객체 및 회전 각도 값을 InputImage.fromMediaImage()에 전달합니다.

Kotlin

val image = InputImage.fromMediaImage(mediaImage, rotation)

Java

InputImage image = InputImage.fromMediaImage(mediaImage, rotation);

파일 URI 사용

파일 URI에서 InputImage 객체를 만들려면 앱 컨텍스트 및 파일 URI를 InputImage.fromFilePath()에 전달합니다. 이 기능은 ACTION_GET_CONTENT 인텐트를 사용하여 사용자에게 갤러리 앱에서 이미지를 선택하라는 메시지를 표시할 때 유용합니다.

Kotlin

val image: InputImage
try {
    image = InputImage.fromFilePath(context, uri)
} catch (e: IOException) {
    e.printStackTrace()
}

Java

InputImage image;
try {
    image = InputImage.fromFilePath(context, uri);
} catch (IOException e) {
    e.printStackTrace();
}

ByteBuffer 또는 ByteArray 사용

ByteBuffer 또는 ByteArray에서 InputImage 객체를 만들려면 앞서 media.Image 입력에서 설명한 대로 이미지 회전 각도를 먼저 계산합니다. 그런 다음 이미지의 높이, 너비, 색상 인코딩 형식, 회전 각도와 함께 버퍼 또는 배열을 사용하여 InputImage 객체를 만듭니다.

Kotlin

val image = InputImage.fromByteBuffer(
        byteBuffer,
        /* image width */ 480,
        /* image height */ 360,
        rotationDegrees,
        InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12
)
// Or:
val image = InputImage.fromByteArray(
        byteArray,
        /* image width */ 480,
        /* image height */ 360,
        rotationDegrees,
        InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12
)

Java

InputImage image = InputImage.fromByteBuffer(byteBuffer,
        /* image width */ 480,
        /* image height */ 360,
        rotationDegrees,
        InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12
);
// Or:
InputImage image = InputImage.fromByteArray(
        byteArray,
        /* image width */480,
        /* image height */360,
        rotation,
        InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12
);

Bitmap 사용

Bitmap 객체에서 InputImage 객체를 만들려면 다음과 같이 선언합니다.

Kotlin

val image = InputImage.fromBitmap(bitmap, 0)

Java

InputImage image = InputImage.fromBitmap(bitmap, rotationDegree);

이미지는 회전 각도와 함께 Bitmap 객체로 표현됩니다.

3. BarcodeScanner의 인스턴스 가져오기

Kotlin

val scanner = BarcodeScanning.getClient()
// Or, to specify the formats to recognize:
// val scanner = BarcodeScanning.getClient(options)

Java

BarcodeScanner scanner = BarcodeScanning.getClient();
// Or, to specify the formats to recognize:
// BarcodeScanner scanner = BarcodeScanning.getClient(options);

4. 이미지 처리

이미지를 process 메서드에 전달합니다.

Kotlin

val result = scanner.process(image)
        .addOnSuccessListener { barcodes ->
            // Task completed successfully
            // ...
        }
        .addOnFailureListener {
            // Task failed with an exception
            // ...
        }

Java

Task<List<Barcode>> result = scanner.process(image)
        .addOnSuccessListener(new OnSuccessListener<List<Barcode>>() {
            @Override
            public void onSuccess(List<Barcode> barcodes) {
                // Task completed successfully
                // ...
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // Task failed with an exception
                // ...
            }
        });

5. 바코드에서 정보 가져오기

바코드 인식 작업이 성공하면 Barcode 객체의 목록이 성공 리스너에 전달됩니다. 각 Barcode 객체는 이미지에서 인식된 바코드를 나타냅니다. 바코드별로 입력 이미지의 경계 좌표 및 바코드로 인코딩된 원시 데이터를 가져올 수 있습니다. 또한 바코드 스캐너가 바코드로 인코딩된 데이터 유형을 식별할 수 있는 경우 파싱된 데이터가 포함된 객체를 가져올 수 있습니다.

예를 들면 다음과 같습니다.

Kotlin

for (barcode in barcodes) {
    val bounds = barcode.boundingBox
    val corners = barcode.cornerPoints

    val rawValue = barcode.rawValue

    val valueType = barcode.valueType
    // See API reference for complete list of supported types
    when (valueType) {
        Barcode.TYPE_WIFI -> {
            val ssid = barcode.wifi!!.ssid
            val password = barcode.wifi!!.password
            val type = barcode.wifi!!.encryptionType
        }
        Barcode.TYPE_URL -> {
            val title = barcode.url!!.title
            val url = barcode.url!!.url
        }
    }
}

Java

for (Barcode barcode: barcodes) {
    Rect bounds = barcode.getBoundingBox();
    Point[] corners = barcode.getCornerPoints();

    String rawValue = barcode.getRawValue();

    int valueType = barcode.getValueType();
    // See API reference for complete list of supported types
    switch (valueType) {
        case Barcode.TYPE_WIFI:
            String ssid = barcode.getWifi().getSsid();
            String password = barcode.getWifi().getPassword();
            int type = barcode.getWifi().getEncryptionType();
            break;
        case Barcode.TYPE_URL:
            String title = barcode.getUrl().getTitle();
            String url = barcode.getUrl().getUrl();
            break;
    }
}

실시간 성능 개선을 위한 팁

실시간 애플리케이션에서 바코드를 스캔하려면 최상의 프레임 속도를 얻으려면 다음 가이드라인을 따르세요.

  • 카메라의 기본 해상도로 입력을 캡처하지 않습니다. 일부 기기에서는 기본 해상도로 입력을 캡처하면 매우 큰 (10메가픽셀 이상) 이미지가 생성되어 정확성에 아무런 이점 없이 지연 시간이 매우 단축됩니다. 대신 카메라에서 바코드를 감지하는 데 필요한 크기만 요청하세요. 이 크기는 일반적으로 2메가픽셀 이하입니다.

    스캔 속도가 중요한 경우 이미지 캡처 해상도를 더 낮출 수 있습니다. 단, 위에 설명된 최소 바코드 크기 요구사항에 유의해야 합니다.

    스트리밍 동영상 프레임 시퀀스에서 바코드를 인식하려는 경우 인식기는 프레임마다 다른 결과를 생성할 수 있습니다. 좋은 결과를 반환할 수 있도록 동일한 값의 연속을 얻을 때까지 기다려야 합니다.

    ITF 및 CODE-39에는 체크섬 숫자가 지원되지 않습니다.

  • Camera 또는 camera2 API를 사용하는 경우 감지기 호출을 제한합니다. 인식기가 실행 중일 때 새 동영상 프레임이 제공되는 경우 프레임을 낮춥니다. 관련 예는 빠른 시작 샘플 앱의 VisionProcessorBase 클래스를 참고하세요.
  • CameraX API를 사용하는 경우 백프레셔 전략이 기본값 ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST로 설정되어 있는지 확인합니다. 이렇게 하면 분석을 위해 한 번에 하나의 이미지만 제공됩니다. 분석기가 사용 중일 때 이미지가 추가로 생성되면 이미지가 자동으로 삭제되며 전송 대기열에 추가되지 않습니다. ImageProxy.close()를 호출하여 분석 중인 이미지를 닫으면 다음 최신 이미지가 전송됩니다.
  • 인식기 출력을 사용하여 입력 이미지에서 그래픽을 오버레이하는 경우 먼저 ML Kit에서 결과를 가져온 후 이미지를 렌더링하고 단일 단계로 오버레이합니다. 이는 각 입력 프레임에 대해 한 번만 디스플레이 표면에 렌더링됩니다. 관련 예는 빠른 시작 샘플 앱에서 CameraSourcePreview GraphicOverlay 클래스를 참고하세요.
  • Camera2 API를 사용할 경우 ImageFormat.YUV_420_888 형식으로 이미지를 캡처합니다. 이전 Camera API를 사용할 경우 ImageFormat.NV21 형식으로 이미지를 캡처합니다.