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

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

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

  1. अगर आपने अब तक ऐसा नहीं किया है, तो अपने Android प्रोजेक्ट में Firebase जोड़ें.
  2. आपके मॉड्यूल (ऐप्लिकेशन-लेवल) की Gradle फ़ाइल में (आम तौर पर <project>/<app-module>/build.gradle.kts या <project>/<app-module>/build.gradle), Android के लिए, Firebase ML Vision लाइब्रेरी के लिए डिपेंडेंसी जोड़ें. हमारा सुझाव है कि Firebase Android बीओएम लाइब्रेरी के वर्शन को कंट्रोल करने के लिए.
    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:33.1.2"))
    
        // 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 लाइब्रेरी के साथ काम करने वाले वर्शन का इस्तेमाल करेगा.

    (वैकल्पिक) BoM का इस्तेमाल किए बिना Firebase लाइब्रेरी डिपेंडेंसी जोड़ें

    अगर आप 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 ML खोलें Firebase कंसोल का एपीआई पेज.
    2. अगर आपने पहले से अपने प्रोजेक्ट को Blaze प्राइसिंग प्लान में अपग्रेड नहीं किया है, तो ऐसा करने के लिए अपग्रेड करें. (आपको अपग्रेड करने के लिए तभी कहा जाएगा, जब प्रोजेक्ट ब्लेज़ प्लान में नहीं है.)

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

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

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

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

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

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

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


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

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

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

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

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

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

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

      Kotlin+KTX

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

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

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

      Kotlin+KTX

      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
      }

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

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

      Kotlin+KTX

      val image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation)

      Java

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

      Kotlin+KTX

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

      Java

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

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

      Kotlin+KTX

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

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

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

      Kotlin+KTX

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

      Java

      FirebaseVisionImage image = FirebaseVisionImage.fromByteBuffer(buffer, metadata);
      // Or: FirebaseVisionImage image = FirebaseVisionImage.fromByteArray(byteArray, metadata);
    • किसीFirebaseVisionImage Bitmap ऑब्जेक्ट:

      Kotlin+KTX

      val image = FirebaseVisionImage.fromBitmap(bitmap)

      Java

      FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);
      Bitmap ऑब्जेक्ट के ज़रिए दिखाई जाने वाली इमेज में सीधा होना चाहिए, इसके लिए किसी अतिरिक्त रोटेशन की आवश्यकता नहीं होगी.

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

    Kotlin+KTX

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

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

    Kotlin+KTX

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

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

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

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

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

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

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

Kotlin+KTX

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

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

अगले चरण

  • Cloud API का इस्तेमाल करने वाले ऐप्लिकेशन को प्रोडक्शन में डिप्लॉय करने से पहले, आपको Google Ads के ट्रैफ़िक को रोकने और उसे कम करने के लिए, अनधिकृत एपीआई ऐक्सेस का असर.

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

किसी दस्तावेज़ के टेक्स्ट की पहचान करने के लिए, दस्तावेज़ पाठ पहचानकर्ता जैसा कि नीचे बताया गया है.

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

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

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

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

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

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

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

      Kotlin+KTX

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

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

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

      Kotlin+KTX

      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
      }

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

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

      Kotlin+KTX

      val image = FirebaseVisionImage.fromMediaImage(mediaImage, rotation)

      Java

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

      Kotlin+KTX

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

      Java

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

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

      Kotlin+KTX

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

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

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

      Kotlin+KTX

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

      Java

      FirebaseVisionImage image = FirebaseVisionImage.fromByteBuffer(buffer, metadata);
      // Or: FirebaseVisionImage image = FirebaseVisionImage.fromByteArray(byteArray, metadata);
    • किसीFirebaseVisionImage Bitmap ऑब्जेक्ट:

      Kotlin+KTX

      val image = FirebaseVisionImage.fromBitmap(bitmap)

      Java

      FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);
      Bitmap ऑब्जेक्ट के ज़रिए दिखाई जाने वाली इमेज में सीधा होना चाहिए, इसके लिए किसी अतिरिक्त रोटेशन की आवश्यकता नहीं होगी.

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

    Kotlin+KTX

    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)

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

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

    Kotlin+KTX

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

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

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

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

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

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

Kotlin+KTX

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

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

अगले चरण

  • Cloud API का इस्तेमाल करने वाले ऐप्लिकेशन को प्रोडक्शन में डिप्लॉय करने से पहले, आपको Google Ads के ट्रैफ़िक को रोकने और उसे कम करने के लिए, अनधिकृत एपीआई ऐक्सेस का असर.