Run the 3x3 median pass in infer(), right after the 1024x1024 matte is produced, instead of at full output resolution after upscaling. A single-pixel jag at model resolution becomes a multi-pixel stair once upscaled, which no full-resolution filter can cleanly undo - so edges now upscale to smooth anti-aliased silhouettes. Also drops the now-redundant (and slower) full-res median from the default cleanup; despeckle stays.
RMBGO - Go Background Removing Library
Golang image background removing library (transparency), with everything
embedded: the BRIA RMBG-1.4 ONNX
model and the onnxruntime shared libraries are
compiled into your binary via go:embed. No model downloads, no system
packages, no runtime setup — just import and go.
It runs on the standard library image interfaces: any image.Image in
(precisely decoded PNG/JPEG/GIF or anything else you can construct), standard
*image.NRGBA / *image.Gray out.
Features
- Fully embedded: the fp32 ONNX model (168 MiB) is baked into the binary, and the onnxruntime library for your build platform is baked in too (selected via build tags, so you only carry the one you need).
- Cross-platform: linux/amd64, linux/arm64, darwin/arm64 and windows/amd64 get embedded onnxruntime 1.29.0 libraries; other platforms can plug in their own via option or env var.
- Faithful to the reference pipeline: RGB, bilinear resize to
1024×1024,
(x/255 − 0.5) / 1.0normalization (RMBG-1.4preprocessor_config.json), min–max normalized matte, bilinear resize back to the original size. - Standard images in, standard images out, no cgo hassle for users (the
only dependency is
yalue/onnxruntime_go). - Safe concurrent use of a single
*rmbg.RMBG.
Install
go get m8sh.su/x/rmbgo
Usage
One-liner (lazy global instance):
import "m8sh.su/x/rmbgo"
cutout, err := rmbg.RemoveBackground(img) // *image.NRGBA, background transparent
Managed instance (recommended for services — reuse it, it holds the session):
r, err := rmbg.New(
rmbg.WithNumThreads(4), // optional
// rmbg.WithModelFile("model_fp16.onnx"), // optional: swap the model
)
if err != nil { log.Fatal(err) }
defer r.Close()
mask, err := r.Mask(img) // *image.Gray alpha matte, 255 = foreground
cutout, err := r.Cutout(img) // *image.NRGBA, alpha = matte
cutout, err = r.RemoveBackground(img) // alias for Cutout
Decoding/encoding is plain standard library:
f, _ := os.Open("input.jpg")
img, _, err := image.Decode(f) // import _ "image/jpeg" etc.
f.Close()
cutout, err := rmbg.RemoveBackground(img)
out, _ := os.Create("out.png")
png.Encode(out, cutout)
CLI demo
go run ./cmd/rmbgo -o out.png input.jpg # transparent PNG
go run ./cmd/rmbgo -mask matte.png input.jpg # + grayscale matte
# gentler cut: keep eyes/glasses/gaps, clip less, soften edges
go run ./cmd/rmbgo -o out.png -fill-holes -grow 2 -feather 1.5 input.jpg
go run ./cmd/rmbgo -o out.png -remap 0.2,0.6 -gamma 1.5 input.jpg
go run ./cmd/rmbgo -o out.png -color-rescue input.jpg # blue cartoon parts on dark frames
go run ./cmd/rmbgo -o out.png -dark-background input.jpg # dark background: bright parts always kept (video-safe)
Tuning the matte (keeping character parts)
RMBG-1.4 is aggressive by default: it may carve out eye whites, glasses lenses, dark mouths or gaps framed by limbs, and it clips faint hair. Every method accepts optional refine options — applied after inference, per call, in output-image pixels:
cutout, err := rmbg.RemoveBackground(img,
rmbg.WithFillHoles(), // keep enclosed holes: eyes, glasses, limb-framed gaps
rmbg.WithGrow(2), // dilate the matte: never clip subject pixels
rmbg.WithFeather(1.5), // soften the cut edge
)
| Option | Effect |
|---|---|
WithFillHoles() |
keep low-alpha regions fully enclosed by the subject — the fix for removed eyes/mouths/glasses and gaps between limbs |
WithColorRescue() |
restore background-labeled regions whose color differs from the estimated background color — e.g. blue cartoon ears/belly dropped on dark video frames; ignores border-touching regions and specks |
WithDarkBackground() |
the background is dark: any bright region is kept no matter what the model says — border-touching, dropped, semi-carved (flicker-stabilizing) and small parts (≥ ~16 px, video-resolution safe) included; also does everything WithColorRescue does |
WithGrow(px) |
dilate the matte by px pixels so subject pixels are never clipped |
WithAlphaRemap(lo, hi) |
smoothstep window: alpha ≤ lo → 0, ≥ hi → 255; e.g. (0.2, 0.6) keeps faint subject pixels (hair, fur, soft fabric) |
WithAlphaGamma(g) |
alpha^(1/g); > 1 keeps more of the subject, < 1 cuts harder |
WithFeather(px) |
soften edges over ~px pixels (removes the scissor-cut look, blends into new backgrounds) |
Applied in the order: gamma → remap → color rescue (or dark-background
rescue) → grow → fill holes → feather. They never touch inference itself, so
different calls can use different settings with the same session.
RefineMask(m, opts...) applies the same options to any existing matte
(WithColorRescue and WithDarkBackground need the source image, so they
only work in Mask/Cutout/RemoveBackground).
Bright cartoonish characters on dark backgrounds — e.g. a gopher whose blue ears and belly get dropped on some video frames — are covered by:
cutout, err := rmbg.RemoveBackground(img, rmbg.WithColorRescue())
API
| Symbol | Description |
|---|---|
New(opts ...Option) (*RMBG, error) |
create a remover (embedded model + embedded onnxruntime) |
(*RMBG).Mask(img, refine ...RefineOption) (*image.Gray, error) |
alpha matte, 255 = foreground |
(*RMBG).Cutout(img, refine ...RefineOption) (*image.NRGBA, error) |
image with alpha = matte |
(*RMBG).RemoveBackground(img, refine ...RefineOption) (*image.NRGBA, error) |
alias for Cutout |
(*RMBG).Close() error |
free native resources |
RemoveBackground / Cutout / Mask(img) |
package-level shortcuts using a shared default instance |
Default() (*RMBG, error) |
access the shared default instance |
Shutdown() error |
tear down onnxruntime (tests/tools) |
WithModelFile(path), WithONNXRuntimeLibrary(path), WithNumThreads(n) |
options |
WithFillHoles(), WithColorRescue(), WithGrow(px), WithAlphaRemap(lo,hi), WithAlphaGamma(g), WithFeather(px), WithDespeckle(minPx) |
per-call matte refine options (see above) |
RefineMask(m *image.Gray, opts ...RefineOption) *image.Gray |
apply refine options to an existing matte |
How the embedding works
assets/model.onnx— RMBG-1.4 fp32 ONNX export, embedded with//go:embedand loaded through onnxruntime's load-from-memory API, so the model is never even written to disk.assets/ort/<GOOS>-<GOARCH>/…— onnxruntime 1.29.0 shared libraries. Build-tagged files embed only the library matching the build target. Since shared libraries cannot bedlopened from memory, the library is extracted once into the user cache dir (os.UserCacheDir()/rmbgo/onnxruntime-<hash>/) on first use; subsequent runs reuse it.- Library resolution order:
WithONNXRuntimeLibrary→$RMBG_ONNXRUNTIME_LIB→$ONNXRUNTIME_SHARED_LIBRARY_PATH→ embedded library.
scripts/fetch_assets.sh re-downloads every pinned asset with sha256
verification, in case you want to reproduce or update them.
Platform matrix
| GOOS/GOARCH | onnxruntime | status |
|---|---|---|
| linux/amd64 | 1.29.0 embedded | tested |
| linux/arm64 | 1.29.0 embedded | built from official release |
| darwin/arm64 | 1.29.0 embedded | built from official release |
| windows/amd64 | 1.29.0 embedded | built from official release |
| anything else | — | bring your own library (WithONNXRuntimeLibrary / env var) |
Note for darwin/amd64 and other exotic combos: onnxruntime dropped prebuilt osx-x86_64 archives after 1.28, so provide your own library there. Building for another OS/arch requires a C cross-toolchain (cgo).
Performance
CPU-only, roughly a few seconds per 1024×1024 inference on a modern laptop
core count; RAM footprint ~0.5 GiB peak. Inference uses all available cores
by default (intra-op threads = runtime.NumCPU(); use WithNumThreads(n)
to cap CPU usage) and the matte postprocessing passes are parallelized
across cores as well. For a ~2× smaller binary you can swap in the official
fp16 export (onnx/model_fp16.onnx) via WithModelFile.
Licensing
- Code in this repository: GNU GPL-3.0 (see
LICENSE). assets/model.onnx: BRIA RMBG-1.4 — non-commercial use only (license). Review it before shipping anything commercial; BRIA sells commercial licenses.- Embedded onnxruntime libraries: MIT.
github.com/yalue/onnxruntime_go: MIT.
Tests
go test ./... # full suite (runs real inference once)
go test -short ./... # skip inference, pure functions only
./scripts/test_bg.sh # run the pipeline on bg.png (or any image) and summarize quality
