Android पर एमएल किट की मदद से, इमेज में मौजूद टेक्स्ट की पहचान करना

इमेज में मौजूद टेक्स्ट की पहचान करने के लिए, ML Kit का इस्तेमाल किया जा सकता है. ML Kit में दो तरह के एपीआई होते हैं. एक सामान्य एपीआई होता है, जो इमेज में मौजूद टेक्स्ट की पहचान करने के लिए सही होता है. जैसे, सड़क के साइन बोर्ड पर लिखा टेक्स्ट. दूसरा एपीआई, दस्तावेज़ों में मौजूद टेक्स्ट की पहचान करने के लिए ऑप्टिमाइज़ किया गया होता है. सामान्य कामों के लिए उपलब्ध एपीआई में, ऑन-डिवाइस और क्लाउड-आधारित, दोनों तरह के मॉडल होते हैं. दस्तावेज़ में मौजूद टेक्स्ट की पहचान करने की सुविधा, सिर्फ़ क्लाउड पर आधारित मॉडल के तौर पर उपलब्ध है. क्लाउड और डिवाइस पर मौजूद मॉडल की तुलना करने के लिए, खास जानकारी देखें.

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

  1. अगर आपने पहले से ही A/B टेस्टिंग नहीं बनाई है, तो अपने Android प्रोजेक्ट में Firebase जोड़ें.
  2. ML Kit Android लाइब्रेरी के लिए डिपेंडेंसी को अपने मॉड्यूल (ऐप्लिकेशन-लेवल) की Gradle फ़ाइल में जोड़ें. आम तौर पर, यह फ़ाइल app/build.gradle होती है:
    apply plugin: 'com.android.application'
    apply plugin: 'com.google.gms.google-services'
    
    dependencies {
      // ...
    
      implementation 'com.google.firebase:firebase-ml-vision:24.0.3'
    }
  3. ज़रूरी नहीं है, लेकिन हमारा सुझाव है कि आप ऐसा करें: अगर आपने डिवाइस पर काम करने वाले एपीआई का इस्तेमाल किया है, तो अपने ऐप्लिकेशन को इस तरह कॉन्फ़िगर करें कि Play Store से इंस्टॉल होने के बाद, एमएल मॉडल अपने-आप डिवाइस पर डाउनलोड हो जाए.

    इसके लिए, अपने ऐप्लिकेशन की AndroidManifest.xml फ़ाइल में यह एलान जोड़ें:

    <application ...>
      ...
      <meta-data
          android:name="com.google.firebase.ml.vision.DEPENDENCIES"
          android:value="ocr" />
      <!-- To use multiple models: android:value="ocr,model2,model3" -->
    </application>
    अगर आपने मॉडल को इंस्टॉल करने के दौरान डाउनलोड करने की सुविधा चालू नहीं की है, तो मॉडल को पहली बार तब डाउनलोड किया जाएगा, जब आपने डिवाइस पर मौजूद डिटेक्टर को चलाया हो. डाउनलोड पूरा होने से पहले किए गए अनुरोधों के नतीजे नहीं दिखेंगे.
  4. अगर आपको क्लाउड-आधारित मॉडल का इस्तेमाल करना है और आपने अपने प्रोजेक्ट के लिए क्लाउड-आधारित एपीआई पहले से चालू नहीं किए हैं, तो अभी ऐसा करें:

    1. Firebase कंसोल के ML Kit APIs पेज को खोलें.
    2. अगर आपने अब तक अपने प्रोजेक्ट को Blaze प्लान में अपग्रेड नहीं किया है, तो ऐसा करने के लिए अपग्रेड करें पर क्लिक करें. (आपको अपग्रेड करने के लिए सिर्फ़ तब कहा जाएगा, जब आपका प्रोजेक्ट Blaze प्लान पर नहीं होगा.)

      क्लाउड पर आधारित एपीआई का इस्तेमाल सिर्फ़ ब्लेज़-लेवल के प्रोजेक्ट कर सकते हैं.

    3. अगर क्लाउड पर आधारित एपीआई पहले से चालू नहीं हैं, तो क्लाउड पर आधारित एपीआई चालू करें पर क्लिक करें.

    अगर आपको सिर्फ़ डिवाइस पर मौजूद मॉडल का इस्तेमाल करना है, तो इस चरण को छोड़ा जा सकता है.

अब आपके पास इमेज में मौजूद टेक्स्ट की पहचान करने की सुविधा है.

इनपुट इमेज के लिए दिशा-निर्देश

  • एमएल किट को टेक्स्ट की सही पहचान करने के लिए, इनपुट इमेज में ऐसा टेक्स्ट होना चाहिए जिसे दिखाने के लिए पिक्सल का सही डेटा इस्तेमाल किया गया हो. लैटिन टेक्स्ट के लिए, हर वर्ण कम से कम 16x16 पिक्सल का होना चाहिए. चाइनीज़, जैपनीज़, और कोरियन टेक्स्ट के लिए (सिर्फ़ क्लाउड पर आधारित एपीआई के साथ काम करता है), हर वर्ण 24x24 पिक्सल का होना चाहिए. आम तौर पर, सभी भाषाओं के लिए, वर्णों को 24x24 पिक्सल से बड़ा करने पर, सटीकता में कोई फ़ायदा नहीं होता.

    इसलिए, उदाहरण के लिए, 640x480 इमेज का इस्तेमाल करके, ऐसे बिजनेस कार्ड को स्कैन किया जा सकता है जो इमेज की पूरी चौड़ाई में हो. लेटर साइज़ के पेपर पर प्रिंट किए गए दस्तावेज़ को स्कैन करने के लिए, 720x1280 पिक्सल की इमेज की ज़रूरत पड़ सकती है.

  • इमेज का फ़ोकस सही न होने पर, टेक्स्ट पहचानने की सुविधा सटीक तरीके से काम नहीं करती. अगर आपको सही नतीजे नहीं मिल रहे हैं, तो उपयोगकर्ता से इमेज को फिर से कैप्चर करने के लिए कहें.

  • अगर आपको किसी रीयल-टाइम ऐप्लिकेशन में टेक्स्ट की पहचान करनी है, तो आपको इनपुट इमेज के कुल डाइमेंशन पर भी ध्यान देना चाहिए. छोटी इमेज को तेज़ी से प्रोसेस किया जा सकता है. इसलिए, इमेज को कम रिज़ॉल्यूशन पर कैप्चर करें, ताकि लेटेन्सी कम हो. हालांकि, इस दौरान ऊपर बताई गई सटीकता से जुड़ी ज़रूरी शर्तों का ध्यान रखें. साथ ही, यह पक्का करें कि इमेज में ज़्यादा से ज़्यादा टेक्स्ट शामिल हो. रीयल-टाइम परफ़ॉर्मेंस को बेहतर बनाने के लिए सलाह भी देखें.


इमेज में मौजूद टेक्स्ट की पहचान करना

डिवाइस पर मौजूद या क्लाउड पर आधारित मॉडल का इस्तेमाल करके, किसी इमेज में मौजूद टेक्स्ट को पहचानने के लिए, टेक्स्ट पहचानने वाले टूल को नीचे दिए गए तरीके से चलाएं.

1. टेक्स्ट आइडेंटिफ़ायर को चालू करना

किसी इमेज में मौजूद टेक्स्ट को पहचानने के लिए, FirebaseVisionImage ऑब्जेक्ट बनाएं. इसके लिए, Bitmap, media.Image, ByteBuffer, बाइट ऐरे या डिवाइस पर मौजूद किसी फ़ाइल का इस्तेमाल करें. इसके बाद, FirebaseVisionImage ऑब्जेक्ट को FirebaseVisionTextRecognizer के processImage तरीके में पास करें.

  1. अपनी इमेज से FirebaseVisionImage ऑब्जेक्ट बनाएं.

    • किसी media.Image ऑब्जेक्ट से FirebaseVisionImage ऑब्जेक्ट बनाने के लिए, FirebaseVisionImage.fromMediaImage() को media.Image ऑब्जेक्ट और इमेज का रोटेशन पास करें. ऐसा तब किया जाता है, जब किसी डिवाइस के कैमरे से इमेज कैप्चर की जाती है.

      अगर CameraX लाइब्रेरी का इस्तेमाल किया जाता है, तो OnImageCapturedListener और ImageAnalysis.Analyzer क्लास, रोटेशन वैल्यू का हिसाब लगाती हैं. इसलिए, आपको रोटेशन को ML Kit के ROTATION_ कॉन्स्टेंट में से किसी एक में बदलना होगा. इसके बाद, FirebaseVisionImage.fromMediaImage() को कॉल करें:

      Java

      private class YourAnalyzer implements ImageAnalysis.Analyzer {
      
          private int degreesToFirebaseRotation(int degrees) {
              switch (degrees) {
                  case 0:
                      return FirebaseVisionImageMetadata.ROTATION_0;
                  case 90:
                      return FirebaseVisionImageMetadata.ROTATION_90;
                  case 180:
                      return FirebaseVisionImageMetadata.ROTATION_180;
                  case 270:
                      return FirebaseVisionImageMetadata.ROTATION_270;
                  default:
                      throw new IllegalArgumentException(
                              "Rotation must be 0, 90, 180, or 270.");
              }
          }
      
          @Override
          public void analyze(ImageProxy imageProxy, int degrees) {
              if (imageProxy == null || imageProxy.getImage() == null) {
                  return;
              }
              Image mediaImage = imageProxy.getImage();
              int rotation = degreesToFirebaseRotation(degrees);
              FirebaseVisionImage image =
                      FirebaseVisionImage.fromMediaImage(mediaImage, rotation);
              // Pass image to an ML Kit Vision API
              // ...
          }
      }

      Kotlin

      private class YourImageAnalyzer : ImageAnalysis.Analyzer {
          private fun degreesToFirebaseRotation(degrees: Int): Int = when(degrees) {
              0 -> FirebaseVisionImageMetadata.ROTATION_0
              90 -> FirebaseVisionImageMetadata.ROTATION_90
              180 -> FirebaseVisionImageMetadata.ROTATION_180
              270 -> FirebaseVisionImageMetadata.ROTATION_270
              else -> throw Exception("Rotation must be 0, 90, 180, or 270.")
          }
      
          override fun analyze(imageProxy: ImageProxy?, degrees: Int) {
              val mediaImage = imageProxy?.image
              val imageRotation = degreesToFirebaseRotation(degrees)
              if (mediaImage != null) {
                  val image = FirebaseVisionImage.fromMediaImage(mediaImage, imageRotation)
                  // Pass image to an ML Kit Vision API
                  // ...
              }
          }
      }

      अगर आपको ऐसी कैमरा लाइब्रेरी का इस्तेमाल नहीं करना है जो आपको इमेज के रोटेशन की जानकारी देती है, तो डिवाइस के रोटेशन और डिवाइस में मौजूद कैमरा सेंसर के ओरिएंटेशन के हिसाब से, इमेज के रोटेशन का हिसाब लगाया जा सकता है:

      Java

      private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
      static {
          ORIENTATIONS.append(Surface.ROTATION_0, 90);
          ORIENTATIONS.append(Surface.ROTATION_90, 0);
          ORIENTATIONS.append(Surface.ROTATION_180, 270);
          ORIENTATIONS.append(Surface.ROTATION_270, 180);
      }
      
      /**
       * 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, Context context)
              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);
      
          // On most devices, the sensor orientation is 90 degrees, but for some
          // devices it is 270 degrees. For devices with a sensor orientation of
          // 270, rotate the image an additional 180 ((270 + 270) % 360) degrees.
          CameraManager cameraManager = (CameraManager) context.getSystemService(CAMERA_SERVICE);
          int sensorOrientation = cameraManager
                  .getCameraCharacteristics(cameraId)
                  .get(CameraCharacteristics.SENSOR_ORIENTATION);
          rotationCompensation = (rotationCompensation + sensorOrientation + 270) % 360;
      
          // Return the corresponding FirebaseVisionImageMetadata rotation value.
          int result;
          switch (rotationCompensation) {
              case 0:
                  result = FirebaseVisionImageMetadata.ROTATION_0;
                  break;
              case 90:
                  result = FirebaseVisionImageMetadata.ROTATION_90;
                  break;
              case 180:
                  result = FirebaseVisionImageMetadata.ROTATION_180;
                  break;
              case 270:
                  result = FirebaseVisionImageMetadata.ROTATION_270;
                  break;
              default:
                  result = FirebaseVisionImageMetadata.ROTATION_0;
                  Log.e(TAG, "Bad rotation value: " + rotationCompensation);
          }
          return result;
      }

      Kotlin

      private val ORIENTATIONS = SparseIntArray()
      
      init {
          ORIENTATIONS.append(Surface.ROTATION_0, 90)
          ORIENTATIONS.append(Surface.ROTATION_90, 0)
          ORIENTATIONS.append(Surface.ROTATION_180, 270)
          ORIENTATIONS.append(Surface.ROTATION_270, 180)
      }
      /**
       * 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, context: Context): 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)
      
          // On most devices, the sensor orientation is 90 degrees, but for some
          // devices it is 270 degrees. For devices with a sensor orientation of
          // 270, rotate the image an additional 180 ((270 + 270) % 360) degrees.
          val cameraManager = context.getSystemService(CAMERA_SERVICE) as CameraManager
          val sensorOrientation = cameraManager
                  .getCameraCharacteristics(cameraId)
                  .get(CameraCharacteristics.SENSOR_ORIENTATION)!!
          rotationCompensation = (rotationCompensation + sensorOrientation + 270) % 360
      
          // Return the corresponding FirebaseVisionImageMetadata rotation value.
          val result: Int
          when (rotationCompensation) {
              0 -> result = FirebaseVisionImageMetadata.ROTATION_0
              90 -> result = FirebaseVisionImageMetadata.ROTATION_90
              180 -> result = FirebaseVisionImageMetadata.ROTATION_180
              270 -> result = FirebaseVisionImageMetadata.ROTATION_270
              else -> {
                  result = FirebaseVisionImageMetadata.ROTATION_0
                  Log.e(TAG, "Bad rotation value: $rotationCompensation")
              }
          }
          return result
      }

      इसके बाद, media.Image ऑब्जेक्ट और रोटेशन वैल्यू को FirebaseVisionImage.fromMediaImage() में पास करें:

      Java

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

      Kotlin

      val image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation)
    • फ़ाइल यूआरआई से FirebaseVisionImage ऑब्जेक्ट बनाने के लिए, ऐप्लिकेशन के कॉन्टेक्स्ट और फ़ाइल यूआरआई को FirebaseVisionImage.fromFilePath() में पास करें. यह तब काम आता है, जब आपको उपयोगकर्ता को उसकी गैलरी ऐप्लिकेशन से कोई इमेज चुनने के लिए प्रॉम्प्ट करना हो. इसके लिए, ACTION_GET_CONTENT इंटेंट का इस्तेमाल करें.

      Java

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

      Kotlin

      val image: FirebaseVisionImage
      try {
          image = FirebaseVisionImage.fromFilePath(context, uri)
      } catch (e: IOException) {
          e.printStackTrace()
      }
    • ByteBuffer या बाइट ऐरे से FirebaseVisionImage ऑब्जेक्ट बनाने के लिए, सबसे पहले इमेज के रोटेशन का हिसाब लगाएं. इसके लिए, media.Image इनपुट के लिए ऊपर बताया गया तरीका अपनाएं.

      इसके बाद, एक FirebaseVisionImageMetadata ऑब्जेक्ट बनाएं. इसमें इमेज की ऊंचाई, चौड़ाई, कलर एन्कोडिंग फ़ॉर्मैट, और रोटेशन की जानकारी शामिल करें:

      Java

      FirebaseVisionImageMetadata metadata = new FirebaseVisionImageMetadata.Builder()
              .setWidth(480)   // 480x360 is typically sufficient for
              .setHeight(360)  // image recognition
              .setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21)
              .setRotation(rotation)
              .build();

      Kotlin

      val metadata = FirebaseVisionImageMetadata.Builder()
              .setWidth(480) // 480x360 is typically sufficient for
              .setHeight(360) // image recognition
              .setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21)
              .setRotation(rotation)
              .build()

      बफ़र या ऐरे और मेटाडेटा ऑब्जेक्ट का इस्तेमाल करके, FirebaseVisionImage ऑब्जेक्ट बनाएं:

      Java

      FirebaseVisionImage image = FirebaseVisionImage.fromByteBuffer(buffer, metadata);
      // Or: FirebaseVisionImage image = FirebaseVisionImage.fromByteArray(byteArray, metadata);

      Kotlin

      val image = FirebaseVisionImage.fromByteBuffer(buffer, metadata)
      // Or: val image = FirebaseVisionImage.fromByteArray(byteArray, metadata)
    • Bitmap ऑब्जेक्ट से FirebaseVisionImage ऑब्जेक्ट बनाने के लिए:

      Java

      FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);

      Kotlin

      val image = FirebaseVisionImage.fromBitmap(bitmap)
      Bitmap ऑब्जेक्ट से दिखाई गई इमेज सीधी होनी चाहिए. इसे घुमाने की ज़रूरत नहीं होनी चाहिए.

  2. FirebaseVisionTextRecognizer का इंस्टेंस पाएं.

    डिवाइस पर मौजूद मॉडल का इस्तेमाल करने के लिए:

    Java

    FirebaseVisionTextRecognizer detector = FirebaseVision.getInstance()
            .getOnDeviceTextRecognizer();

    Kotlin

    val detector = FirebaseVision.getInstance()
            .onDeviceTextRecognizer

    क्लाउड-आधारित मॉडल का इस्तेमाल करने के लिए:

    Java

    FirebaseVisionTextRecognizer detector = FirebaseVision.getInstance()
            .getCloudTextRecognizer();
    // Or, to change the default settings:
    //   FirebaseVisionTextRecognizer detector = FirebaseVision.getInstance()
    //          .getCloudTextRecognizer(options);
    // Or, to provide language hints to assist with language detection:
    // See https://cloud.google.com/vision/docs/languages for supported languages
    FirebaseVisionCloudTextRecognizerOptions options = new FirebaseVisionCloudTextRecognizerOptions.Builder()
            .setLanguageHints(Arrays.asList("en", "hi"))
            .build();

    Kotlin

    val detector = FirebaseVision.getInstance().cloudTextRecognizer
    // Or, to change the default settings:
    // val detector = FirebaseVision.getInstance().getCloudTextRecognizer(options)
    // Or, to provide language hints to assist with language detection:
    // See https://cloud.google.com/vision/docs/languages for supported languages
    val options = FirebaseVisionCloudTextRecognizerOptions.Builder()
            .setLanguageHints(listOf("en", "hi"))
            .build()
  3. आखिर में, इमेज को processImage तरीके से पास करें:

    Java

    Task<FirebaseVisionText> result =
            detector.processImage(image)
                    .addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
                        @Override
                        public void onSuccess(FirebaseVisionText firebaseVisionText) {
                            // Task completed successfully
                            // ...
                        }
                    })
                    .addOnFailureListener(
                            new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception e) {
                                    // Task failed with an exception
                                    // ...
                                }
                            });

    Kotlin

    val result = detector.processImage(image)
            .addOnSuccessListener { firebaseVisionText ->
                // Task completed successfully
                // ...
            }
            .addOnFailureListener { e ->
                // Task failed with an exception
                // ...
            }

2. पहचाने गए टेक्स्ट के ब्लॉक से टेक्स्ट निकालना

अगर टेक्स्ट पहचानने की प्रोसेस पूरी हो जाती है, तो FirebaseVisionText ऑब्जेक्ट को success listener को पास कर दिया जाएगा. FirebaseVisionText ऑब्जेक्ट में, इमेज में पहचाना गया पूरा टेक्स्ट और शून्य या उससे ज़्यादा TextBlock ऑब्जेक्ट शामिल होते हैं.

हर TextBlock, टेक्स्ट के आयताकार ब्लॉक को दिखाता है. इसमें शून्य या इससे ज़्यादा Line ऑब्जेक्ट होते हैं. हर Line ऑब्जेक्ट में शून्य या उससे ज़्यादा Element ऑब्जेक्ट होते हैं. ये ऑब्जेक्ट, शब्दों और शब्द जैसी इकाइयों (तारीखें, संख्याएं वगैरह) को दिखाते हैं.

हर TextBlock, Line, और Element ऑब्जेक्ट के लिए, आपको उस इलाके में पहचाना गया टेक्स्ट और उस इलाके के बाउंडिंग कोऑर्डिनेट मिल सकते हैं.

उदाहरण के लिए:

Java

String resultText = result.getText();
for (FirebaseVisionText.TextBlock block: result.getTextBlocks()) {
    String blockText = block.getText();
    Float blockConfidence = block.getConfidence();
    List<RecognizedLanguage> blockLanguages = block.getRecognizedLanguages();
    Point[] blockCornerPoints = block.getCornerPoints();
    Rect blockFrame = block.getBoundingBox();
    for (FirebaseVisionText.Line line: block.getLines()) {
        String lineText = line.getText();
        Float lineConfidence = line.getConfidence();
        List<RecognizedLanguage> lineLanguages = line.getRecognizedLanguages();
        Point[] lineCornerPoints = line.getCornerPoints();
        Rect lineFrame = line.getBoundingBox();
        for (FirebaseVisionText.Element element: line.getElements()) {
            String elementText = element.getText();
            Float elementConfidence = element.getConfidence();
            List<RecognizedLanguage> elementLanguages = element.getRecognizedLanguages();
            Point[] elementCornerPoints = element.getCornerPoints();
            Rect elementFrame = element.getBoundingBox();
        }
    }
}

Kotlin

val resultText = result.text
for (block in result.textBlocks) {
    val blockText = block.text
    val blockConfidence = block.confidence
    val blockLanguages = block.recognizedLanguages
    val blockCornerPoints = block.cornerPoints
    val blockFrame = block.boundingBox
    for (line in block.lines) {
        val lineText = line.text
        val lineConfidence = line.confidence
        val lineLanguages = line.recognizedLanguages
        val lineCornerPoints = line.cornerPoints
        val lineFrame = line.boundingBox
        for (element in line.elements) {
            val elementText = element.text
            val elementConfidence = element.confidence
            val elementLanguages = element.recognizedLanguages
            val elementCornerPoints = element.cornerPoints
            val elementFrame = element.boundingBox
        }
    }
}

रीयल-टाइम परफ़ॉर्मेंस को बेहतर बनाने के लिए सलाह

अगर आपको किसी ऐप्लिकेशन में रीयल-टाइम में टेक्स्ट पहचानने के लिए, डिवाइस पर मौजूद मॉडल का इस्तेमाल करना है, तो सबसे अच्छे फ़्रेमरेट पाने के लिए इन दिशा-निर्देशों का पालन करें:

  • टेक्स्ट पहचानने वाले टूल को किए जाने वाले कॉल की संख्या को सीमित करता है. अगर टेक्स्ट पहचानने की सुविधा चालू होने के दौरान कोई नया वीडियो फ़्रेम उपलब्ध होता है, तो फ़्रेम को छोड़ दें.
  • अगर आपको इनपुट इमेज पर ग्राफ़िक ओवरले करने के लिए, टेक्स्ट पहचानने वाले टूल के आउटपुट का इस्तेमाल करना है, तो पहले ML Kit से नतीजे पाएं. इसके बाद, इमेज रेंडर करें और उसे एक ही चरण में ओवरले करें. ऐसा करने से, हर इनपुट फ़्रेम के लिए डिसप्ले सर्फ़ेस पर सिर्फ़ एक बार रेंडर किया जाता है.
  • Camera2 API का इस्तेमाल करने पर, इमेज को ImageFormat.YUV_420_888 फ़ॉर्मैट में कैप्चर करें.

    अगर Camera API के पुराने वर्शन का इस्तेमाल किया जा रहा है, तो इमेज को ImageFormat.NV21 फ़ॉर्मैट में कैप्चर करें.

  • इमेज को कम रिज़ॉल्यूशन में कैप्चर करें. हालांकि, इस एपीआई के इमेज डाइमेंशन से जुड़ी ज़रूरी शर्तों का भी ध्यान रखें.

अगले चरण


दस्तावेज़ों की इमेज में मौजूद टेक्स्ट की पहचान करना

किसी दस्तावेज़ के टेक्स्ट को पहचानने के लिए, क्लाउड पर आधारित दस्तावेज़ के टेक्स्ट को पहचानने वाले टूल को कॉन्फ़िगर करें और उसे चलाएं. इसके लिए, यहां दिया गया तरीका अपनाएं.

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

दस्तावेज़ में मौजूद टेक्स्ट की पहचान करने वाले एपीआई का इस्तेमाल करने के लिए:

1. टेक्स्ट आइडेंटिफ़ायर को चालू करना

किसी इमेज में मौजूद टेक्स्ट को पहचानने के लिए, FirebaseVisionImage ऑब्जेक्ट बनाएं. इसके लिए, Bitmap, media.Image, ByteBuffer, बाइट कलेक्शन या डिवाइस पर मौजूद किसी फ़ाइल का इस्तेमाल करें. इसके बाद, FirebaseVisionImage ऑब्जेक्ट को FirebaseVisionDocumentTextRecognizer के processImage तरीके में पास करें.

  1. अपनी इमेज से FirebaseVisionImage ऑब्जेक्ट बनाएं.

    • किसी media.Image ऑब्जेक्ट से FirebaseVisionImage ऑब्जेक्ट बनाने के लिए, FirebaseVisionImage.fromMediaImage() को media.Image ऑब्जेक्ट और इमेज का रोटेशन पास करें. ऐसा तब किया जाता है, जब किसी डिवाइस के कैमरे से इमेज कैप्चर की जाती है.

      अगर CameraX लाइब्रेरी का इस्तेमाल किया जाता है, तो OnImageCapturedListener और ImageAnalysis.Analyzer क्लास, रोटेशन वैल्यू का हिसाब लगाती हैं. इसलिए, आपको रोटेशन को ML Kit के ROTATION_ कॉन्स्टेंट में से किसी एक में बदलना होगा. इसके बाद, FirebaseVisionImage.fromMediaImage() को कॉल करें:

      Java

      private class YourAnalyzer implements ImageAnalysis.Analyzer {
      
          private int degreesToFirebaseRotation(int degrees) {
              switch (degrees) {
                  case 0:
                      return FirebaseVisionImageMetadata.ROTATION_0;
                  case 90:
                      return FirebaseVisionImageMetadata.ROTATION_90;
                  case 180:
                      return FirebaseVisionImageMetadata.ROTATION_180;
                  case 270:
                      return FirebaseVisionImageMetadata.ROTATION_270;
                  default:
                      throw new IllegalArgumentException(
                              "Rotation must be 0, 90, 180, or 270.");
              }
          }
      
          @Override
          public void analyze(ImageProxy imageProxy, int degrees) {
              if (imageProxy == null || imageProxy.getImage() == null) {
                  return;
              }
              Image mediaImage = imageProxy.getImage();
              int rotation = degreesToFirebaseRotation(degrees);
              FirebaseVisionImage image =
                      FirebaseVisionImage.fromMediaImage(mediaImage, rotation);
              // Pass image to an ML Kit Vision API
              // ...
          }
      }

      Kotlin

      private class YourImageAnalyzer : ImageAnalysis.Analyzer {
          private fun degreesToFirebaseRotation(degrees: Int): Int = when(degrees) {
              0 -> FirebaseVisionImageMetadata.ROTATION_0
              90 -> FirebaseVisionImageMetadata.ROTATION_90
              180 -> FirebaseVisionImageMetadata.ROTATION_180
              270 -> FirebaseVisionImageMetadata.ROTATION_270
              else -> throw Exception("Rotation must be 0, 90, 180, or 270.")
          }
      
          override fun analyze(imageProxy: ImageProxy?, degrees: Int) {
              val mediaImage = imageProxy?.image
              val imageRotation = degreesToFirebaseRotation(degrees)
              if (mediaImage != null) {
                  val image = FirebaseVisionImage.fromMediaImage(mediaImage, imageRotation)
                  // Pass image to an ML Kit Vision API
                  // ...
              }
          }
      }

      अगर आपको ऐसी कैमरा लाइब्रेरी का इस्तेमाल नहीं करना है जो आपको इमेज के रोटेशन की जानकारी देती है, तो डिवाइस के रोटेशन और डिवाइस में मौजूद कैमरा सेंसर के ओरिएंटेशन के हिसाब से, इमेज के रोटेशन का हिसाब लगाया जा सकता है:

      Java

      private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
      static {
          ORIENTATIONS.append(Surface.ROTATION_0, 90);
          ORIENTATIONS.append(Surface.ROTATION_90, 0);
          ORIENTATIONS.append(Surface.ROTATION_180, 270);
          ORIENTATIONS.append(Surface.ROTATION_270, 180);
      }
      
      /**
       * 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, Context context)
              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);
      
          // On most devices, the sensor orientation is 90 degrees, but for some
          // devices it is 270 degrees. For devices with a sensor orientation of
          // 270, rotate the image an additional 180 ((270 + 270) % 360) degrees.
          CameraManager cameraManager = (CameraManager) context.getSystemService(CAMERA_SERVICE);
          int sensorOrientation = cameraManager
                  .getCameraCharacteristics(cameraId)
                  .get(CameraCharacteristics.SENSOR_ORIENTATION);
          rotationCompensation = (rotationCompensation + sensorOrientation + 270) % 360;
      
          // Return the corresponding FirebaseVisionImageMetadata rotation value.
          int result;
          switch (rotationCompensation) {
              case 0:
                  result = FirebaseVisionImageMetadata.ROTATION_0;
                  break;
              case 90:
                  result = FirebaseVisionImageMetadata.ROTATION_90;
                  break;
              case 180:
                  result = FirebaseVisionImageMetadata.ROTATION_180;
                  break;
              case 270:
                  result = FirebaseVisionImageMetadata.ROTATION_270;
                  break;
              default:
                  result = FirebaseVisionImageMetadata.ROTATION_0;
                  Log.e(TAG, "Bad rotation value: " + rotationCompensation);
          }
          return result;
      }

      Kotlin

      private val ORIENTATIONS = SparseIntArray()
      
      init {
          ORIENTATIONS.append(Surface.ROTATION_0, 90)
          ORIENTATIONS.append(Surface.ROTATION_90, 0)
          ORIENTATIONS.append(Surface.ROTATION_180, 270)
          ORIENTATIONS.append(Surface.ROTATION_270, 180)
      }
      /**
       * 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, context: Context): 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)
      
          // On most devices, the sensor orientation is 90 degrees, but for some
          // devices it is 270 degrees. For devices with a sensor orientation of
          // 270, rotate the image an additional 180 ((270 + 270) % 360) degrees.
          val cameraManager = context.getSystemService(CAMERA_SERVICE) as CameraManager
          val sensorOrientation = cameraManager
                  .getCameraCharacteristics(cameraId)
                  .get(CameraCharacteristics.SENSOR_ORIENTATION)!!
          rotationCompensation = (rotationCompensation + sensorOrientation + 270) % 360
      
          // Return the corresponding FirebaseVisionImageMetadata rotation value.
          val result: Int
          when (rotationCompensation) {
              0 -> result = FirebaseVisionImageMetadata.ROTATION_0
              90 -> result = FirebaseVisionImageMetadata.ROTATION_90
              180 -> result = FirebaseVisionImageMetadata.ROTATION_180
              270 -> result = FirebaseVisionImageMetadata.ROTATION_270
              else -> {
                  result = FirebaseVisionImageMetadata.ROTATION_0
                  Log.e(TAG, "Bad rotation value: $rotationCompensation")
              }
          }
          return result
      }

      इसके बाद, media.Image ऑब्जेक्ट और रोटेशन वैल्यू को FirebaseVisionImage.fromMediaImage() में पास करें:

      Java

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

      Kotlin

      val image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation)
    • फ़ाइल यूआरआई से FirebaseVisionImage ऑब्जेक्ट बनाने के लिए, ऐप्लिकेशन के कॉन्टेक्स्ट और फ़ाइल यूआरआई को FirebaseVisionImage.fromFilePath() में पास करें. यह तब काम आता है, जब आपको उपयोगकर्ता को उसकी गैलरी ऐप्लिकेशन से कोई इमेज चुनने के लिए प्रॉम्प्ट करना हो. इसके लिए, ACTION_GET_CONTENT इंटेंट का इस्तेमाल करें.

      Java

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

      Kotlin

      val image: FirebaseVisionImage
      try {
          image = FirebaseVisionImage.fromFilePath(context, uri)
      } catch (e: IOException) {
          e.printStackTrace()
      }
    • ByteBuffer या बाइट ऐरे से FirebaseVisionImage ऑब्जेक्ट बनाने के लिए, सबसे पहले इमेज के रोटेशन का हिसाब लगाएं. इसके लिए, media.Image इनपुट के लिए ऊपर बताया गया तरीका अपनाएं.

      इसके बाद, एक FirebaseVisionImageMetadata ऑब्जेक्ट बनाएं. इसमें इमेज की ऊंचाई, चौड़ाई, कलर एन्कोडिंग फ़ॉर्मैट, और रोटेशन की जानकारी शामिल करें:

      Java

      FirebaseVisionImageMetadata metadata = new FirebaseVisionImageMetadata.Builder()
              .setWidth(480)   // 480x360 is typically sufficient for
              .setHeight(360)  // image recognition
              .setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21)
              .setRotation(rotation)
              .build();

      Kotlin

      val metadata = FirebaseVisionImageMetadata.Builder()
              .setWidth(480) // 480x360 is typically sufficient for
              .setHeight(360) // image recognition
              .setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21)
              .setRotation(rotation)
              .build()

      बफ़र या ऐरे और मेटाडेटा ऑब्जेक्ट का इस्तेमाल करके, FirebaseVisionImage ऑब्जेक्ट बनाएं:

      Java

      FirebaseVisionImage image = FirebaseVisionImage.fromByteBuffer(buffer, metadata);
      // Or: FirebaseVisionImage image = FirebaseVisionImage.fromByteArray(byteArray, metadata);

      Kotlin

      val image = FirebaseVisionImage.fromByteBuffer(buffer, metadata)
      // Or: val image = FirebaseVisionImage.fromByteArray(byteArray, metadata)
    • Bitmap ऑब्जेक्ट से FirebaseVisionImage ऑब्जेक्ट बनाने के लिए:

      Java

      FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);

      Kotlin

      val image = FirebaseVisionImage.fromBitmap(bitmap)
      Bitmap ऑब्जेक्ट से दिखाई गई इमेज सीधी होनी चाहिए. इसे घुमाने की ज़रूरत नहीं होनी चाहिए.

  2. FirebaseVisionDocumentTextRecognizer का इंस्टेंस पाएं:

    Java

    FirebaseVisionDocumentTextRecognizer detector = FirebaseVision.getInstance()
            .getCloudDocumentTextRecognizer();
    // Or, to provide language hints to assist with language detection:
    // See https://cloud.google.com/vision/docs/languages for supported languages
    FirebaseVisionCloudDocumentRecognizerOptions options =
            new FirebaseVisionCloudDocumentRecognizerOptions.Builder()
                    .setLanguageHints(Arrays.asList("en", "hi"))
                    .build();
    FirebaseVisionDocumentTextRecognizer detector = FirebaseVision.getInstance()
            .getCloudDocumentTextRecognizer(options);

    Kotlin

    val detector = FirebaseVision.getInstance()
            .cloudDocumentTextRecognizer
    // Or, to provide language hints to assist with language detection:
    // See https://cloud.google.com/vision/docs/languages for supported languages
    val options = FirebaseVisionCloudDocumentRecognizerOptions.Builder()
            .setLanguageHints(listOf("en", "hi"))
            .build()
    val detector = FirebaseVision.getInstance()
            .getCloudDocumentTextRecognizer(options)

  3. आखिर में, इमेज को processImage तरीके से पास करें:

    Java

    detector.processImage(myImage)
            .addOnSuccessListener(new OnSuccessListener<FirebaseVisionDocumentText>() {
                @Override
                public void onSuccess(FirebaseVisionDocumentText result) {
                    // Task completed successfully
                    // ...
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    // Task failed with an exception
                    // ...
                }
            });

    Kotlin

    detector.processImage(myImage)
            .addOnSuccessListener { firebaseVisionDocumentText ->
                // Task completed successfully
                // ...
            }
            .addOnFailureListener { e ->
                // Task failed with an exception
                // ...
            }

2. पहचाने गए टेक्स्ट के ब्लॉक से टेक्स्ट निकालना

अगर टेक्स्ट की पहचान करने की प्रोसेस पूरी हो जाती है, तो यह FirebaseVisionDocumentText ऑब्जेक्ट दिखाएगा. FirebaseVisionDocumentText ऑब्जेक्ट में, इमेज में पहचाना गया पूरा टेक्स्ट और ऑब्जेक्ट का क्रम शामिल होता है. इससे पहचाने गए दस्तावेज़ की संरचना का पता चलता है:

हर Block, Paragraph, Word, और Symbol ऑब्जेक्ट के लिए, आपको उस इलाके में पहचाना गया टेक्स्ट और उस इलाके के बाउंडिंग कोऑर्डिनेट मिल सकते हैं.

उदाहरण के लिए:

Java

String resultText = result.getText();
for (FirebaseVisionDocumentText.Block block: result.getBlocks()) {
    String blockText = block.getText();
    Float blockConfidence = block.getConfidence();
    List<RecognizedLanguage> blockRecognizedLanguages = block.getRecognizedLanguages();
    Rect blockFrame = block.getBoundingBox();
    for (FirebaseVisionDocumentText.Paragraph paragraph: block.getParagraphs()) {
        String paragraphText = paragraph.getText();
        Float paragraphConfidence = paragraph.getConfidence();
        List<RecognizedLanguage> paragraphRecognizedLanguages = paragraph.getRecognizedLanguages();
        Rect paragraphFrame = paragraph.getBoundingBox();
        for (FirebaseVisionDocumentText.Word word: paragraph.getWords()) {
            String wordText = word.getText();
            Float wordConfidence = word.getConfidence();
            List<RecognizedLanguage> wordRecognizedLanguages = word.getRecognizedLanguages();
            Rect wordFrame = word.getBoundingBox();
            for (FirebaseVisionDocumentText.Symbol symbol: word.getSymbols()) {
                String symbolText = symbol.getText();
                Float symbolConfidence = symbol.getConfidence();
                List<RecognizedLanguage> symbolRecognizedLanguages = symbol.getRecognizedLanguages();
                Rect symbolFrame = symbol.getBoundingBox();
            }
        }
    }
}

Kotlin

val resultText = result.text
for (block in result.blocks) {
    val blockText = block.text
    val blockConfidence = block.confidence
    val blockRecognizedLanguages = block.recognizedLanguages
    val blockFrame = block.boundingBox
    for (paragraph in block.paragraphs) {
        val paragraphText = paragraph.text
        val paragraphConfidence = paragraph.confidence
        val paragraphRecognizedLanguages = paragraph.recognizedLanguages
        val paragraphFrame = paragraph.boundingBox
        for (word in paragraph.words) {
            val wordText = word.text
            val wordConfidence = word.confidence
            val wordRecognizedLanguages = word.recognizedLanguages
            val wordFrame = word.boundingBox
            for (symbol in word.symbols) {
                val symbolText = symbol.text
                val symbolConfidence = symbol.confidence
                val symbolRecognizedLanguages = symbol.recognizedLanguages
                val symbolFrame = symbol.boundingBox
            }
        }
    }
}

अगले चरण