एंड्रॉइड पर एमएल किट के साथ लैंडमार्क पहचानें

आप किसी छवि में प्रसिद्ध स्थलों को पहचानने के लिए एमएल किट का उपयोग कर सकते हैं।

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

  1. यदि आपने पहले से नहीं किया है, तो अपने एंड्रॉइड प्रोजेक्ट में फायरबेस जोड़ें
  2. अपने मॉड्यूल (ऐप-स्तर) ग्रैडल फ़ाइल (आमतौर पर 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. यदि आपने पहले से ही अपने प्रोजेक्ट के लिए क्लाउड-आधारित एपीआई सक्षम नहीं किया है, तो अभी करें:

    1. फायरबेस कंसोल का एमएल किट एपीआई पेज खोलें।
    2. यदि आपने पहले से ही अपने प्रोजेक्ट को ब्लेज़ मूल्य निर्धारण योजना में अपग्रेड नहीं किया है, तो ऐसा करने के लिए अपग्रेड पर क्लिक करें। (आपको केवल तभी अपग्रेड करने के लिए प्रेरित किया जाएगा यदि आपका प्रोजेक्ट ब्लेज़ योजना पर नहीं है।)

      केवल ब्लेज़-स्तरीय प्रोजेक्ट ही क्लाउड-आधारित एपीआई का उपयोग कर सकते हैं।

    3. यदि क्लाउड-आधारित एपीआई पहले से सक्षम नहीं हैं, तो क्लाउड-आधारित एपीआई सक्षम करें पर क्लिक करें।

लैंडमार्क डिटेक्टर कॉन्फ़िगर करें

डिफ़ॉल्ट रूप से, क्लाउड डिटेक्टर मॉडल के STABLE संस्करण का उपयोग करता है और 10 परिणाम तक लौटाता है। यदि आप इनमें से किसी भी सेटिंग को बदलना चाहते हैं, तो उन्हें FirebaseVisionCloudDetectorOptions ऑब्जेक्ट के साथ निर्दिष्ट करें।

उदाहरण के लिए, दोनों डिफ़ॉल्ट सेटिंग्स को बदलने के लिए, निम्न उदाहरण के अनुसार एक FirebaseVisionCloudDetectorOptions ऑब्जेक्ट बनाएं:

Java

FirebaseVisionCloudDetectorOptions options =
        new FirebaseVisionCloudDetectorOptions.Builder()
                .setModelType(FirebaseVisionCloudDetectorOptions.LATEST_MODEL)
                .setMaxResults(15)
                .build();

Kotlin+KTX

val options = FirebaseVisionCloudDetectorOptions.Builder()
        .setModelType(FirebaseVisionCloudDetectorOptions.LATEST_MODEL)
        .setMaxResults(15)
        .build()

डिफ़ॉल्ट सेटिंग्स का उपयोग करने के लिए, आप अगले चरण में FirebaseVisionCloudDetectorOptions.DEFAULT DEFAULT का उपयोग कर सकते हैं।

लैंडमार्क डिटेक्टर चलाएँ

किसी छवि में स्थलों को पहचानने के लिए, Bitmap , media.Image , ByteBuffer , बाइट सरणी, या डिवाइस पर एक फ़ाइल से एक FirebaseVisionImage ऑब्जेक्ट बनाएं। फिर, FirebaseVisionImage ऑब्जेक्ट को FirebaseVisionCloudLandmarkDetector के detectInImage विधि में पास करें।

  1. अपनी छवि से एक FirebaseVisionImage ऑब्जेक्ट बनाएं।

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

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

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

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

      Java

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

      Kotlin+KTX

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

      Java

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

      Kotlin+KTX

      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+KTX

      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+KTX

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

      Java

      FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);

      Kotlin+KTX

      val image = FirebaseVisionImage.fromBitmap(bitmap)
      Bitmap ऑब्जेक्ट द्वारा दर्शाई गई छवि सीधी होनी चाहिए, जिसमें किसी अतिरिक्त घुमाव की आवश्यकता नहीं है।

  2. FirebaseVisionCloudLandmarkDetector का एक उदाहरण प्राप्त करें:

    Java

    FirebaseVisionCloudLandmarkDetector detector = FirebaseVision.getInstance()
            .getVisionCloudLandmarkDetector();
    // Or, to change the default settings:
    // FirebaseVisionCloudLandmarkDetector detector = FirebaseVision.getInstance()
    //         .getVisionCloudLandmarkDetector(options);

    Kotlin+KTX

    val detector = FirebaseVision.getInstance()
            .visionCloudLandmarkDetector
    // Or, to change the default settings:
    // val detector = FirebaseVision.getInstance()
    //         .getVisionCloudLandmarkDetector(options)
  3. अंत में, छवि को detectInImage विधि में पास करें:

    Java

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

    Kotlin+KTX

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

मान्यता प्राप्त स्थलों के बारे में जानकारी प्राप्त करें

यदि लैंडमार्क पहचान ऑपरेशन सफल होता है, तो FirebaseVisionCloudLandmark ऑब्जेक्ट की एक सूची सफल श्रोता को भेज दी जाएगी। प्रत्येक FirebaseVisionCloudLandmark ऑब्जेक्ट एक लैंडमार्क का प्रतिनिधित्व करता है जिसे छवि में पहचाना गया था। प्रत्येक लैंडमार्क के लिए, आप इनपुट छवि में इसके बाउंडिंग निर्देशांक, लैंडमार्क का नाम, इसका अक्षांश और देशांतर, इसकी नॉलेज ग्राफ इकाई आईडी (यदि उपलब्ध हो), और मैच का आत्मविश्वास स्कोर प्राप्त कर सकते हैं। उदाहरण के लिए:

Java

for (FirebaseVisionCloudLandmark landmark: firebaseVisionCloudLandmarks) {

    Rect bounds = landmark.getBoundingBox();
    String landmarkName = landmark.getLandmark();
    String entityId = landmark.getEntityId();
    float confidence = landmark.getConfidence();

    // Multiple locations are possible, e.g., the location of the depicted
    // landmark and the location the picture was taken.
    for (FirebaseVisionLatLng loc: landmark.getLocations()) {
        double latitude = loc.getLatitude();
        double longitude = loc.getLongitude();
    }
}

Kotlin+KTX

for (landmark in firebaseVisionCloudLandmarks) {

    val bounds = landmark.boundingBox
    val landmarkName = landmark.landmark
    val entityId = landmark.entityId
    val confidence = landmark.confidence

    // Multiple locations are possible, e.g., the location of the depicted
    // landmark and the location the picture was taken.
    for (loc in landmark.locations) {
        val latitude = loc.latitude
        val longitude = loc.longitude
    }
}

अगले कदम