habulaj commited on
Commit
39f2554
·
verified ·
1 Parent(s): 96eebff

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -23
app.py CHANGED
@@ -9,16 +9,22 @@ from io import BytesIO
9
  from PIL import Image, ImageFilter, ImageEnhance
10
  import rembg
11
  import onnxruntime as ort
12
- import cv2
13
- import numpy as np
14
 
15
  app = FastAPI()
16
 
17
- # Limita o número de threads do onnxruntime
18
  options = ort.SessionOptions()
19
- options.intra_op_num_threads = 2
 
20
 
21
- def resize_image(image, max_size=1024):
 
 
 
 
 
 
22
  width, height = image.size
23
  if width > max_size or height > max_size:
24
  ratio = min(max_size / width, max_size / height)
@@ -27,23 +33,13 @@ def resize_image(image, max_size=1024):
27
  return image
28
 
29
  def adjust_brightness_contrast(image, brightness=1.2, contrast=1.2):
 
30
  enhancer = ImageEnhance.Brightness(image)
31
  image = enhancer.enhance(brightness)
32
  enhancer = ImageEnhance.Contrast(image)
33
  image = enhancer.enhance(contrast)
34
  return image
35
 
36
- def remove_shadows(image):
37
- # Converte a imagem para escala de cinza
38
- gray = cv2.cvtColor(np.array(image), cv2.COLOR_RGBA2GRAY)
39
-
40
- # Aplica limiarização para remover áreas escuras (sombras)
41
- _, mask = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY)
42
-
43
- # Aplica a máscara na imagem original
44
- result = cv2.bitwise_and(np.array(image), np.array(image), mask=mask)
45
- return Image.fromarray(result)
46
-
47
  @app.get("/remove-background")
48
  async def remove_background(image_url: str):
49
  try:
@@ -54,17 +50,15 @@ async def remove_background(image_url: str):
54
  # Abre a imagem usando Pillow
55
  image = Image.open(BytesIO(response.content))
56
 
57
- # Pré-processamento: redimensiona e ajusta brilho/contraste
58
- image = resize_image(image, max_size=1024)
59
  image = adjust_brightness_contrast(image)
60
 
61
  # Remove o fundo da imagem usando rembg
62
- output = rembg.remove(image, model="u2net_human_seg", session_options=options)
63
-
64
- # Remove sombras
65
- output = remove_shadows(output)
66
 
67
- # Suaviza a imagem
68
  output = output.filter(ImageFilter.SMOOTH_MORE)
69
 
70
  # Converte a imagem de volta para bytes
 
9
  from PIL import Image, ImageFilter, ImageEnhance
10
  import rembg
11
  import onnxruntime as ort
12
+ from functools import lru_cache
 
13
 
14
  app = FastAPI()
15
 
16
+ # Configurações do onnxruntime para CPU
17
  options = ort.SessionOptions()
18
+ options.intra_op_num_threads = 2 # Limita o número de threads para evitar sobrecarga
19
+ options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL # Execução sequencial para melhor desempenho em CPU
20
 
21
+ # Cache do modelo u2net (carrega apenas uma vez)
22
+ @lru_cache(maxsize=1)
23
+ def load_u2net_model():
24
+ return rembg.get_model("u2net")
25
+
26
+ def resize_image(image, max_size=512):
27
+ """Redimensiona a imagem para uma largura máxima de 512px, mantendo a proporção."""
28
  width, height = image.size
29
  if width > max_size or height > max_size:
30
  ratio = min(max_size / width, max_size / height)
 
33
  return image
34
 
35
  def adjust_brightness_contrast(image, brightness=1.2, contrast=1.2):
36
+ """Ajusta o brilho e o contraste da imagem."""
37
  enhancer = ImageEnhance.Brightness(image)
38
  image = enhancer.enhance(brightness)
39
  enhancer = ImageEnhance.Contrast(image)
40
  image = enhancer.enhance(contrast)
41
  return image
42
 
 
 
 
 
 
 
 
 
 
 
 
43
  @app.get("/remove-background")
44
  async def remove_background(image_url: str):
45
  try:
 
50
  # Abre a imagem usando Pillow
51
  image = Image.open(BytesIO(response.content))
52
 
53
+ # Pré-processamento: redimensiona para 512px e ajusta brilho/contraste
54
+ image = resize_image(image, max_size=512)
55
  image = adjust_brightness_contrast(image)
56
 
57
  # Remove o fundo da imagem usando rembg
58
+ model = load_u2net_model() # Carrega o modelo (usando cache)
59
+ output = rembg.remove(image, model=model, session_options=options)
 
 
60
 
61
+ # Pós-processamento: suaviza as bordas
62
  output = output.filter(ImageFilter.SMOOTH_MORE)
63
 
64
  # Converte a imagem de volta para bytes