rmbg

package module
v1.4.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 31, 2026 License: MIT Imports: 8 Imported by: 0

README

rmbg

🎨 High-performance background removal library for Go

A fast and efficient Go library for removing backgrounds from images using ONNX Runtime and the U²-Net model. Perfect for e-commerce, profile pictures, product photography, and image preprocessing pipelines.

✨ Features

  • 🎯 Smart Cropping: Automatically detect and crop around the main subject
  • 🖼️ Multiple Mask Strategies: Auto-detect, alpha channel, edge detection, or background color detection
  • 🔧 Configurable: Fine-tune thread count, memory usage, and processing parameters
  • 🔄 Reusable Sessions: Session pooling for optimal performance in concurrent environments

📋 Requirements

  • Go 1.25.0 or higher
  • ONNX Runtime library installed on your system

🚀 Installation

go get github.com/josuedeavila/rmbg

📥 Model Download

Download the U²-Net ONNX model:

mkdir -p models
cd models
# Download u2netp model (smaller, faster)
wget https://github.com/danielgatis/rembg/releases/download/v0.0.0/u2netp.onnx

Or use the full U²-Net model for better quality:

wget https://github.com/danielgatis/rembg/releases/download/v0.0.0/u2net.onnx

💡 Quick Start

Basic Background Removal
package main

import (
    "fmt"
    "github.com/disintegration/imaging"
    "github.com/josuedeavila/rmbg"
)

func main() {
    // Initialize the engine
    cfg := &rmbg.Config{
        ModelPath:         "./models/u2netp.onnx",
        IntraOpNumThreads: 4,
        InterOpNumThreads: 2,
        CpuMemArena:       false,
        MemPattern:        true,
    }

    engine, err := rmbg.New(cfg)
    if err != nil {
        panic(err)
    }
    defer engine.Close()

    // Load image
    img, err := imaging.Open("input.jpg")
    if err != nil {
        panic(err)
    }

    // Remove background
    result, err := engine.RemoveBackground(img)
    if err != nil {
        panic(err)
    }

    // Save result
    err = imaging.Save(result, "output.png")
    if err != nil {
        panic(err)
    }

    fmt.Println("Background removed successfully!")
}
Smart Crop

Automatically crop the image around the detected subject:

// Remove background and crop
cropped, err := engine.SmartCrop(img, &rmbg.CropConfig{
    Margin:        20,          // Pixels around the object
    MarginPercent: 0.1,         // Or 10% of object dimensions
    MinThreshold:  10,          // Mask sensitivity (0-255)
    SquareCrop:    true,        // Force square crop
})
if err != nil {
    panic(err)
}

imaging.Save(cropped, "cropped.png")
Using Custom Masks
// Define crop configuration
cropConfig := &rmbg.CropConfig{
    Margin:       10,
    SquareCrop:   true,
    MinThreshold: 20,
}

// Use existing alpha channel
result, err := engine.SmartCropFromMask(img, rmbg.MaskFromAlpha, cropConfig)

// Auto-detect best mask strategy
result, err := engine.SmartCropFromMask(img, rmbg.AutoMask, cropConfig)

// Detect edges
result, err := engine.SmartCropFromMask(img, func(img image.Image) *image.Gray {
    return rmbg.MaskFromEdges(img, 200)
}, cropConfig)

// Detect background color
result, err := engine.SmartCropFromMask(img, func(img image.Image) *image.Gray {
    bgColor := color.RGBA{R: 255, G: 255, B: 255, A: 255} // white
    return rmbg.MaskFromBackground(img, bgColor, 50)
}, cropConfig)

⚙️ Configuration

Engine Config
type Config struct {
    // Path to ONNX model file
    ModelPath string

    // Number of threads for intra-op parallelism (default: 1)
    // Higher values = more parallel ops within layers
    IntraOpNumThreads int

    // Number of threads for inter-op parallelism (default: 1)
    // Higher values = more parallel execution between layers
    InterOpNumThreads int

    // Enable CPU memory arena (default: false)
    // Can improve performance but uses more memory
    CpuMemArena bool

    // Enable memory pattern optimization (default: true)
    MemPattern bool
}
Crop Config
type CropConfig struct {
    // Fixed margin in pixels around detected object
    Margin int

    // Margin as percentage of object dimensions (overrides Margin)
    MarginPercent float64

    // Minimum mask value to consider as object (0-255). The predicted mask
    // holds the model's per-pixel confidence, so this is a confidence floor.
    MinThreshold uint8

    // Force square crop using largest dimension
    SquareCrop bool
}

🎯 Use Cases

  • E-commerce: Product photography with clean backgrounds
  • Profile Pictures: Automatic background removal for avatars
  • Image Processing Pipelines: Batch processing of images
  • AR/VR Applications: Subject extraction for compositing
  • Document Scanning: Remove backgrounds from scanned objects
  • Creative Tools: Photo editing and manipulation

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📝 License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AutoMask added in v1.2.0

func AutoMask(img image.Image) *image.Gray

func MaskFromAlpha added in v1.2.0

func MaskFromAlpha(img image.Image) *image.Gray

func MaskFromBackground added in v1.2.0

func MaskFromBackground(img image.Image, bg color.Color, tolerance float64) *image.Gray

func MaskFromEdges added in v1.2.0

func MaskFromEdges(img image.Image, threshold float64) *image.Gray

Types

type Config

type Config struct {
	// ModelPath is the path to the ONNX model file.
	ModelPath string
	// IntraOpNumThreads is the number of threads to use for intra-op parallelism.
	IntraOpNumThreads int
	// InterOpNumThreads is the number of threads to use for inter-op parallelism.
	InterOpNumThreads int
	// CpuMemArena is a flag indicating whether to use a CPU memory arena.
	CpuMemArena bool
	// MemPattern is a flag indicating whether to use a memory pattern.
	MemPattern bool
}

Config for RemBG

type CropConfig added in v1.1.0

type CropConfig struct {
	// Margin is the margin in pixels around the detected object (default: 20)
	Margin int
	// MarginPercent is the margin as a percentage of the object dimensions (overrides Margin if > 0)
	MarginPercent float64
	// MinThreshold is the minimum value of the mask to consider as part of the object (0-255, default: 10)
	MinThreshold uint8
	// SquareCrop forces the crop to be square, using the largest dimension
	SquareCrop bool
}

CropConfig configures the behavior of the smart crop

type Mask added in v1.2.0

type Mask func(img image.Image) *image.Gray

type RemBG

type RemBG struct {
	// contains filtered or unexported fields
}

RemBG with session reuse and memory pooling

func New

func New(config *Config) (*RemBG, error)

NewRemBG initializes ONNX session

func (*RemBG) Close

func (r *RemBG) Close() error

Close destroys the session and releases resources

func (*RemBG) RemoveBackground

func (r *RemBG) RemoveBackground(img image.Image) (image.Image, error)

RemoveBackground processes image with memory pooling

func (*RemBG) RunInference

func (r *RemBG) RunInference(input []ort.Value, output []ort.Value) error

func (*RemBG) SmartCrop added in v1.1.0

func (r *RemBG) SmartCrop(img image.Image, config *CropConfig) (image.Image, error)

SmartCrop removes the background and performs a smart crop focusing on the object

func (*RemBG) SmartCropFromMask added in v1.2.0

func (engine *RemBG) SmartCropFromMask(img image.Image, maskFunc Mask, config *CropConfig) (image.Image, error)

SmartCropFromMask performs a smart crop using an existing mask

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址