opsiclear-admin commited on
Commit
4a3a265
·
verified ·
1 Parent(s): 9c08519

Add histogram normalization on foreground pixels after alpha premultiply

Browse files
Files changed (1) hide show
  1. app.py +19 -2
app.py CHANGED
@@ -376,8 +376,25 @@ def preprocess_image(input: Image.Image) -> Image.Image:
376
  bbox = center[0] - size // 2, center[1] - size // 2, center[0] + size // 2, center[1] + size // 2
377
  output = output.crop(bbox) # type: ignore
378
  output = np.array(output).astype(np.float32) / 255
379
- output = output[:, :, :3] * output[:, :, 3:4]
380
- output = Image.fromarray((output * 255).astype(np.uint8))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
381
  return output
382
 
383
 
 
376
  bbox = center[0] - size // 2, center[1] - size // 2, center[0] + size // 2, center[1] + size // 2
377
  output = output.crop(bbox) # type: ignore
378
  output = np.array(output).astype(np.float32) / 255
379
+ rgb = output[:, :, :3]
380
+ alpha = output[:, :, 3:4]
381
+ rgb = rgb * alpha # premultiply alpha
382
+
383
+ # Histogram normalization on foreground pixels only
384
+ fg_mask = (alpha[:, :, 0] > 0.05)
385
+ if fg_mask.any():
386
+ for c in range(3):
387
+ ch = rgb[:, :, c]
388
+ fg_vals = ch[fg_mask]
389
+ if fg_vals.max() > fg_vals.min():
390
+ # Stretch foreground channel to use full [0, 1] range
391
+ lo, hi = np.percentile(fg_vals, [1, 99])
392
+ if hi > lo:
393
+ ch_norm = np.clip((ch - lo) / (hi - lo), 0, 1)
394
+ # Only apply to foreground pixels
395
+ rgb[:, :, c] = np.where(fg_mask, ch_norm, 0)
396
+
397
+ output = Image.fromarray((rgb * 255).astype(np.uint8))
398
  return output
399
 
400