dennny123 commited on
Commit
41845ad
·
verified ·
1 Parent(s): 16cf633

Align the restored alpha with the VAE crop instead of resizing it

Browse files

A live run showed 429x768 in, 424x768 out: ComfyUI's vae_encode_crop_pixels narrows each dimension by dim % 8 at offset (dim % 8) // 2, so any input side that is not a multiple of 8 comes back a few pixels shorter. Centre-cropping the saved alpha reproduces that offset exactly (verified identical for every dimension 8..4096), keeping the mask pixel-aligned where a resize would shift the cutout.

Files changed (1) hide show
  1. app.py +14 -3
app.py CHANGED
@@ -272,9 +272,20 @@ def reattach_alpha(
272
  if alpha is None:
273
  return image
274
  if alpha.size != image.size:
275
- # The pipeline restores the input's exact dimensions, so this is only
276
- # insurance -- putalpha raises on a size mismatch.
277
- alpha = alpha.resize(image.size, Image.LANCZOS)
 
 
 
 
 
 
 
 
 
 
 
278
  image = image.convert("RGBA")
279
  image.putalpha(alpha)
280
  return image
 
272
  if alpha is None:
273
  return image
274
  if alpha.size != image.size:
275
+ # The VAE round-trip crops each dimension down to a multiple of 8
276
+ # (ComfyUI's vae_encode_crop_pixels narrows by dim % 8 at offset
277
+ # (dim % 8) // 2), so an input whose width or height is not a multiple
278
+ # of 8 legitimately comes back a few pixels smaller -- 429px wide in,
279
+ # 424 out. Centre-cropping the alpha reproduces that offset exactly, so
280
+ # the mask stays pixel-aligned; resizing it would shift the cutout by a
281
+ # pixel or two against the image it belongs to.
282
+ alpha_w, alpha_h = alpha.size
283
+ out_w, out_h = image.size
284
+ if alpha_w >= out_w and alpha_h >= out_h:
285
+ left, top = (alpha_w - out_w) // 2, (alpha_h - out_h) // 2
286
+ alpha = alpha.crop((left, top, left + out_w, top + out_h))
287
+ else:
288
+ alpha = alpha.resize(image.size, Image.LANCZOS)
289
  image = image.convert("RGBA")
290
  image.putalpha(alpha)
291
  return image