אתם יכולים להשתמש ב-ML Kit כדי להוסיף בקלות תכונות של פילוח נושאים לאפליקציה.
Feature | פרטים |
---|---|
שם ה-Sdk | play-services-mlkit-subject-segmentation |
הטמעה | לא נכלל בחבילה: הורדה דינמית של המודל מתבצעת באמצעות Google Play Services. |
ההשפעה של גודל האפליקציה | הגדלה של כ-200KB. |
זמן האתחול | יכול להיות שהמשתמשים יצטרכו להמתין להורדת המודל לפני השימוש הראשון. |
רוצה לנסות?
- מומלץ לשחק עם האפליקציה לדוגמה כדי .
לפני שמתחילים
- בקובץ
build.gradle
ברמת הפרויקט, חשוב לכלול את מאגר Maven של Google בקטעbuildscript
וגם בקטעallprojects
. - מוסיפים את התלות של ספריית הפילוח של נושאי ML Kit לקובץ GRid ברמת האפליקציה של המודול, שהוא בדרך כלל
app/build.gradle
:
dependencies {
implementation 'com.google.android.gms:play-services-mlkit-subject-segmentation:16.0.0-beta1'
}
כפי שצוין למעלה, המודל מסופק על ידי Google Play Services.
אפשר להגדיר שהאפליקציה תוריד את המודל באופן אוטומטי למכשיר
אחרי שהאפליקציה מותקנת מחנות Play. כדי לעשות את זה, צריך להוסיף את הפרטים הבאים:
הצהרה לקובץ AndroidManifest.xml
של האפליקציה:
<application ...>
...
<meta-data
android:name="com.google.mlkit.vision.DEPENDENCIES"
android:value="subject_segment" >
<!-- To use multiple models: android:value="subject_segment,model2,model3" -->
</application>
תוכלו גם לבדוק באופן מפורש את זמינות המודל ולבקש הורדה דרך Google Play Services באמצעות ModuleInstallClient API.
אם לא מפעילים הורדות של מודלים בזמן ההתקנה או מבקשים הורדה מפורשת מתבצעת הורדה של המודל בפעם הראשונה שתפעילו את הפילוח. הבקשות שלכם לפני שההורדה הסתיימה, לא נמצאו תוצאות.
1. הכנת תמונת הקלט
כדי לבצע פילוח על תמונה, צריך ליצור אובייקט InputImage
מ-Bitmap
, media.Image
, ByteBuffer
, ממערך בייטים או מקובץ
במכשיר.
אפשר ליצור InputImage
ממקורות שונים, מוסבר על כל אחד מהם בהמשך.
באמצעות media.Image
כדי ליצור InputImage
מאובייקט media.Image
, למשל כשמצלמים תמונה
המצלמה של המכשיר, מעבירים את האובייקט media.Image
ואת
ל-InputImage.fromMediaImage()
.
אם משתמשים
ספריית CameraX, OnImageCapturedListener
ImageAnalysis.Analyzer
מחלקות מחשבים את ערך הסבב
עבורך.
private class YourImageAnalyzer : ImageAnalysis.Analyzer { override fun analyze(imageProxy: ImageProxy) { val mediaImage = imageProxy.image if (mediaImage != null) { val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees) // Pass image to an ML Kit Vision API // ... } } }
private class YourAnalyzer implements ImageAnalysis.Analyzer { @Override public void analyze(ImageProxy imageProxy) { Image mediaImage = imageProxy.getImage(); if (mediaImage != null) { InputImage image = InputImage.fromMediaImage(mediaImage, imageProxy.getImageInfo().getRotationDegrees()); // Pass image to an ML Kit Vision API // ... } } }
אם לא משתמשים בספריית מצלמה שמאפשרת לקבוע את כיוון הסיבוב של התמונה, הוא יכול לחשב אותו על סמך זווית הסיבוב של המכשיר וכיוון המצלמה החיישן במכשיר:
private val ORIENTATIONS = SparseIntArray() init { ORIENTATIONS.append(Surface.ROTATION_0, 0) ORIENTATIONS.append(Surface.ROTATION_90, 90) ORIENTATIONS.append(Surface.ROTATION_180, 180) ORIENTATIONS.append(Surface.ROTATION_270, 270) } /** * 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, isFrontFacing: Boolean): 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) // Get the device's sensor orientation. val cameraManager = activity.getSystemService(CAMERA_SERVICE) as CameraManager val sensorOrientation = cameraManager .getCameraCharacteristics(cameraId) .get(CameraCharacteristics.SENSOR_ORIENTATION)!! if (isFrontFacing) { rotationCompensation = (sensorOrientation + rotationCompensation) % 360 } else { // back-facing rotationCompensation = (sensorOrientation - rotationCompensation + 360) % 360 } return rotationCompensation }
private static final SparseIntArray ORIENTATIONS = new SparseIntArray(); static { ORIENTATIONS.append(Surface.ROTATION_0, 0); ORIENTATIONS.append(Surface.ROTATION_90, 90); ORIENTATIONS.append(Surface.ROTATION_180, 180); ORIENTATIONS.append(Surface.ROTATION_270, 270); } /** * 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, boolean isFrontFacing) 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); // Get the device's sensor orientation. CameraManager cameraManager = (CameraManager) activity.getSystemService(CAMERA_SERVICE); int sensorOrientation = cameraManager .getCameraCharacteristics(cameraId) .get(CameraCharacteristics.SENSOR_ORIENTATION); if (isFrontFacing) { rotationCompensation = (sensorOrientation + rotationCompensation) % 360; } else { // back-facing rotationCompensation = (sensorOrientation - rotationCompensation + 360) % 360; } return rotationCompensation; }
לאחר מכן, מעבירים את האובייקט media.Image
הערך של מעלה הסיבוב ל-InputImage.fromMediaImage()
:
val image = InputImage.fromMediaImage(mediaImage, rotation)
InputImage image = InputImage.fromMediaImage(mediaImage, rotation);
שימוש ב-URI של קובץ
כדי ליצור InputImage
מ-URI של קובץ, מעבירים את ההקשר של האפליקציה ואת ה-URI של הקובץ
InputImage.fromFilePath()
זה שימושי כאשר
צריך להשתמש ב-Intent ACTION_GET_CONTENT
כדי לבקש מהמשתמש לבחור
תמונה מאפליקציית הגלריה.
val image: InputImage try { image = InputImage.fromFilePath(context, uri) } catch (e: IOException) { e.printStackTrace() }
InputImage image;
try {
image = InputImage.fromFilePath(context, uri);
} catch (IOException e) {
e.printStackTrace();
}
שימוש ב-ByteBuffer
או ב-ByteArray
כדי ליצור InputImage
מ-ByteBuffer
או מ-ByteArray
, קודם צריך לחשב את התמונה
מעלות סיבוב כפי שתואר קודם לכן עבור קלט media.Image
.
אחר כך יוצרים את האובייקט InputImage
עם מאגר נתונים זמני או מערך, יחד עם
גובה, רוחב, פורמט קידוד צבעים ומידת סיבוב:
val image = InputImage.fromByteBuffer( byteBuffer, /* image width */ 480, /* image height */ 360, rotationDegrees, InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12 ) // Or: val image = InputImage.fromByteArray( byteArray, /* image width */ 480, /* image height */ 360, rotationDegrees, InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12 )
InputImage image = InputImage.fromByteBuffer(byteBuffer, /* image width */ 480, /* image height */ 360, rotationDegrees, InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12 ); // Or: InputImage image = InputImage.fromByteArray( byteArray, /* image width */480, /* image height */360, rotation, InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12 );
באמצעות Bitmap
כדי ליצור InputImage
מאובייקט Bitmap
, צריך ליצור את ההצהרה הבאה:
val image = InputImage.fromBitmap(bitmap, 0)
InputImage image = InputImage.fromBitmap(bitmap, rotationDegree);
התמונה מיוצגת על ידי אובייקט Bitmap
ביחד עם מעלות סיבוב.
2. יצירת מכונה של SubjectSegmenter
הגדרת אפשרויות הפילוח
כדי לפלח את התמונה, קודם צריך ליצור מופע של SubjectSegmenterOptions
בתור
עוקבים:
val options = SubjectSegmenterOptions.Builder() // enable options .build()
SubjectSegmenterOptions options = new SubjectSegmenterOptions.Builder() // enable options .build();
אלו הפרטים של כל אפשרות:
מסכת אבטחה קדמית
מסכת הסמך בחזית מאפשרת להבחין בין הנושא הקדמי את הרקע.
אפשר להתקשר אל enableForegroundConfidenceMask()
באפשרויות כדי לאחזר מאוחר יותר
את המסכה הקדמית באמצעות קריאה ל-getForegroundMask()
אובייקט SubjectSegmentationResult
הוחזר אחרי עיבוד התמונה.
val options = SubjectSegmenterOptions.Builder() .enableForegroundConfidenceMask() .build()
SubjectSegmenterOptions options = new SubjectSegmenterOptions.Builder() .enableForegroundConfidenceMask() .build();
מפת סיביות מקדימה
באופן דומה, אפשר לקבל גם מפת סיביות של הנושא הקדמי.
אפשר להתקשר אל enableForegroundBitmap()
באפשרויות כדי לאחזר מאוחר יותר
למפת הסיביות בחזית באמצעות קריאה ל-getForegroundBitmap()
אובייקט SubjectSegmentationResult
הוחזר אחרי עיבוד התמונה.
val options = SubjectSegmenterOptions.Builder() .enableForegroundBitmap() .build()
SubjectSegmenterOptions options = new SubjectSegmenterOptions.Builder() .enableForegroundBitmap() .build();
מסכת ביטחון מרובת נושאים
כמו באפשרויות לחזית, אפשר להשתמש ב-SubjectResultOptions
כדי להפעיל
את מסכת הסמך לכל נושא שפועל בחזית באופן הבא:
val subjectResultOptions = SubjectSegmenterOptions.SubjectResultOptions.Builder() .enableConfidenceMask() .build() val options = SubjectSegmenterOptions.Builder() .enableMultipleSubjects(subjectResultOptions) .build()
SubjectResultOptions subjectResultOptions = new SubjectSegmenterOptions.SubjectResultOptions.Builder() .enableConfidenceMask() .build() SubjectSegmenterOptions options = new SubjectSegmenterOptions.Builder() .enableMultipleSubjects(subjectResultOptions) .build()
מפת סיביות של נושאים מרובים
באופן דומה, אפשר להפעיל את מפת הסיביות לכל נושא:
val subjectResultOptions = SubjectSegmenterOptions.SubjectResultOptions.Builder() .enableSubjectBitmap() .build() val options = SubjectSegmenterOptions.Builder() .enableMultipleSubjects(subjectResultOptions) .build()
SubjectResultOptions subjectResultOptions = new SubjectSegmenterOptions.SubjectResultOptions.Builder() .enableSubjectBitmap() .build() SubjectSegmenterOptions options = new SubjectSegmenterOptions.Builder() .enableMultipleSubjects(subjectResultOptions) .build()
יוצרים את פילוח הנושא
אחרי שציינת את האפשרויות של SubjectSegmenterOptions
, יוצרים
מכונה SubjectSegmenter
קוראת ל-getClient()
ומעבירה את האפשרויות בתור
:
val segmenter = SubjectSegmentation.getClient(options)
SubjectSegmenter segmenter = SubjectSegmentation.getClient(options);
3. עיבוד תמונה
עוברים את InputImage
המוכנים
ל-method process
של SubjectSegmenter
:
segmenter.process(inputImage) .addOnSuccessListener { result -> // Task completed successfully // ... } .addOnFailureListener { e -> // Task failed with an exception // ... }
segmenter.process(inputImage) .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(SubjectSegmentationResult result) { // Task completed successfully // ... } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Task failed with an exception // ... } });
4. מקבלים את התוצאה של פילוח הנושא
אחזור מסכות חזית ומפות סיביות
אחרי עיבוד התמונה, אפשר לאחזר את המסכה בחזית של השיחה
getForegroundConfidenceMask()
כהבא:
val colors = IntArray(image.width * image.height) val foregroundMask = result.foregroundConfidenceMask for (i in 0 until image.width * image.height) { if (foregroundMask[i] > 0.5f) { colors[i] = Color.argb(128, 255, 0, 255) } } val bitmapMask = Bitmap.createBitmap( colors, image.width, image.height, Bitmap.Config.ARGB_8888 )
int[] colors = new int[image.getWidth() * image.getHeight()]; FloatBuffer foregroundMask = result.getForegroundConfidenceMask(); for (int i = 0; i < image.getWidth() * image.getHeight(); i++) { if (foregroundMask.get() > 0.5f) { colors[i] = Color.argb(128, 255, 0, 255); } } Bitmap bitmapMask = Bitmap.createBitmap( colors, image.getWidth(), image.getHeight(), Bitmap.Config.ARGB_8888 );
אפשר גם לאחזר מפת סיביות של חזית התמונה שנשלחת אל getForegroundBitmap()
:
val foregroundBitmap = result.foregroundBitmap
Bitmap foregroundBitmap = result.getForegroundBitmap();
אחזור מסכות ומפות סיביות לכל נושא
באופן דומה, אפשר לאחזר את המסכה עבור המצולמים על ידי קריאה
getConfidenceMask()
בכל נושא באופן הבא:
val subjects = result.subjects val colors = IntArray(image.width * image.height) for (subject in subjects) { val mask = subject.confidenceMask for (i in 0 until subject.width * subject.height) { val confidence = mask[i] if (confidence > 0.5f) { colors[image.width * (subject.startY - 1) + subject.startX] = Color.argb(128, 255, 0, 255) } } } val bitmapMask = Bitmap.createBitmap( colors, image.width, image.height, Bitmap.Config.ARGB_8888 )
Listsubjects = result.getSubjects(); int[] colors = new int[image.getWidth() * image.getHeight()]; for (Subject subject : subjects) { FloatBuffer mask = subject.getConfidenceMask(); for (int i = 0; i < subject.getWidth() * subject.getHeight(); i++) { float confidence = mask.get(); if (confidence > 0.5f) { colors[width * (subject.getStartY() - 1) + subject.getStartX()] = Color.argb(128, 255, 0, 255); } } } Bitmap bitmapMask = Bitmap.createBitmap( colors, image.width, image.height, Bitmap.Config.ARGB_8888 );
אפשר גם לגשת למפת הסיביות של כל נושא מפולח באופן הבא:
val bitmaps = mutableListOf() for (subject in subjects) { bitmaps.add(subject.bitmap) }
Listbitmaps = new ArrayList<>(); for (Subject subject : subjects) { bitmaps.add(subject.getBitmap()); }
טיפים לשיפור הביצועים
בכל סשן באפליקציה, ההסקה הראשונה בדרך כלל איטית יותר מההסקה הבאה מסקנות כתוצאה מאתחול המודל. אם זמן אחזור קצר הוא קריטי, קריאה ל"דמה" מסקנות מראש.
איכות התוצאות תלויה באיכות של תמונת הקלט:
- כדי ש-ML Kit יקבל תוצאת פילוח מדויקת, התמונה צריכה להיות בגודל של לפחות 512x512 פיקסלים.
- גם מיקוד תמונה לא טוב יכול להשפיע על רמת הדיוק. אם לא מתקבלות תוצאות מקובלות, מבקשים מהמשתמש לצלם מחדש את התמונה.