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

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

<ph type="x-smartling-placeholder">
기능번들로 묶이지 않음번들
구현모델은 Google Play 서비스를 통해 동적으로 다운로드됩니다.모델은 빌드 시간에 앱에 정적으로 연결됩니다.
앱 크기크기가 약 200KB 늘어났습니다.크기가 약 2.4MB 증가했습니다.
초기화 시간처음 사용하기 전에 모델이 다운로드될 때까지 기다려야 할 수 있습니다.모델을 즉시 사용할 수 있습니다.

사용해 보기

시작하기 전에

<ph type="x-smartling-placeholder">
  1. 프로젝트 수준 build.gradle 파일에 Google의 buildscriptallprojects 섹션에 있는 Maven 저장소

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

    모델을 앱과 번들로 묶는 경우:

    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 바코드는 2, 3 또는 4단위이므로 EAN-13 바코드 이미지에는 막대와 최소 너비가 2, 4, 6, 8픽셀인 공백을 사용할 수 있습니다. EAN-13이 바코드의 너비가 총 95단위이면 바코드는 최소 190이어야 합니다. 지정할 수 있습니다.

    PDF417과 같은 밀도가 높은 형식은 ML Kit를 사용하여 올바르게 읽습니다. 예를 들어 PDF417 코드는 34개의 17단위 가로 '단어' 표시할 수 있으며, 이 형식은 최소한 1156픽셀

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

  • 일반적인 애플리케이션의 경우 해상도 이미지(예: 1280x720 또는 1920x1080)로 카메라에서 더 먼 거리에서 스캔할 수 있어야 합니다.

    그러나 지연 시간이 중요한 애플리케이션에서는 더 낮은 해상도에서 이미지를 캡처하기 때문에 성능을 향상할 수 있지만 바코드가 입력 이미지의 대부분을 구성합니다. 참고 항목 실시간 성능 향상을 위한 팁

1. 바코드 스캐너 구성

읽을 바코드 형식을 알고 있으면 해당 형식만 감지하도록 구성하여 바코드 감지기의 정확도를 높입니다.

예를 들어 Aztec 코드와 QR 코드만 인식하려면 BarcodeScannerOptions 객체를 반환합니다.

Kotlin

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

자바

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

자바

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
}

자바

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 사용

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 사용

InputImage를 만들려면 다음 안내를 따르세요. ByteBuffer 또는 ByteArray 이전에 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
)

자바

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 사용

InputImage를 만들려면 다음 안내를 따르세요. 객체를 Bitmap 객체에서 삭제하려면 다음과 같이 선언합니다.

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

자바

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
                // ...
            }
        });
<ph type="x-smartling-placeholder">

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

자바

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 감지기 호출을 제한합니다. 새 동영상 감지기가 실행되는 동안 frame 사용할 수 있게 되면 프레임을 삭제합니다. 자세한 내용은 <ph type="x-smartling-placeholder"></ph> VisionProcessorBase 클래스를 참조하세요.
  • CameraX API를 사용하는 경우 백프레셔 전략이 기본값으로 설정되어 있는지 확인 ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST 이렇게 하면 분석을 위해 한 번에 하나의 이미지만 전송됩니다. 더 많은 이미지가 분석기가 사용 중일 때 생성되지 않으면 자동으로 삭제되어 배달. 분석 중인 이미지가 ImageProxy.close()를 호출하면 다음 최신 이미지가 게재됩니다.
  • 감지기 출력을 사용하여 그래픽 이미지를 먼저 ML Kit에서 결과를 가져온 후 이미지를 하나의 단계로 오버레이할 수 있습니다. 이는 디스플레이 표면에 렌더링됩니다. 각 입력 프레임에 대해 한 번만 허용됩니다. 자세한 내용은 <ph type="x-smartling-placeholder"></ph> CameraSourcePreview GraphicOverlay 클래스를 참조하세요.
  • Camera2 API를 사용하는 경우 ImageFormat.YUV_420_888 형식으로 이미지를 캡처합니다. 이전 Camera API를 사용하는 경우 ImageFormat.NV21 형식으로 이미지를 캡처합니다.