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

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

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

  1. अगर आपने पहले से ऐसा नहीं किया है, तो अपने Android प्रोजेक्ट में Firebase जोड़ें.
  2. अपनी मॉड्यूल (ऐप्लिकेशन-लेवल) Gradle फ़ाइल (आम तौर पर <project>/<app-module>/build.gradle.kts या <project>/<app-module>/build.gradle) में, Android के लिए Firebase ML विज़न लाइब्रेरी की डिपेंडेंसी जोड़ें. हमारा सुझाव है कि लाइब्रेरी के वर्शन को कंट्रोल करने के लिए, Firebase Android BoM का इस्तेमाल करें.
    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:33.10.0"))
    
        // Add the dependency for the Firebase ML Vision library
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation 'com.google.firebase:firebase-ml-vision'
    }

    Firebase Android BoM का इस्तेमाल करने पर, आपका ऐप्लिकेशन हमेशा Firebase Android लाइब्रेरी के काम करने वाले वर्शन का इस्तेमाल करेगा.

    अगर Firebase BoM का इस्तेमाल नहीं किया जाता है, तो आपको हर Firebase लाइब्रेरी के वर्शन की जानकारी, उसकी डिपेंडेंसी लाइन में देनी होगी.

    ध्यान दें कि अगर आपके ऐप्लिकेशन में एक से ज़्यादा Firebase लाइब्रेरी का इस्तेमाल किया जाता है, तो हमारा सुझाव है कि आप लाइब्रेरी के वर्शन मैनेज करने के लिए BoM का इस्तेमाल करें. इससे यह पक्का होता है कि सभी वर्शन काम करते हों.

    dependencies {
        // Add the dependency for the Firebase ML Vision library
        // When NOT using the BoM, you must specify versions in Firebase library dependencies
        implementation 'com.google.firebase:firebase-ml-vision:24.1.0'
    }
    क्या आपको Kotlin के लिए कोई लाइब्रेरी मॉड्यूल चाहिए? अक्टूबर 2023 (Firebase BoM 32.5.0) से, Kotlin और Java, दोनों डेवलपर मुख्य लाइब्रेरी मॉड्यूल का इस्तेमाल कर सकते हैं. ज़्यादा जानकारी के लिए, इस पहल के बारे में अक्सर पूछे जाने वाले सवाल देखें.
  3. अगर आपने अब तक अपने प्रोजेक्ट के लिए, क्लाउड पर काम करने वाले एपीआई चालू नहीं किए हैं, तो अभी ऐसा करें:

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

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

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

अब आप इमेज में टेक्स्ट की पहचान करने के लिए तैयार हैं.

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

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

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

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


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

किसी इमेज में मौजूद टेक्स्ट की पहचान करने के लिए, टेक्स्ट रिकग्निज़र को यहां बताए गए तरीके से चलाएं.

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

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

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

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

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

      KotlinJava
      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 Vision API
                  // ...
              }
          }
      }
      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 Vision API
              // ...
          }
      }

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

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

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

      KotlinJava
      val image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation)
      FirebaseVisionImage image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation);
    • फ़ाइल यूआरआई से FirebaseVisionImage ऑब्जेक्ट बनाने के लिए, ऐप्लिकेशन कॉन्टेक्स्ट और फ़ाइल यूआरआई को FirebaseVisionImage.fromFilePath() में पास करें. यह तब काम आता है, जब उपयोगकर्ता को अपने गैलरी ऐप्लिकेशन से कोई इमेज चुनने के लिए कहने के लिए, ACTION_GET_CONTENT इंटेंट का इस्तेमाल किया जाता है.
      KotlinJava
      val image: FirebaseVisionImage
      try {
          image = FirebaseVisionImage.fromFilePath(context, uri)
      } catch (e: IOException) {
          e.printStackTrace()
      }
      FirebaseVisionImage image;
      try {
          image = FirebaseVisionImage.fromFilePath(context, uri);
      } catch (IOException e) {
          e.printStackTrace();
      }
    • ByteBuffer या बाइट कलेक्शन से FirebaseVisionImage ऑब्जेक्ट बनाने के लिए, सबसे पहले media.Image इनपुट के लिए ऊपर बताए गए तरीके से इमेज के रोटेशन का हिसाब लगाएं.

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

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

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

      KotlinJava
      val image = FirebaseVisionImage.fromByteBuffer(buffer, metadata)
      // Or: val image = FirebaseVisionImage.fromByteArray(byteArray, metadata)
      FirebaseVisionImage image = FirebaseVisionImage.fromByteBuffer(buffer, metadata);
      // Or: FirebaseVisionImage image = FirebaseVisionImage.fromByteArray(byteArray, metadata);
    • Bitmap ऑब्जेक्ट से FirebaseVisionImage ऑब्जेक्ट बनाने के लिए:
      KotlinJava
      val image = FirebaseVisionImage.fromBitmap(bitmap)
      FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);
      Bitmap ऑब्जेक्ट से दिखाई गई इमेज, सीधी होनी चाहिए. इसे किसी और दिशा में घुमाने की ज़रूरत नहीं है.

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

    KotlinJava
    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()
    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();
  3. आखिर में, इमेज को processImage तरीके में पास करें:

    KotlinJava
    val result = detector.processImage(image)
        .addOnSuccessListener { firebaseVisionText ->
            // Task completed successfully
            // ...
        }
        .addOnFailureListener { e ->
            // Task failed with an exception
            // ...
        }
    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
                                    // ...
                                }
                            });

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

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

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

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

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

KotlinJava
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
        }
    }
}
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();
        }
    }
}

अगले चरण


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

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

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

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

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

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

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

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

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

      KotlinJava
      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 Vision API
                  // ...
              }
          }
      }
      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 Vision API
              // ...
          }
      }

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

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

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

      KotlinJava
      val image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation)
      FirebaseVisionImage image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation);
    • फ़ाइल यूआरआई से FirebaseVisionImage ऑब्जेक्ट बनाने के लिए, ऐप्लिकेशन कॉन्टेक्स्ट और फ़ाइल यूआरआई को FirebaseVisionImage.fromFilePath() में पास करें. यह तब काम आता है, जब उपयोगकर्ता को अपने गैलरी ऐप्लिकेशन से कोई इमेज चुनने के लिए कहने के लिए, ACTION_GET_CONTENT इंटेंट का इस्तेमाल किया जाता है.
      KotlinJava
      val image: FirebaseVisionImage
      try {
          image = FirebaseVisionImage.fromFilePath(context, uri)
      } catch (e: IOException) {
          e.printStackTrace()
      }
      FirebaseVisionImage image;
      try {
          image = FirebaseVisionImage.fromFilePath(context, uri);
      } catch (IOException e) {
          e.printStackTrace();
      }
    • ByteBuffer या बाइट कलेक्शन से FirebaseVisionImage ऑब्जेक्ट बनाने के लिए, सबसे पहले media.Image इनपुट के लिए ऊपर बताए गए तरीके से इमेज के रोटेशन का हिसाब लगाएं.

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

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

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

      KotlinJava
      val image = FirebaseVisionImage.fromByteBuffer(buffer, metadata)
      // Or: val image = FirebaseVisionImage.fromByteArray(byteArray, metadata)
      FirebaseVisionImage image = FirebaseVisionImage.fromByteBuffer(buffer, metadata);
      // Or: FirebaseVisionImage image = FirebaseVisionImage.fromByteArray(byteArray, metadata);
    • Bitmap ऑब्जेक्ट से FirebaseVisionImage ऑब्जेक्ट बनाने के लिए:
      KotlinJava
      val image = FirebaseVisionImage.fromBitmap(bitmap)
      FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);
      Bitmap ऑब्जेक्ट से दिखाई गई इमेज, सीधी होनी चाहिए. इसे किसी और दिशा में घुमाने की ज़रूरत नहीं है.

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

    KotlinJava

    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)

    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);

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

    KotlinJava
    detector.processImage(myImage)
        .addOnSuccessListener { firebaseVisionDocumentText ->
            // Task completed successfully
            // ...
        }
        .addOnFailureListener { e ->
            // Task failed with an exception
            // ...
        }
    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
                    // ...
                }
            });

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

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

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

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

KotlinJava
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
            }
        }
    }
}
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();
            }
        }
    }
}

अगले चरण

Firebase ML lets you add powerful machine learning features to your app with ready-to-use APIs and support for custom model deployment.

Feb 28, 2025 को अपडेट किया गया

असल दुनिया में होने वाली समस्याएं हल करने के लिए, अपने ऐप्लिकेशन में मशीन लर्निंग का इस्तेमाल करें.

Feb 28, 2025 को अपडेट किया गया