זיהוי פנים עם ערכת ML באנדרואיד

אתה יכול להשתמש בערכת ML כדי לזהות פרצופים בתמונות ובווידאו.

לפני שאתה מתחיל

  1. אם עדיין לא עשית זאת, הוסף את Firebase לפרויקט Android שלך .
  2. הוסף את התלות של ספריות אנדרואיד של ML Kit לקובץ 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'
      // If you want to detect face contours (landmark detection and classification
      // don't require this additional model):
      implementation 'com.google.firebase:firebase-ml-vision-face-model:20.0.1'
    }
    
  3. אופציונלי אך מומלץ : הגדר את האפליקציה שלך להוריד אוטומטית את דגם ה-ML למכשיר לאחר התקנת האפליקציה שלך מחנות Play.

    כדי לעשות זאת, הוסף את ההצהרה הבאה לקובץ AndroidManifest.xml של האפליקציה שלך:

    <application ...>
      ...
      <meta-data
          android:name="com.google.firebase.ml.vision.DEPENDENCIES"
          android:value="face" />
      <!-- To use multiple models: android:value="face,model2,model3" -->
    </application>
    
    אם לא תאפשר הורדות של מודלים בזמן ההתקנה, הדגם יוריד בפעם הראשונה שתפעיל את הגלאי. בקשות שתגיש לפני סיום ההורדה לא יביאו לתוצאות.

הנחיות לקלט תמונה

כדי ש-ML Kit יזהה במדויק פרצופים, תמונות קלט חייבות להכיל פרצופים המיוצגים על ידי מספיק נתוני פיקסלים. באופן כללי, כל פנים שאתה רוצה לזהות בתמונה צריך להיות לפחות 100x100 פיקסלים. אם אתה רוצה לזהות את קווי המתאר של הפנים, ערכת ML דורשת קלט ברזולוציה גבוהה יותר: כל פנים צריך להיות לפחות 200x200 פיקסלים.

אם אתה מזהה פרצופים ביישום בזמן אמת, אולי תרצה לשקול גם את הממדים הכוללים של תמונות הקלט. ניתן לעבד תמונות קטנות יותר מהר יותר, לכן כדי להפחית את זמן ההשהיה, צלם תמונות ברזולוציות נמוכות יותר (תזכור את דרישות הדיוק שלעיל) והבטח שהפנים של הנושא תופסות כמה שיותר מהתמונה. ראה גם טיפים לשיפור הביצועים בזמן אמת .

מיקוד לקוי של התמונה יכול לפגוע ברמת הדיוק. אם אינך מקבל תוצאות מקובלות, נסה לבקש מהמשתמש לצלם מחדש את התמונה.

כיוון הפנים ביחס למצלמה יכול גם להשפיע על תווי הפנים שמזהה ML Kit. ראה מושגי זיהוי פנים .

1. הגדר את גלאי הפנים

לפני שתחיל זיהוי פנים על תמונה, אם ברצונך לשנות אחת מהגדרות ברירת המחדל של גלאי הפנים, ציין את ההגדרות הללו באמצעות אובייקט FirebaseVisionFaceDetectorOptions . אתה יכול לשנות את ההגדרות הבאות:

הגדרות
מצב הופעה FAST (ברירת מחדל) | ACCURATE

העדיפו מהירות או דיוק בעת זיהוי פנים.

זיהוי ציוני דרך NO_LANDMARKS (ברירת מחדל) | ALL_LANDMARKS

האם לנסות לזהות "סימני דרך" בפנים: עיניים, אוזניים, אף, לחיים, פה וכדומה.

זיהוי קווי מתאר NO_CONTOURS (ברירת מחדל) | ALL_CONTOURS

האם לזהות את קווי המתאר של תווי הפנים. קווי מתאר מזוהים רק עבור הפנים הבולטות ביותר בתמונה.

סיווג פרצופים NO_CLASSIFICATIONS (ברירת מחדל) | ALL_CLASSIFICATIONS

האם לסווג פרצופים לקטגוריות כמו "מחייכים" ו"עיניים פקוחות" או לא.

גודל פנים מינימלי float (ברירת מחדל: 0.1f )

הגודל המינימלי, יחסית לתמונה, של פרצופים לזיהוי.

אפשר מעקב פנים false (ברירת מחדל) | true

האם להקצות לפנים מזהה, שניתן להשתמש בו כדי לעקוב אחר פרצופים על פני תמונות.

שים לב שכאשר זיהוי קווי מתאר מופעל, רק פנים אחד מזוהה, כך שמעקב פנים אינו מייצר תוצאות שימושיות. מסיבה זו, וכדי לשפר את מהירות הזיהוי, אל תאפשר גם זיהוי קווי מתאר וגם מעקב פנים.

לדוגמה:

Java

// High-accuracy landmark detection and face classification
FirebaseVisionFaceDetectorOptions highAccuracyOpts =
        new FirebaseVisionFaceDetectorOptions.Builder()
                .setPerformanceMode(FirebaseVisionFaceDetectorOptions.ACCURATE)
                .setLandmarkMode(FirebaseVisionFaceDetectorOptions.ALL_LANDMARKS)
                .setClassificationMode(FirebaseVisionFaceDetectorOptions.ALL_CLASSIFICATIONS)
                .build();

// Real-time contour detection of multiple faces
FirebaseVisionFaceDetectorOptions realTimeOpts =
        new FirebaseVisionFaceDetectorOptions.Builder()
                .setContourMode(FirebaseVisionFaceDetectorOptions.ALL_CONTOURS)
                .build();

Kotlin+KTX

// High-accuracy landmark detection and face classification
val highAccuracyOpts = FirebaseVisionFaceDetectorOptions.Builder()
        .setPerformanceMode(FirebaseVisionFaceDetectorOptions.ACCURATE)
        .setLandmarkMode(FirebaseVisionFaceDetectorOptions.ALL_LANDMARKS)
        .setClassificationMode(FirebaseVisionFaceDetectorOptions.ALL_CLASSIFICATIONS)
        .build()

// Real-time contour detection of multiple faces
val realTimeOpts = FirebaseVisionFaceDetectorOptions.Builder()
        .setContourMode(FirebaseVisionFaceDetectorOptions.ALL_CONTOURS)
        .build()

2. הפעל את גלאי הפנים

כדי לזהות פרצופים בתמונה, צור אובייקט FirebaseVisionImage מ- Bitmap , media.Image , ByteBuffer , מערך בתים או קובץ במכשיר. לאחר מכן, העבר את אובייקט FirebaseVisionImage לשיטת detectInImage של FirebaseVisionFaceDetector .

לזיהוי פנים, עליך להשתמש בתמונה במידות של לפחות 480x360 פיקסלים. אם אתה מזהה פרצופים בזמן אמת, לכידת פריימים ברזולוציה מינימלית זו יכולה לעזור להפחית את זמן האחזור.

  1. צור אובייקט FirebaseVisionImage מהתמונה שלך.

    • כדי ליצור אובייקט FirebaseVisionImage מאובייקט media.Image , כגון בעת ​​לכידת תמונה ממצלמה של מכשיר, העבר את אובייקט media.Image וסיבוב התמונה ל- FirebaseVisionImage.fromMediaImage() .

      אם אתה משתמש בספריית CameraX , המחלקות OnImageCapturedListener ו- ImageAnalysis.Analyzer מחשבות את ערך הסיבוב עבורך, אז אתה רק צריך להמיר את הסיבוב לאחד מקבועי ROTATION_ של ML Kit לפני שתקרא 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+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)
    • כדי ליצור אובייקט FirebaseVisionImage מ-URI של קובץ, העבר את ההקשר של האפליקציה ו-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()
      }
    • כדי ליצור אובייקט FirebaseVisionImage מ- ByteBuffer או מערך בתים, חשב תחילה את סיבוב התמונה כמתואר לעיל עבור קלט 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)
    • כדי ליצור אובייקט FirebaseVisionImage מאובייקט Bitmap :

      Java

      FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);

      Kotlin+KTX

      val image = FirebaseVisionImage.fromBitmap(bitmap)
      התמונה המיוצגת על ידי אובייקט Bitmap חייבת להיות זקופה, ללא צורך בסיבוב נוסף.
  2. קבל מופע של FirebaseVisionFaceDetector :

    Java

    FirebaseVisionFaceDetector detector = FirebaseVision.getInstance()
            .getVisionFaceDetector(options);

    Kotlin+KTX

    val detector = FirebaseVision.getInstance()
            .getVisionFaceDetector(options)
  3. לבסוף, העבירו את התמונה לשיטת detectInImage :

    Java

    Task<List<FirebaseVisionFace>> result =
            detector.detectInImage(image)
                    .addOnSuccessListener(
                            new OnSuccessListener<List<FirebaseVisionFace>>() {
                                @Override
                                public void onSuccess(List<FirebaseVisionFace> faces) {
                                    // 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 { faces ->
                // Task completed successfully
                // ...
            }
            .addOnFailureListener { e ->
                // Task failed with an exception
                // ...
            }

3. קבל מידע על פרצופים שזוהו

אם פעולת זיהוי הפנים תצליח, רשימה של אובייקטי FirebaseVisionFace תועבר למאזין ההצלחה. כל אובייקט FirebaseVisionFace מייצג פנים שזוהה בתמונה. עבור כל פנים, אתה יכול לקבל את הקואורדינטות התוחמות שלו בתמונת הקלט, כמו גם כל מידע אחר שהגדרת את גלאי הפנים למצוא. לדוגמה:

Java

for (FirebaseVisionFace face : faces) {
    Rect bounds = face.getBoundingBox();
    float rotY = face.getHeadEulerAngleY();  // Head is rotated to the right rotY degrees
    float rotZ = face.getHeadEulerAngleZ();  // Head is tilted sideways rotZ degrees

    // If landmark detection was enabled (mouth, ears, eyes, cheeks, and
    // nose available):
    FirebaseVisionFaceLandmark leftEar = face.getLandmark(FirebaseVisionFaceLandmark.LEFT_EAR);
    if (leftEar != null) {
        FirebaseVisionPoint leftEarPos = leftEar.getPosition();
    }

    // If contour detection was enabled:
    List<FirebaseVisionPoint> leftEyeContour =
            face.getContour(FirebaseVisionFaceContour.LEFT_EYE).getPoints();
    List<FirebaseVisionPoint> upperLipBottomContour =
            face.getContour(FirebaseVisionFaceContour.UPPER_LIP_BOTTOM).getPoints();

    // If classification was enabled:
    if (face.getSmilingProbability() != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) {
        float smileProb = face.getSmilingProbability();
    }
    if (face.getRightEyeOpenProbability() != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) {
        float rightEyeOpenProb = face.getRightEyeOpenProbability();
    }

    // If face tracking was enabled:
    if (face.getTrackingId() != FirebaseVisionFace.INVALID_ID) {
        int id = face.getTrackingId();
    }
}

Kotlin+KTX

for (face in faces) {
    val bounds = face.boundingBox
    val rotY = face.headEulerAngleY // Head is rotated to the right rotY degrees
    val rotZ = face.headEulerAngleZ // Head is tilted sideways rotZ degrees

    // If landmark detection was enabled (mouth, ears, eyes, cheeks, and
    // nose available):
    val leftEar = face.getLandmark(FirebaseVisionFaceLandmark.LEFT_EAR)
    leftEar?.let {
        val leftEarPos = leftEar.position
    }

    // If contour detection was enabled:
    val leftEyeContour = face.getContour(FirebaseVisionFaceContour.LEFT_EYE).points
    val upperLipBottomContour = face.getContour(FirebaseVisionFaceContour.UPPER_LIP_BOTTOM).points

    // If classification was enabled:
    if (face.smilingProbability != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) {
        val smileProb = face.smilingProbability
    }
    if (face.rightEyeOpenProbability != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) {
        val rightEyeOpenProb = face.rightEyeOpenProbability
    }

    // If face tracking was enabled:
    if (face.trackingId != FirebaseVisionFace.INVALID_ID) {
        val id = face.trackingId
    }
}

דוגמה לקווי מתאר פנים

כאשר הפעלת זיהוי קווי מתאר פנים, תקבל רשימה של נקודות עבור כל תכונת פנים שזוהתה. נקודות אלו מייצגות את צורת התכונה. עיין בסקירת מושגי זיהוי הפנים לפרטים על אופן ייצוג קווי המתאר.

התמונה הבאה ממחישה כיצד נקודות אלו ממפות לפנים (לחץ על התמונה להגדלה):

זיהוי פנים בזמן אמת

אם ברצונך להשתמש בזיהוי פנים ביישום בזמן אמת, עקוב אחר ההנחיות הבאות כדי להשיג את קצבי המסגרות הטובים ביותר:

  • הגדר את גלאי הפנים כך שישתמש בזיהוי קווי מתאר פנים או בסיווג ובזיהוי ציוני דרך, אך לא בשניהם:

    זיהוי קווי מתאר
    זיהוי ציוני דרך
    מִיוּן
    זיהוי וסיווג ציוני דרך
    זיהוי קווי מתאר וזיהוי ציוני דרך
    זיהוי וסיווג קווי מתאר
    זיהוי קווי מתאר, זיהוי ציוני דרך וסיווג

  • אפשר מצב FAST (מופעל כברירת מחדל).

  • שקול לצלם תמונות ברזולוציה נמוכה יותר. עם זאת, זכור גם את דרישות ממדי התמונה של ממשק API זה.

  • מצערת קוראת לגלאי. אם מסגרת וידאו חדשה הופכת לזמינה בזמן שהגלאי פועל, שחרר את המסגרת.
  • אם אתה משתמש בפלט של הגלאי כדי לשכב גרפיקה על תמונת הקלט, תחילה קבל את התוצאה מ-ML Kit, ולאחר מכן עבד את התמונה ואת שכבת העל בצעד אחד. על ידי כך, אתה מעבד למשטח התצוגה רק פעם אחת עבור כל מסגרת קלט.
  • אם אתה משתמש בממשק ה-API של Camera2, צלם תמונות בפורמט ImageFormat.YUV_420_888 .

    אם אתה משתמש ב-Camera API הישן יותר, צלם תמונות בפורמט ImageFormat.NV21 .