tonyassi commited on
Commit
c66f6d9
Β·
verified Β·
1 Parent(s): 85119c0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -2
app.py CHANGED
@@ -10,13 +10,41 @@ from diffusers import AutoPipelineForInpainting, AutoencoderKL
10
  # -----------------------------
11
  # Pure-CPU helpers (no CUDA here)
12
  # -----------------------------
13
- def squarify_image(img, color="white"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  w, h = img.size
15
  size = max(w, h)
16
- bg = Image.new(mode="RGB", size=(size, size), color=color)
17
  bg.paste(img, ((size - w) // 2, (size - h) // 2))
18
  return bg
19
 
 
20
  def divisible_by_8(image: Image.Image) -> Image.Image:
21
  w, h = image.size
22
  new_w = max(8, (w // 8) * 8)
 
10
  # -----------------------------
11
  # Pure-CPU helpers (no CUDA here)
12
  # -----------------------------
13
+ from PIL import Image, ImageChops
14
+
15
+ def autocrop_content(img: Image.Image, bg_color=(255, 255, 255), tol=12) -> Image.Image:
16
+ """
17
+ Trim uniform white (or near-white) margins before we center/pad.
18
+ Works for RGB and RGBA. `tol` is tolerance for "how white".
19
+ """
20
+ if img.mode in ("RGBA", "LA"):
21
+ # If we have transparency, use alpha channel bbox
22
+ alpha = img.split()[-1]
23
+ bbox = alpha.getbbox()
24
+ return img.crop(bbox) if bbox else img
25
+
26
+ # RGB: compare to a solid background
27
+ bg = Image.new(img.mode, img.size, bg_color)
28
+ diff = ImageChops.difference(img, bg).convert("L")
29
+ # Binarize with tolerance to catch JPEG off-white backgrounds
30
+ mask = diff.point(lambda p: 255 if p > tol else 0, mode="1")
31
+ bbox = mask.getbbox()
32
+ return img.crop(bbox) if bbox else img
33
+
34
+ def squarify_image(img: Image.Image, color="white") -> Image.Image:
35
+ """
36
+ 1) Trim outer white margins.
37
+ 2) Pad to square, centered.
38
+ """
39
+ img = autocrop_content(img, bg_color=(255, 255, 255), tol=12)
40
+
41
  w, h = img.size
42
  size = max(w, h)
43
+ bg = Image.new("RGB", (size, size), color=color)
44
  bg.paste(img, ((size - w) // 2, (size - h) // 2))
45
  return bg
46
 
47
+
48
  def divisible_by_8(image: Image.Image) -> Image.Image:
49
  w, h = image.size
50
  new_w = max(8, (w // 8) * 8)