如何在Android MLKit中将图形叠加层转换为Bitmap
Got it, let's walk through how to convert that segmentation overlay graphic into a Bitmap. Based on the SegmentationGraphic class logic from the ML Kit sample, here's a straightforward, actionable approach:
Core Idea
Instead of drawing the segmentation mask directly to a preview canvas (like the sample does), we'll create a mutable Bitmap, attach a Canvas to it, and run the same drawing logic on this Bitmap-linked canvas.
Step 1: Prepare the Bitmap & Canvas
First, create a Bitmap that matches the dimensions of your input image or camera frame. Then get a Canvas instance tied to this Bitmap—this is where we'll draw the segmentation overlay.
// Replace these with your actual input image/frame dimensions int inputWidth = ...; int inputHeight = ...; // Create a mutable Bitmap to hold the segmentation overlay Bitmap segmentationBitmap = Bitmap.createBitmap(inputWidth, inputHeight, Bitmap.Config.ARGB_8888); Canvas bitmapCanvas = new Canvas(segmentationBitmap);
Step 2: Adapt the Segmentation Drawing Logic
Take the core mask-rendering code from the sample's draw(Canvas) method and adapt it to draw on your bitmap's canvas. Here's the key part:
// Get your ML Kit segmentation result (adjust this line to match your result retrieval) SegmentationResult segmentationResult = ...; SegmentationMask mask = segmentationResult.getSegmentationMask(); ByteBuffer maskBuffer = mask.getBuffer(); int maskWidth = mask.getWidth(); int maskHeight = mask.getHeight(); // Set up the paint for the overlay (semi-transparent green as in the sample) Paint overlayPaint = new Paint(); overlayPaint.setColor(Color.argb(128, 0, 255, 0)); // Scale the canvas to match the mask to input image size bitmapCanvas.save(); bitmapCanvas.scale( (float) inputWidth / maskWidth, (float) inputHeight / maskHeight ); // Iterate through the mask buffer and draw foreground regions for (int y = 0; y < maskHeight; y++) { for (int x = 0; x < maskWidth; x++) { float foregroundConfidence = maskBuffer.getFloat(); // Only draw pixels where foreground confidence exceeds your threshold if (foregroundConfidence > 0.5) { bitmapCanvas.drawRect(x, y, x + 1, y + 1, overlayPaint); } } } bitmapCanvas.restore();
Step 3: Use the Resulting Bitmap
Now segmentationBitmap holds your segmentation overlay as a standalone Bitmap. You can display it in an ImageView, save it to storage, or combine it with the original image as needed.
Quick Notes
- Adjust the threshold (
0.5in the example) and overlay color to fit your use case. - If your input image has rotation or scaling transformations (like camera preview orientation), add those to the
bitmapCanvasbefore drawing (mirroring the transformations used in the sample'sGraphicOverlay).
内容的提问来源于stack exchange,提问作者Hemant Bharti

