# Image Background Removal & Cleanup

## Quick workflow

1. **Install rembg (CPU only):**
```bash
pip3 install "rembg[cpu]"
```

2. **Remove background:**
```python
from rembg import remove
from PIL import Image
import io
with open('input.jpg', 'rb') as f:
    input_data = f.read()
output_data = remove(input_data)
with open('output.png', 'wb') as f:
    f.write(output_data)
```

3. **Clean semi-transparent artifacts** (removes ghost pixels not touching opaque edges):
```python
pixels = np.array(Image.open('output.png').convert('RGBA'))
alpha = pixels[:,:,3]
opaque = alpha > 240
semi = (alpha > 5) & (alpha < 200)
keep = np.zeros_like(semi)
for y in range(1, h-1):
    for x in range(1, w-1):
        if semi[y,x] and opaque[y-1:y+2, x-1:x+2].any():
            keep[y,x] = True
pixels[semi & ~keep, 3] = 0
```

4. **Upscale for smoother edges:**
```python
img = img.resize((w*3, h*3), Image.Resampling.LANCZOS).filter(ImageFilter.SMOOTH)
```

## Common scenarios

| Problem | Pass | Approach |
|---|---|---|
| Near-white background | 1 | Threshold RGB > 245 all channels → alpha=0 |
| Solid red/color bg | 1 | Euclidean distance from known RGB → alpha=0 |
| Semi-transparent residuals | 2 | Clear semi alpha not bordering opaque |
| Jaggies on text | 3 | Upscale 3x LANCZOS + SMOOTH |
| Signature in corner | 2 | Mask dark pixels in bottom-right region → alpha=0 |

## Capability note

This server has no wired image generation toolset. For new image creation, write an Imagen prompt. For editing (bg removal, resize, signature removal, color masking), the above workflow works.
