-
Notifications
You must be signed in to change notification settings - Fork 0
Portrait Mode (WIP) #18
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
IzaakBH
wants to merge
30
commits into
main
Choose a base branch
from
portrait-mediapipe
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 3 commits
Commits
Show all changes
30 commits
Select commit
Hold shift + click to select a range
fcb312a
Initial mediapipe segmentation
772a10f
Add something that currently just blurs the whole image
5b582fa
Working portrait mode
d18a13f
Use a faster blurring algorithm & refactor to apply mask at blur time
cdc4085
Add coroutines lib
7cf8cc4
Run blurring in a coroutine
059cfab
Fix applying the mask when blurring
011f2d2
Add comment for mask blurring
50f0324
Add portrait mode setting
6c58f8e
Disable portrait mode when setting off
d26e1e2
Clean up the SegmenterHelper to remove stream specific code
780c7c9
Remove image segmenter listener
9e92755
Ensure rotation is correct on save
a1d598f
unused file
289799b
Fix linting errors
54c6cd3
Merge branch 'main' into portrait-mediapipe
2d4ac18
Fix build errors
a75f673
Use proper library management
98ac693
Add some proguard rules
196dc66
Remove more dead code
8391197
Use compatable coroutines version
a2e551f
Use actual latest mediapipe task version
59b8191
Another proguard rule
ca845fa
Use actual latest mediapipe task version
494e349
Remove ImageSegmenterHelper.kt
f7e4d8f
Remove specific portrait setting with aim of using photo modes instead
3b580aa
Add portrait photo mode and use in photo mode plugin
72d86c0
Remove imports
d7c3630
Move to a mode for toggling portrait
35179f4
Move back to CPU to make mediapipe work
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Binary file not shown.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
189 changes: 189 additions & 0 deletions
189
app/src/main/java/co/stonephone/stonecamera/plugins/Portrait.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,189 @@ | ||
| package co.stonephone.stonecamera.plugins | ||
|
|
||
| import android.content.ContentResolver | ||
| import android.content.ContentValues | ||
| import android.content.Context | ||
| import android.graphics.Bitmap | ||
| import android.graphics.BitmapFactory | ||
| import android.graphics.Canvas | ||
| import android.graphics.Color | ||
| import android.net.Uri | ||
| import android.os.Environment | ||
| import android.os.SystemClock | ||
| import android.provider.MediaStore | ||
| import android.renderscript.Allocation | ||
| import android.renderscript.Element | ||
| import android.renderscript.RenderScript | ||
| import android.renderscript.ScriptIntrinsicBlur | ||
| import androidx.camera.core.ImageCapture | ||
| import co.stonephone.stonecamera.MyApplication | ||
| import co.stonephone.stonecamera.StoneCameraViewModel | ||
| import co.stonephone.stonecamera.utils.ImageSegmenterHelper | ||
| import com.google.mediapipe.framework.image.BitmapImageBuilder | ||
| import com.google.mediapipe.framework.image.ByteBufferExtractor | ||
| import com.google.mediapipe.tasks.vision.core.RunningMode | ||
| import com.google.mediapipe.tasks.vision.imagesegmenter.ImageSegmenterResult | ||
| import java.io.File | ||
| import java.io.FileOutputStream | ||
| import java.io.OutputStream | ||
| import java.nio.ByteBuffer | ||
|
|
||
|
|
||
| class PortraitModePlugin : IPlugin, ImageSegmenterHelper.SegmenterListener { | ||
| override val id: String = "portraitModePlugin" | ||
| override val name: String = "Portrait Mode" | ||
|
|
||
| private lateinit var imageSegmenterHelper: ImageSegmenterHelper | ||
|
|
||
| // Note the various models available here: /home/izaak/Downloads/selfie_segmenter.tflite. | ||
|
|
||
| override fun initialize(viewModel: StoneCameraViewModel) { | ||
| imageSegmenterHelper = ImageSegmenterHelper( | ||
| context = MyApplication.getAppContext(), | ||
| runningMode = RunningMode.IMAGE, | ||
| currentModel = ImageSegmenterHelper.MODEL_SELFIE_SEGMENTER, | ||
| currentDelegate = ImageSegmenterHelper.DELEGATE_CPU, | ||
| imageSegmenterListener = this | ||
| ); | ||
|
|
||
| imageSegmenterHelper.setupImageSegmenter(); | ||
| } | ||
|
|
||
| //TODO fix image rotation being incorrect after processing | ||
| override fun onImageSaved( | ||
| stoneCameraViewModel: StoneCameraViewModel, | ||
| outputFileResults: ImageCapture.OutputFileResults | ||
| ) { | ||
| val contentResolver: ContentResolver = MyApplication.getAppContext().contentResolver | ||
| val imageUri = outputFileResults.savedUri ?: return | ||
|
|
||
| // Open the input stream of the original image | ||
| val inputStream = contentResolver.openInputStream(imageUri) | ||
| val bitmap: Bitmap = BitmapFactory.decodeStream(inputStream) | ||
|
|
||
| val segmentationResults: ImageSegmenterResult = imageSegmenterHelper.segmentImageFile(BitmapImageBuilder(bitmap).build()) ?: return | ||
|
|
||
| val byteBuffer: ByteBuffer = ByteBufferExtractor.extract(segmentationResults.categoryMask().get()) | ||
|
|
||
| val blurred = applyBlurBasedOnMask(MyApplication.getAppContext(), imageUri, byteBuffer) ?: return | ||
| blurred.saveImage(MyApplication.getAppContext()) | ||
| inputStream?.close() | ||
| } | ||
|
|
||
| fun applyBlurBasedOnMask(context: Context, imageUri: Uri, byteBuffer: ByteBuffer): Bitmap? { | ||
| // Step 1: Load the image from URI | ||
| val bitmap = loadBitmapFromUri(context, imageUri) ?: return null | ||
|
|
||
| // Step 2: Extract the mask from the ByteBuffer (assuming it's a binary mask with the same dimensions as the image) | ||
| val width = bitmap.width | ||
| val height = bitmap.height | ||
| val maskPixels = IntArray(width * height) | ||
|
|
||
| // Convert ByteBuffer to pixel values (assuming it's a grayscale mask) | ||
| byteBuffer.rewind() // Reset ByteBuffer position | ||
| for (i in 0 until width * height) { | ||
| val pixelValue = byteBuffer.get().toInt() // Get a single byte from the buffer | ||
| maskPixels[i] = if (pixelValue != 0) Color.WHITE else Color.BLACK | ||
| } | ||
|
|
||
| // Step 3: Apply a blur using RenderScript (or RenderEffect if on a newer Android version) | ||
| val rs = RenderScript.create(context) | ||
| val inputAllocation = Allocation.createFromBitmap(rs, bitmap) | ||
| val outputAllocation = Allocation.createTyped(rs, inputAllocation.type) | ||
|
|
||
| val blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs)) | ||
| blurScript.setRadius(25f) // Adjust blur radius | ||
|
|
||
| blurScript.setInput(inputAllocation) | ||
| blurScript.forEach(outputAllocation) | ||
|
|
||
| val blurredBitmap = Bitmap.createBitmap(bitmap.width, bitmap.height, Bitmap.Config.ARGB_8888) | ||
| outputAllocation.copyTo(blurredBitmap) | ||
|
|
||
| // Step 4: Apply the mask: only blur pixels where the mask is non-zero | ||
| val finalBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) | ||
| val canvas = Canvas(finalBitmap) | ||
| canvas.drawBitmap(bitmap, 0f, 0f, null) // Draw the original bitmap on the canvas | ||
|
|
||
| // Apply blur only on mask areas | ||
| for (y in 0 until height) { | ||
| for (x in 0 until width) { | ||
| if (maskPixels[y * width + x] == Color.WHITE) { | ||
| finalBitmap.setPixel(x, y, blurredBitmap.getPixel(x, y)) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| rs.destroy() // Clean up RenderScript resources | ||
| return finalBitmap | ||
| } | ||
|
|
||
| fun loadBitmapFromUri(context: Context, uri: Uri): Bitmap? { | ||
| try { | ||
| val inputStream = context.contentResolver.openInputStream(uri) | ||
| return BitmapFactory.decodeStream(inputStream) | ||
| } catch (e: Exception) { | ||
| e.printStackTrace() | ||
| return null | ||
| } | ||
| } | ||
|
|
||
| fun Bitmap.saveImage(context: Context): Uri? { | ||
|
||
| if (android.os.Build.VERSION.SDK_INT >= 29) { | ||
| val values = ContentValues() | ||
| values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg") | ||
| values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis() / 1000) | ||
| values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis()) | ||
| values.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/test_pictures") | ||
| values.put(MediaStore.Images.Media.IS_PENDING, true) | ||
| values.put(MediaStore.Images.Media.DISPLAY_NAME, "img_${SystemClock.uptimeMillis()}") | ||
|
|
||
| val uri: Uri? = | ||
| context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) | ||
| if (uri != null) { | ||
| saveImageToStream(this, context.contentResolver.openOutputStream(uri)) | ||
| values.put(MediaStore.Images.Media.IS_PENDING, false) | ||
| context.contentResolver.update(uri, values, null, null) | ||
| return uri | ||
| } | ||
| } else { | ||
| val directory = | ||
| File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).toString() + "_test_pictures") | ||
| if (!directory.exists()) { | ||
| directory.mkdirs() | ||
| } | ||
| val fileName = "img_${SystemClock.uptimeMillis()}"+ ".jpeg" | ||
| val file = File(directory, fileName) | ||
| saveImageToStream(this, FileOutputStream(file)) | ||
| if (file.absolutePath != null) { | ||
| val values = ContentValues() | ||
| values.put(MediaStore.Images.Media.DATA, file.absolutePath) | ||
| // .DATA is deprecated in API 29 | ||
| context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) | ||
| return Uri.fromFile(file) | ||
| } | ||
| } | ||
| return null | ||
| } | ||
|
|
||
| fun saveImageToStream(bitmap: Bitmap, outputStream: OutputStream?) { | ||
| if (outputStream != null) { | ||
| try { | ||
| bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream) | ||
| outputStream.close() | ||
| } catch (e: Exception) { | ||
| e.printStackTrace() | ||
| } | ||
| } | ||
| } | ||
|
|
||
| override val settings: List<PluginSetting> = emptyList() // No settings for portrait yet | ||
|
|
||
| override fun onError(error: String, errorCode: Int) { | ||
| TODO("Not yet implemented") | ||
| } | ||
|
|
||
| override fun onResults(resultBundle: ImageSegmenterHelper.ResultBundle) { | ||
| TODO("Not yet implemented") | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.