PSNbst commited on
Commit
949d787
·
verified ·
1 Parent(s): d7106ba

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -4
app.py CHANGED
@@ -4,9 +4,24 @@ import os
4
  import shutil
5
  import random
6
 
 
 
 
 
 
 
 
 
 
 
7
  def resize_and_pad(image, target_size):
8
  """Resize the image and pad it to match target size."""
9
- img = image.convert("RGB")
 
 
 
 
 
10
  aspect_ratio = img.width / img.height
11
  target_aspect_ratio = target_size[0] / target_size[1]
12
 
@@ -22,9 +37,6 @@ def resize_and_pad(image, target_size):
22
  # Use high-quality resampling for resizing
23
  img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
24
 
25
- # Randomly select black or white as the background color
26
- padding_color = (255, 255, 255) if random.choice([True, False]) else (0, 0, 0)
27
-
28
  # Create a new image with the determined background color
29
  new_img = Image.new("RGB", target_size, padding_color)
30
  offset = ((target_size[0] - new_width) // 2, (target_size[1] - new_height) // 2)
 
4
  import shutil
5
  import random
6
 
7
+ def process_transparent_image(image, padding_color):
8
+ """Handle images with transparency by converting transparent areas to a solid color."""
9
+ if image.mode in ("RGBA", "LA") or (image.mode == "P" and "transparency" in image.info):
10
+ alpha = image.convert("RGBA").getchannel("A") # Extract the alpha channel
11
+ # Create a new image with the background color
12
+ background = Image.new("RGBA", image.size, padding_color + (255,))
13
+ background.paste(image, mask=alpha) # Paste with transparency mask
14
+ return background.convert("RGB") # Convert back to RGB
15
+ return image.convert("RGB") # For non-transparent images
16
+
17
  def resize_and_pad(image, target_size):
18
  """Resize the image and pad it to match target size."""
19
+ # Randomly select black or white as the background color
20
+ padding_color = (255, 255, 255) if random.choice([True, False]) else (0, 0, 0)
21
+
22
+ # Handle transparent images
23
+ img = process_transparent_image(image, padding_color)
24
+
25
  aspect_ratio = img.width / img.height
26
  target_aspect_ratio = target_size[0] / target_size[1]
27
 
 
37
  # Use high-quality resampling for resizing
38
  img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
39
 
 
 
 
40
  # Create a new image with the determined background color
41
  new_img = Image.new("RGB", target_size, padding_color)
42
  offset = ((target_size[0] - new_width) // 2, (target_size[1] - new_height) // 2)