Skip to content

[FEAT]: Better Feathering #2

Description

@julianadormon

Hi Steven! Thanks for this project, it really helped me see behind the curtain.

I was getting some unfavourable halos around some of my low res tests. I ended up making more use of the semi-transparency provided by the model on the pixels that transition between foreground to background. Perhaps this can help someone else.

`public async Task RemoveBackgroundAsync(Stream StreamImage, Stream MaskStream)
{
StreamImage.Position = 0;
MaskStream.Position = 0;

        var ImageWithBg = await Image.LoadAsync<Rgba32>(StreamImage);
        var MaskImage = await Image.LoadAsync<Rgba32>(MaskStream);

        using var ImageWithBgRemoved = new Image<Rgba32>(ImageWithBg.Width, ImageWithBg.Height);

        // Define your cutoff range.
        // Values below MinVal become 0 alpha (transparent).
        // Values above MaxVal become 255 alpha (opaque).
        // Anything in between is scaled linearly.
        const byte MinVal = 70;
        const byte MaxVal = 117;

        byte AdjustAlpha(byte MaskValue)
        {
            if (MaskValue <= MinVal)
                return 0;
            if (MaskValue >= MaxVal)
                return 255;

            float Proportion = (MaskValue - MinVal) / (float)(MaxVal - MinVal);
            return (byte)(Proportion * 255f);
        }

        // Walk over every pixel, using the mask’s R channel.
        WalkImage(ImageWithBg.Height, ImageWithBg.Width, (x, y) =>
        {
            var SourcePixel = ImageWithBg[x, y];
            var MaskPixel = MaskImage[x, y];

            // Compute a new alpha value using the linear mapping.
            byte NewAlpha = AdjustAlpha(MaskPixel.R);

            // Construct the new pixel with the same RGB, but replaced alpha.
            ImageWithBgRemoved[x, y] = new Rgba32(SourcePixel.R, SourcePixel.G, SourcePixel.B, NewAlpha);
        });

        var Result = new MemoryStream();
        await ImageWithBgRemoved.SaveAsync(Result, new PngEncoder());
        Result.Position = 0;

        return Result;
    }`

Metadata

Metadata

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions