ML Kit'i kullanarak uygulamanıza kolayca özne segmentasyonu özellikleri ekleyin.
Özellik | Ayrıntılar |
---|---|
SDK adı | play-services-mlkit-subject-segmentation |
Uygulama | Paketten çıkarılmış: Model, Google Play Hizmetleri kullanılarak dinamik olarak indirilir. |
Uygulama boyutu etkisi | Boyut yaklaşık 200 KB artar. |
Başlatma süresi | Kullanıcıların, ilk kullanımdan önce modelin indirilmesini beklemesi gerekebilir. |
Deneyin
- Bu API'nin kullanımına dair bir örnek görmek için örnek uygulamayı inceleyin.
Başlamadan önce
- Proje düzeyindeki
build.gradle
dosyanızda, Google'ın Maven deposunu hembuildscript
hem deallprojects
bölümüne eklediğinizden emin olun. - ML Kit konu segmentasyonu kitaplığına olan bağımlılığı, modülünüzün uygulama düzeyindeki Gradle dosyasına (genellikle
app/build.gradle
) ekleyin:
dependencies {
implementation 'com.google.android.gms:play-services-mlkit-subject-segmentation:16.0.0-beta1'
}
Yukarıda belirtildiği gibi model, Google Play Hizmetleri tarafından sağlanır.
Uygulamanızı, Play Store'dan yüklendikten sonra modeli cihaza otomatik olarak indirecek şekilde yapılandırabilirsiniz. Bunu yapmak için uygulamanızın AndroidManifest.xml
dosyasına aşağıdaki bildirimi ekleyin:
<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>
Ayrıca ModuleInstallClient API ile modelin kullanılabilirliğini açıkça kontrol edebilir ve Google Play Hizmetleri üzerinden indirme isteğinde bulunabilirsiniz.
Yükleme sırasında model indirmelerini etkinleştirmezseniz veya açıkça indirme isteğinde bulunmazsanız model, segmentleyiciyi ilk kez çalıştırdığınızda indirilir. İndirme tamamlanmadan önce yaptığınız istekler sonuç vermez.
1. Giriş resmini hazırlama
Bir resimde segmentasyon gerçekleştirmek için InputImage
, Bitmap
, media.Image
, ByteBuffer
, bayt dizisi veya cihazdaki bir dosyadan InputImage
nesnesi oluşturun.
Farklı kaynaklardan InputImage
nesnesi oluşturabilirsiniz. Her biri aşağıda açıklanmıştır.
media.Image
kullanma
Bir media.Image
nesnesinden InputImage
nesnesi oluşturmak için (ör. bir cihazın kamerasından resim yakaladığınızda) media.Image
nesnesini ve resmin dönüşünü InputImage.fromMediaImage()
'e iletin.
CameraX kitaplığını kullanıyorsanız OnImageCapturedListener
ve
ImageAnalysis.Analyzer
sınıfları, sizin için döndürme değerini hesaplar.
Kotlin
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 // ... } } }
Java
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 // ... } } }
Resmin dönüş derecesini veren bir kamera kitaplığı kullanmıyorsanız, cihazın dönüş derecesi ve cihazdaki kamera sensörünün yönlendirmesinden yararlanarak dönüş derecesini hesaplayabilirsiniz:
Kotlin
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 }
Java
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; }
Ardından, media.Image
nesnesini ve dönüş derecesi değerini InputImage.fromMediaImage()
'ye iletin:
Kotlin
val image = InputImage.fromMediaImage(mediaImage, rotation)
Java
InputImage image = InputImage.fromMediaImage(mediaImage, rotation);
Dosya URI'si kullanma
Dosya URI'sinden InputImage
nesnesi oluşturmak için uygulama bağlamını ve dosya URI'sini InputImage.fromFilePath()
'ye iletin. Bu, kullanıcıdan galeri uygulamasından bir resim seçmesini istemek için ACTION_GET_CONTENT
amacını kullandığınızda yararlıdır.
Kotlin
val image: InputImage try { image = InputImage.fromFilePath(context, uri) } catch (e: IOException) { e.printStackTrace() }
Java
InputImage image; try { image = InputImage.fromFilePath(context, uri); } catch (IOException e) { e.printStackTrace(); }
ByteBuffer
veya ByteArray
kullanma
ByteBuffer
veya ByteArray
öğesinden InputImage
nesnesi oluşturmak için öncelikle media.Image
girişi için daha önce açıklandığı gibi görüntü döndürme derecesini hesaplayın.
Ardından, arabellek veya diziyle birlikte resmin yüksekliği, genişliği, renk kodlama biçimi ve döndürme derecesiyle InputImage
nesnesini oluşturun:
Kotlin
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 )
Java
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
kullanma
Bitmap
nesnesinden InputImage
nesnesi oluşturmak için aşağıdaki bildirimi yapın:
Kotlin
val image = InputImage.fromBitmap(bitmap, 0)
Java
InputImage image = InputImage.fromBitmap(bitmap, rotationDegree);
Resim, döndürme dereceleriyle birlikte bir Bitmap
nesnesiyle gösterilir.
2. SubjectSegmenter örneği oluşturma
Segmentleyici seçeneklerini tanımlama
Resminizi segmentlere ayırmak için önce SubjectSegmenterOptions
öğesinin bir örneğini aşağıdaki gibi oluşturun:
Kotlin
val options = SubjectSegmenterOptions.Builder() // enable options .build()
Java
SubjectSegmenterOptions options = new SubjectSegmenterOptions.Builder() // enable options .build();
Her seçeneğin ayrıntıları aşağıda verilmiştir:
Ön plan güvenilirlik maskesi
Ön plan güven maskesi, ön plandaki nesneyi arka plandan ayırt etmenizi sağlar.
Seçeneklerdeki enableForegroundConfidenceMask()
işlevi, resmi işledikten sonra döndürülen SubjectSegmentationResult
nesnesinde getForegroundMask()
işlevini çağırarak ön plan maskesini daha sonra almanıza olanak tanır.
Kotlin
val options = SubjectSegmenterOptions.Builder() .enableForegroundConfidenceMask() .build()
Java
SubjectSegmenterOptions options = new SubjectSegmenterOptions.Builder() .enableForegroundConfidenceMask() .build();
Ön plan bit eşlemi
Benzer şekilde, ön plandaki öznenin bit eşlem görüntüsünü de alabilirsiniz.
Seçeneklerdeki enableForegroundBitmap()
, resmi işledikten sonra döndürülen SubjectSegmentationResult
nesnesinde getForegroundBitmap()
çağırarak ön plan bit eşlemini daha sonra almanıza olanak tanır.
Kotlin
val options = SubjectSegmenterOptions.Builder() .enableForegroundBitmap() .build()
Java
SubjectSegmenterOptions options = new SubjectSegmenterOptions.Builder() .enableForegroundBitmap() .build();
Çoklu özne güven maskesi
Ön plan seçeneklerinde olduğu gibi, her ön plan öğesi için güven maskesini etkinleştirmek üzere SubjectResultOptions
simgesini kullanabilirsiniz:
Kotlin
val subjectResultOptions = SubjectSegmenterOptions.SubjectResultOptions.Builder() .enableConfidenceMask() .build() val options = SubjectSegmenterOptions.Builder() .enableMultipleSubjects(subjectResultOptions) .build()
Java
SubjectResultOptions subjectResultOptions = new SubjectSegmenterOptions.SubjectResultOptions.Builder() .enableConfidenceMask() .build() SubjectSegmenterOptions options = new SubjectSegmenterOptions.Builder() .enableMultipleSubjects(subjectResultOptions) .build()
Çok öğeli bit eşlem
Benzer şekilde, her konu için bit eşlemi etkinleştirebilirsiniz:
Kotlin
val subjectResultOptions = SubjectSegmenterOptions.SubjectResultOptions.Builder() .enableSubjectBitmap() .build() val options = SubjectSegmenterOptions.Builder() .enableMultipleSubjects(subjectResultOptions) .build()
Java
SubjectResultOptions subjectResultOptions = new SubjectSegmenterOptions.SubjectResultOptions.Builder() .enableSubjectBitmap() .build() SubjectSegmenterOptions options = new SubjectSegmenterOptions.Builder() .enableMultipleSubjects(subjectResultOptions) .build()
Özne segmenterini oluşturma
SubjectSegmenterOptions
seçeneklerini belirledikten sonra getClient()
işlevini çağıran ve seçenekleri parametre olarak ileten bir SubjectSegmenter
örneği oluşturun:
Kotlin
val segmenter = SubjectSegmentation.getClient(options)
Java
SubjectSegmenter segmenter = SubjectSegmentation.getClient(options);
3. Görüntü işleme
Hazırlanan InputImage
nesnesini SubjectSegmenter
'ün process
yöntemine iletin:
Kotlin
segmenter.process(inputImage) .addOnSuccessListener { result -> // Task completed successfully // ... } .addOnFailureListener { e -> // Task failed with an exception // ... }
Java
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. Özne segmentasyon sonucunu alma
Ön plan maskelerini ve bit eşlemleri alma
İşlendikten sonra, resim çağrınız için ön plan maskesini
getForegroundConfidenceMask()
aşağıdaki gibi alabilirsiniz:
Kotlin
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 )
Java
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 );
Ayrıca, getForegroundBitmap()
çağrısı yaparak resmin ön planının bit eşlem görüntüsünü de alabilirsiniz:
Kotlin
val foregroundBitmap = result.foregroundBitmap
Java
Bitmap foregroundBitmap = result.getForegroundBitmap();
Her özne için maskeleri ve bit eşlemleri alma
Benzer şekilde, segmentlere ayrılmış konuların maskesini her bir konu için aşağıdaki gibi getConfidenceMask()
çağırarak alabilirsiniz:
Kotlin
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 )
Java
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 );
Ayrıca, her bir segmentlere ayrılmış konunun bit eşlemine aşağıdaki şekilde de erişebilirsiniz:
Kotlin
val bitmaps = mutableListOf() for (subject in subjects) { bitmaps.add(subject.bitmap) }
Java
Listbitmaps = new ArrayList<>(); for (Subject subject : subjects) { bitmaps.add(subject.getBitmap()); }
Performansı artırmaya yönelik ipuçları
Her uygulama oturumunda, model başlatma nedeniyle ilk çıkarım genellikle sonraki çıkarımlardan daha yavaştır. Düşük gecikme süresi kritik öneme sahipse önceden "sahte" bir çıkarım çağrısı yapmayı düşünebilirsiniz.
Sonuçlarınızın kalitesi, giriş resminin kalitesine bağlıdır:
- ML Kit'in doğru bir segmentasyon sonucu elde etmesi için resim en az 512x512 piksel olmalıdır.
- Resmin iyi odaklanmaması da doğruluğu etkileyebilir. Kabul edilebilir sonuçlar almazsanız kullanıcıdan resmi yeniden çekmesini isteyin.