Spaces:
mashroo
/
Runtime error

YoussefAnso commited on
Commit
c69515e
·
1 Parent(s): 1756164

Enhance image preprocessing in app.py with improved background handling and color conversion

Browse files

- Added hex_to_rgb function to convert hex color strings to RGB tuples.
- Updated preprocess_image to handle RGBA images, perform background removal, resize content, and apply a solid background color.
- Improved error handling for background removal failures, ensuring user feedback on model availability.

Files changed (1) hide show
  1. app.py +24 -6
app.py CHANGED
@@ -105,19 +105,37 @@ def add_background(image, bg_color=(255, 255, 255)):
105
  return Image.alpha_composite(background, image)
106
 
107
 
 
 
 
 
 
 
108
  def preprocess_image(image, background_choice, foreground_ratio, backgroud_color):
109
  """
110
- input image is a pil image in RGBA, return RGB image
 
 
111
  """
112
- print(background_choice)
113
- if background_choice == "Alpha as mask":
114
- background = Image.new("RGBA", image.size, (0, 0, 0, 0))
115
- image = Image.alpha_composite(background, image)
116
- else:
117
  image = remove_background(image)
118
  if image is None:
119
  raise gr.Error("Background removal failed. Please check the input image and ensure the model file exists and is valid.")
120
 
 
 
 
 
 
 
 
 
 
 
 
121
  @spaces.GPU
122
  def gen_image(input_image, seed, scale, step):
123
  global pipeline, model, args
 
105
  return Image.alpha_composite(background, image)
106
 
107
 
108
+ def hex_to_rgb(hex_color: str) -> tuple[int, int, int]:
109
+ """Converts a hex color string to an RGB tuple."""
110
+ hex_color = hex_color.lstrip('#')
111
+ return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
112
+
113
+
114
  def preprocess_image(image, background_choice, foreground_ratio, backgroud_color):
115
  """
116
+ Preprocesses the input image by optionally removing the background, resizing,
117
+ and adding a new solid background.
118
+ Returns an RGB PIL Image.
119
  """
120
+ if image.mode != 'RGBA':
121
+ image = image.convert('RGBA')
122
+
123
+ if background_choice == "Auto Remove background":
 
124
  image = remove_background(image)
125
  if image is None:
126
  raise gr.Error("Background removal failed. Please check the input image and ensure the model file exists and is valid.")
127
 
128
+ # Resize the content of the image
129
+ image = do_resize_content(image, foreground_ratio)
130
+
131
+ # Add a solid background color
132
+ rgb_background = hex_to_rgb(backgroud_color)
133
+ image_with_bg = add_background(image, rgb_background)
134
+
135
+ # Convert to RGB and return
136
+ return image_with_bg.convert("RGB")
137
+
138
+
139
  @spaces.GPU
140
  def gen_image(input_image, seed, scale, step):
141
  global pipeline, model, args