sharp icon indicating copy to clipboard operation
sharp copied to clipboard

Remove white pixels to have a transparent background

Open LouisR-P opened this issue 2 months ago • 1 comments

Question about an existing feature

What are you trying to achieve?

I am trying to remove white pixels (RGB ➡️ 255 255 255, but also close values like 255 254 255 or 253 255 255 for example) from any random clothes images.

When you searched for similar issues, what did you find that might be related?

I found this, so I tried to use threshold and unflatten.

Please provide a minimal, standalone code sample, without other dependencies, that demonstrates this question

const processedPantsImage = await sharp(pantsImage)
        .threshold(0, { greyscale: false })
        .unflatten()
        .toBuffer();

With this code ⬆️, im having this result: Before: trouser After: image

This is good but not perfect, it seems to remove the whitest pixels (255 255 255) but not the darkest ones (253 255 255) for example as you can see still some white part staying around the pant.

So I tried different values/options in thresold but I never manage to found one. I tried

const processedPantsImage = await sharp(pantsImage)
        .threshold(240, { greyscale: false })
        .unflatten()
        .toBuffer();

But I gave me a strange black pants in result 😅 Im not sure to really understand how this works

Could you help me finding the correct values I need or give me a better solution? Thanks!

LouisR-P avatar Apr 20 '24 22:04 LouisR-P

up

LouisR-P avatar May 02 '24 14:05 LouisR-P

https://sharp.pixelplumbing.com/api-operation#unflatten

Existing alpha channel values for non-white pixels remain unchanged.

This means unflatten is probably the wrong solution to your problem as you also want non-fully-white pixels to become transparent.

I'd use threshold to create a single-channel negative mask:

await sharp(input)
  .negate()
  .threshold(5)
  .toFile("mask.png");

You can then attach this as an alpha channel:

await sharp(input)
  .joinChannel("mask.png")
  .toFile("output.png");

lovell avatar May 06 '24 19:05 lovell

I hope this information helped. Please feel free to re-open with more details if further assistance is required.

lovell avatar May 16 '24 12:05 lovell