Bubbles30 commited on
Commit
9ff7d3f
·
verified ·
1 Parent(s): 8b57c93

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -7
app.py CHANGED
@@ -124,27 +124,37 @@ def download_image(url, out_path, fail_log, code, suf):
124
  log(f"Download failed for all methods")
125
  return False
126
 
 
 
 
127
  def flatten_threshold(img: Image.Image,
128
  target: int,
129
  fill=(255,255,255),
130
  thresh: int = 128) -> Image.Image:
131
  """
132
- 1. Force any pixel with alpha ≤ thresh to white.
133
- 2. Keep fully opaque pixels as-is.
134
- 3. Center the result on a target×target white canvas.
135
  """
136
- # 1) Convert to RGBA to get alpha
 
 
 
 
 
 
 
137
  rgba = img.convert("RGBA")
138
  r, g, b, a = rgba.split()
139
 
140
- # 2) Build a binary mask: opaque where alpha > thresh
141
  mask = a.point(lambda v: 255 if v > thresh else 0)
142
 
143
- # 3) Compose RGB image using that mask
144
  rgb = Image.new("RGB", rgba.size, fill)
145
  rgb.paste(rgba.convert("RGB"), mask=mask)
146
 
147
- # 4) Pad/center on square
148
  w, h = rgb.size
149
  canvas = Image.new("RGB", (target, target), fill)
150
  x = (target - w) // 2
 
124
  log(f"Download failed for all methods")
125
  return False
126
 
127
+ from PIL import Image, ImageFile
128
+ ImageFile.LOAD_TRUNCATED_IMAGES = True # just in case
129
+
130
  def flatten_threshold(img: Image.Image,
131
  target: int,
132
  fill=(255,255,255),
133
  thresh: int = 128) -> Image.Image:
134
  """
135
+ 1) Convert any palette or L-mode with byte transparency into RGBA
136
+ 2) Force alpha ≤ thresh → white, alpha > thresh → keep color
137
+ 3) Center result on a target×target white canvas
138
  """
139
+ # Step 0: handle palette images with byte transparency
140
+ if img.mode == "P":
141
+ if img.info.get("transparency") is not None:
142
+ img = img.convert("RGBA") # bring in the alpha byte
143
+ else:
144
+ img = img.convert("RGB") # no alpha channel at all
145
+
146
+ # Step 1: make sure we have an alpha channel
147
  rgba = img.convert("RGBA")
148
  r, g, b, a = rgba.split()
149
 
150
+ # Step 2: build binary mask
151
  mask = a.point(lambda v: 255 if v > thresh else 0)
152
 
153
+ # Step 3: composite over white
154
  rgb = Image.new("RGB", rgba.size, fill)
155
  rgb.paste(rgba.convert("RGB"), mask=mask)
156
 
157
+ # Step 4: pad to square
158
  w, h = rgb.size
159
  canvas = Image.new("RGB", (target, target), fill)
160
  x = (target - w) // 2