Skip to document
← AutoBGAbdul Moiz / Engineering studies Download PDF
Contents 12 chapters + figures

A technical study of controlled automotive imaging

Change the setting. Keep the car.

High-resolution matting, deterministic studio compositing, and carefully bounded diffusion. How AutoBG turns everyday vehicle photographs into grounded studio scenes without asking a model to redraw the vehicle.

  • Computer vision
  • BiRefNet HR
  • SDXL
  • ControlNet

Part I / The problem

01

Background removal is only the beginning.

A clean cutout is not a believable studio image. A vehicle can have sharp edges and still look pasted onto a floor because the wheels do not touch their shadows, the reflection starts at the wrong height, or the old background's color survives around the mirrors. AutoBG addresses the whole composition rather than stopping at segmentation.

The product takes an uploaded car photograph, separates the vehicle with a high-resolution alpha matte, places it in a selected studio, and returns a downloadable PNG. Geometry and image-processing operations handle placement, contact, and edge integration. Diffusion is reserved for the parts of the scene where generation is useful.

AutoBG upload and result interface
Figure 1. The demonstrated product workflow is upload, generate, preview, and download. The interface requests the White Studio reflection mode.

Part II / The system

02

One matte, three rendering paths.

The frontend sends a multipart request to FastAPI. Input decoding, validation, downscaling, and segmentation are shared across modes. The resulting RGBA cutout is dispatched to a deterministic template compositor, a floor-reflection generator, or a full-background generator.

One upload. Three rendering paths.AutoBG / System map
BrowserShared backendMode dispatch
Next.js interfaceupload · before / after · download
POST /processFormData: file + template + mode
PNG responseblob → preview + local download
FastAPI gatewaydecode RGB · validate · downscale ≤ 2048px
BiRefNet HRPyTorch inference → continuous RGBA matte
Mode routershared cutout → selected renderer
templatecompositing · no diffusion
reflect_aireflect_gen · floor-only inpainting
aiaigen · full background inpainting
reflect_ai + ai reuse one cached SDXL / ControlNet pipeline.
Every request starts with the same matte. The UI requests reflect_ai; the API defaults to template when no mode is supplied.
ModeWhat changesPrimary implementation
templatePrepared studio, geometric reflection, shadows, and integrationcompositing; no diffusion after matting
reflect_aiA bounded floor reflection band within the prepared studioreflect_gen using the shared SDXL pipeline
aiThe wider background, followed by source-cutout reintegrationaigen using SDXL and Canny ControlNet

The API defaults to template when no mode is supplied. The current browser interface explicitly sends reflect_ai and white_studio. The API therefore exposes more rendering choices than the present UI. In the reviewed dispatcher, any unrecognized mode also falls through to template; it is not a strict enum-validation endpoint.

Part III / Image formation

03

Continuous alpha preserves the edge.

BiRefNet HR produces a continuous opacity estimate instead of a coarse binary foreground mask. This matters around mirrors, tires, chrome, and fine silhouette details, where a hard yes/no cutout can discard structure or preserve the old background.

A matte, not a binary cutoutAutoBG / System map
PrepareInferRestoreRefine
RGB photographresize to 2048² · ImageNet normalization
BiRefNet HRforward pass → sigmoid alpha
RGBA cutoutLANCZOS alpha resize to source dimensions
Edge refinementforeground recovery · tighten · anti-alias
Foreground recovery: PyMatting ML estimation when available → color-decontamination fallback otherwise.
The continuous alpha returns to the input resolution. Template and reflection paths then recover foreground colors before tightening the edge.

The default model identifier is ZhengPeng7/BiRefNet_HR and the internal inference size is 2048 by 2048. RGB input is resized and ImageNet-normalized, passed through the model, and converted from the final prediction through sigmoid into alpha. The alpha map is resized with LANCZOS back to the processed input's dimensions and attached to the RGB image.

Alpha compositing
I = alpha * F + (1 - alpha) * B

I : observed image color
F : foreground vehicle color
B : background color
alpha : continuous opacity in [0, 1]

The API may first reduce a large upload to MAX_INPUT_SIDE, default 2048. Returning alpha at the input resolution therefore refers to the downscaled image passed to segmentation, not necessarily the original camera file's full resolution. Segmentation selects CUDA when available; the SDXL generation path explicitly requires CUDA.

Part III / Image formation

04

Solve the color contamination, not only the mask.

Semi-transparent edge pixels mix the foreground with the old background. Simply placing those pixels on a white studio can leave a colored fringe. The compositor first attempts foreground-color estimation with PyMatting. If that path is unavailable, a guided color-diffusion fallback propagates interior colors into the edge band.

Alpha tightening then suppresses faint low-opacity glow, contracts the matte by roughly one pixel with a small elliptical erosion, and applies anti-aliasing. The objective is a cleaner boundary without indiscriminately blurring the entire subject.

OperationWhy it existsFailure to watch
Foreground recoveryRemove background color mixed into translucent edge pixelsResidual color fringe or overcorrected paint color
Alpha tighteningReduce the faint halo outside the silhouetteThin mirrors or fine details eroded away
Anti-aliasingAvoid visibly jagged boundariesAn overly soft tire or body edge
Lighting integrationReduce the pasted-on appearanceUnintended exposure or color changes

Part III / Image formation

05

Ground the wheels before adding atmosphere.

The deterministic studio compositorAutoBG / System map
Prepare the sceneGround the vehicleIntegrate the result
Studio backgroundsaved PNG plate or procedural wall + floor
Prepare foregroundclean edges · white balance · floor bounce
Scale & place70% canvas width · height capped at 56%
Contact contourlowest opaque pixel in each column
Reflection + shadowmirror per column · ambient band + dark core
Composite the carstudio → reflection → shadow → foreground
Realism finishscreen-blended light wrap · seeded film grain
Studio PNG1200 × 900 · RGB
This is the template path after segmentation. Geometry, contact shadows, reflection, lighting, and seeded grain are handled with NumPy, OpenCV, and Pillow.

The template path uses a saved studio plate when one exists, otherwise a procedural wall/floor background. The cutout is cropped, scaled, and positioned on the canvas. Placement is paired with a per-column ground contour computed from the lowest opaque pixel of the vehicle silhouette.

The reflection mirrors each column about its own contact height, rather than flipping the whole bounding box about one horizontal line. This distinction matters for a three-quarter view where the front and rear wheels occupy different image heights. Reflection opacity fades with distance and blur increases away from contact.

Contact shadows combine a soft ambient layer along the underside with darker cores around wheel-contact columns. White-balance adjustment, ambient floor bounce, edge light wrap, and seeded grain integrate the subject and background after geometry has been established.

LayerGeometric or photometric responsibility
Studio plate / procedural sceneA consistent wall, floor, horizon, and perspective
Per-column ground contourContact height appropriate to the photographed viewpoint
ReflectionA fading, depth-softened mirror anchored to the contour
ShadowSoft body occlusion plus darker wheel contact
Realism passWhite balance, floor bounce, edge light, and texture consistency

Part IV / Bounded generation

06

Generate only the part that needs generation.

The default UI path builds a prepared car-and-studio composite, initializes a geometric reflection, and asks SDXL to refine a masked floor band. A contour-following mask restricts the edit. Canny edges provide structural conditioning, while a fixed seed and configurable diffusion settings make experiments easier to compare.

Generate the reflection. Preserve the scene.AutoBG / System map
Build an initializationConstrain diffusionBlend back locally
Base compositestudio + contact shadow + prepared car
Geometric mirrorper-column contact · fade · distance blur
Initialization imagebase + geometric floor reflection
Floor-only maskcontact contour · 50% of car height · feather
Canny conditioningedges from the initialization image
SDXL + ControlNet1024² · 22 steps · strength 0.32 · seed 7
Blend AI + geometry50 / 50 by default · soften with blur
Masked paste-backtake only the refined floor region
Final composite1200 × 900 · PNG response
Only the feathered floor band is pasted back into the base composite. The vehicle geometry is not regenerated, and the studio outside that mask is retained.
Reflection controlReviewed defaultMeaning
REFL_STEPS22Configured inference-step budget
REFL_STRENGTH0.32Denoising strength relative to the initialized reflection
REFL_CN0.70ControlNet conditioning scale
REFL_GUIDE6.0Text guidance scale
REFL_BLEND0.50Geometric contribution to the AI/geometric mixture
REFL_SEED7Generator seed

The generated result is blended with the geometric initialization, softened, and pasted back through the floor mask. This avoids using an unconstrained generated image as the entire final result. A stronger diffusion setting can add detail, but it can also introduce duplicates, distorted wheels, or a reflection that no longer corresponds to the subject.

Part IV / Bounded generation

07

A broader edit needs a stronger reintegration path.

Full-background mode places the vehicle on a working canvas and marks the background for inpainting. The shared SDXL ControlNet pipeline generates the surrounding scene with template-specific prompts and Canny guidance. The source cutout is subsequently cleaned and composited back into the generated scene.

Full-background generationAutoBG / System map
ConditionGenerateGroundMatch
Place the cutoutgray canvas · background mask · Canny edges
SDXL inpaintingtemplate prompt · 30 steps · guidance 7
Ground the scenedeglow · ambient shadow · wheel cores
Match illuminationLAB color + exposure harmonization
Finish → guided-filter alpha → paste original cutout → light wrap → film grain.
The ai path generates a new scene, then harmonizes and re-pastes the original cutout. Default generation is 1024 × 1024; it is a separate path from floor-only reflection.

Post-processing suppresses the bright floor halo sometimes produced near the car, adds dedicated contact shadows, harmonizes exposure and color statistics, refines the edge with a guided filter, and applies light wrap and grain. These operations are necessary because a plausible background and a good matte do not automatically form a coherent photograph.

ModelResponsibility
stabilityai/stable-diffusion-xl-base-1.0The base diffusion model
diffusers/controlnet-canny-sdxl-1.0Edge-conditioned structural guidance
madebyollin/sdxl-vae-fp16-fixFP16 VAE used by the CUDA pipeline

The default working size is 1024 by 1024, with 30 configured inference steps, guidance 7.0, and ControlNet scale 0.5. These are code defaults, not a measured best setting for every input image. The renderer's output size also differs from the template compositor, so the API should not be described as returning one universal dimension for all modes.

Part IV / Bounded generation

08

Prepare reusable studios; isolate experiments.

Offline plate preparation

The make_plate utility takes a reference studio photo, segments the car, expands the removal mask to cover nearby shadow/reflection, and inpaints an empty studio. The saved plate can be reused by the deterministic compositor. This is an offline preparation step, not an extra generation pass in every request.

Build a reusable studio plateAutoBG / System map
ReferenceRemoveReconstructReuse
Reference photoplates/reference.png or .jpg
Mask the vehicleBiRefNet alpha → 35 × 35 dilation
Empty-studio inpaintSDXL · 30 steps · ControlNet disabled
Save the plateresize back → white_studio.png
make_plate is an offline preparation utility. The compositor loads plates/white_studio.png when it exists, otherwise it builds the background procedurally.

Conditioned relighting

A separate IC-Light FBC module experiments with foreground/background-conditioned relighting. It uses a Realistic Vision V5.1 SD1.5 base, patches the UNet input to accept the noisy latent plus foreground and background conditioning latents, and merges IC-Light offset weights. The documented inference works at SD1.5's 512-scale before upscaling.

Optional IC-Light relighting moduleAutoBG / System map
Conditioning imagesPatched SD1.5Relit output
Foreground on graycar cutout normalized on a 512² canvas
Studio backgroundtemplate image resized to 512²
VAE encodingforeground + background → 8 conditioning channels
UNet: 4 → 12 channelsnoisy latent + foreground + background
IC-Light FBC offsetsadditive weight merge · hooked forward pass
SD1.5 relight25 steps · foreground + background conditioning
Upscale the result512² → 1024² · LANCZOS
iclight is present as an independent experiment; main does not expose it as a processing mode. It is not part of the demo's reflect_ai path.

Part V / Product and runtime

09

A small API with an explicit output contract.

EndpointBehavior
GET /Returns service status and active matting model identifier
GET /templatesLists available studio templates
POST /processAccepts an image plus template/mode fields; returns image/png bytes
Multipart request
POST /process
Content-Type: multipart/form-data

file     = uploaded image
template = white_studio
mode     = reflect_ai

Response: image/png (binary)

Empty uploads and unreadable images return 400 errors. Segmentation and renderer failures return 500 responses with the failing stage's message. The frontend receives the PNG as a blob, creates an object URL, previews it, and offers a local download.

The browser's progress bar is estimated, not backend telemetry: it approaches 90% using an elapsed-time curve and completes when the server response arrives. This avoids pretending that a waiting browser knows the actual diffusion step count. It must not be presented as a real-time GPU progress feed.

Part V / Product and runtime

10

Spend GPU time where it changes the result.

The README reports approximate NVIDIA L4 request timings of 0.7 seconds for template composition, 13 seconds for AI reflection, and 18 seconds for full-background generation. The graph reproduces those reported values on one seconds axis. It is a mode-cost comparison, not a new benchmark performed for this portfolio.

Figure / README-reported warm-request timings

Three modes. Different inference budgets.

Approximate AutoBG request timings on NVIDIA L4Template: 0.7 seconds; AI reflection: 13 seconds; AI background: 18 seconds. These are approximate README-reported values, not a new benchmark.0s5s10s15s20sTemplate~0.7sAI reflection~13sAI background~18s
One linear seconds axis, from 0 to 20. Model loading and download are separate; image size, configuration, and hardware change actual latency.

The template mode avoids diffusion after matting. Reflection mode pays for a constrained generated region. Full-background mode pays for a wider generative scene and a reintegration chain. This separation gives the caller a meaningful quality/consistency/cost choice instead of running the largest available model for every operation.

Startup warms matting and, by default, attempts to preload SDXL through WARM_SDXL. The SDXL and ControlNet objects are reused by reflection and background modes. Cold model download/loading, GPU memory pressure, input dimensions, package versions, and renderer settings can all change end-to-end latency.

Part VI / Operating the system

11

Keep responsibilities small enough to inspect.

ModuleResponsibility
mainDecode, validate, downscale, segment, dispatch, and return PNG
segmentCached BiRefNet inference and continuous-alpha RGBA output
compositingStudio assets, edge recovery, placement, reflections, shadows, and realism
reflect_genReflection mask, initialized mirror, SDXL conditioning, and local paste-back
aigenShared diffusion loader, background generation, and scene integration
make_plateOffline construction of reusable empty studio plates
iclightIndependent experimental conditioned-relighting path
FrontendUpload state, estimated progress, before/after previews, and PNG download

What to evaluate next

  • Use a held-out set of side, front, and three-quarter views, including mirrors and fine trim.
  • Measure silhouette/edge quality separately from foreground color preservation.
  • Inspect wheel contact, reflection correspondence, duplicate-car artifacts, and floor halos.
  • Compare all modes with fixed inputs and explicit settings, recording cold and warm timings separately.
  • Test empty, oversized, malformed, no-car, and concurrent requests before making an operational reliability claim.

Observability should distinguish decode errors, segmentation failures, model-load failures, out-of-memory conditions, and renderer errors. Stage timings and the selected mode/model/configuration are more actionable than a single total request duration. Any production queue or retry layer should also make GPU work idempotent and avoid silently duplicating expensive generation.

Closing / Engineering judgment

12

The boundary is the feature.

AutoBG's central choice is selective generation. Continuous matting protects the silhouette; deterministic compositing establishes placement and ground contact; diffusion is given a bounded region or an explicit reintegration path. The result is easier to reason about than a single unconstrained prompt to redraw the scene.

  • Fix foreground color contamination as well as alpha quality.
  • Anchor reflections and shadows to the actual silhouette, not only its bounding box.
  • Separate reusable scene preparation from online inference.
  • Use explicit generation boundaries, reproducible settings, and source-cutout reintegration.
  • Keep prototype behavior, README timings, experiments, and future hardening clearly distinguished.