Daniel251 commited on
Commit
f61c827
·
verified ·
1 Parent(s): 916813b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +113 -58
app.py CHANGED
@@ -8,6 +8,7 @@ from PIL import Image, ImageDraw, ImageFilter, ImageFont
8
  import numpy as np
9
  import torch
10
  from diffusers import StableDiffusionInpaintPipeline
 
11
  import tempfile
12
  import time
13
 
@@ -249,6 +250,7 @@ with gr.Blocks(title="🎨 Object Replacer AI") as demo:
249
  output_image = gr.Image(
250
  label="",
251
  type="pil",
 
252
  height=350
253
  )
254
 
@@ -334,8 +336,6 @@ with gr.Blocks(title="🎨 Object Replacer AI") as demo:
334
  """Processa a imagem com inpainting"""
335
  try:
336
  log_msg("=== INÍCIO DO PROCESSAMENTO ===")
337
- log_msg(f"Original img: {type(original_img)}")
338
- log_msg(f"Brush data: {type(brush_data)}")
339
 
340
  if original_img is None:
341
  return None, "❌ Carregue uma imagem primeiro!"
@@ -343,80 +343,135 @@ with gr.Blocks(title="🎨 Object Replacer AI") as demo:
343
  if brush_data is None:
344
  return None, "❌ Use o pincel para marcar o objeto!"
345
 
346
- # Processar brush_data do Gradio ImageMask
347
- # No Gradio 6, ImageMask retorna dict com 'background' e 'layers'
348
  img = original_img
349
- mask = None
 
 
350
 
351
  if isinstance(brush_data, dict):
352
- log_msg(f"Brush data keys: {brush_data.keys()}")
 
 
 
 
 
353
 
354
- # Tentar obter a imagem de fundo
355
- if 'background' in brush_data and brush_data['background'] is not None:
356
- img = brush_data['background']
357
- log_msg(f"Imagem do background: {img.size}")
358
 
359
- # Tentar obter as camadas (máscara)
360
- if 'layers' in brush_data and brush_data['layers'] is not None:
361
- layers = brush_data['layers']
362
- log_msg(f"Layers: {len(layers)} camadas")
363
 
364
- # A máscara geralmente está na primeira camada
365
- if len(layers) > 0:
366
- mask_data = layers[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367
 
368
- # Converter para PIL Image
369
- if isinstance(mask_data, np.ndarray):
370
- # Se for RGBA, pegar apenas o canal alpha
371
- if mask_data.ndim == 3:
372
- if mask_data.shape[2] == 4:
373
- mask = Image.fromarray(mask_data[:, :, 3], mode='L')
374
  else:
375
- # Converter para escala de cinza
376
- mask = Image.fromarray(mask_data).convert('L')
377
  else:
378
- mask = Image.fromarray(mask_data, mode='L')
379
-
380
- log_msg(f"Máscara criada: {mask.size}")
381
- elif isinstance(mask_data, Image.Image):
382
- mask = mask_data.convert('L')
383
- log_msg(f"Máscara PIL: {mask.size}")
 
 
 
 
 
384
 
385
- # Se não encontrou nas layers, tentar 'mask' direto
386
- if mask is None and 'mask' in brush_data and brush_data['mask'] is not None:
387
- mask_data = brush_data['mask']
388
- if isinstance(mask_data, np.ndarray):
389
- mask = Image.fromarray(mask_data).convert('L')
390
- elif isinstance(mask_data, Image.Image):
391
- mask = mask_data.convert('L')
392
- log_msg(f"Máscara do dict: {mask.size if mask else 'None'}")
393
-
394
- # Se ainda não tem máscara, verificar se brush_data é a própria máscara
395
- if mask is None:
396
- if isinstance(brush_data, np.ndarray):
397
- mask = Image.fromarray(brush_data).convert('L')
398
- log_msg(f"Máscara do array: {mask.size}")
399
- elif isinstance(brush_data, Image.Image):
400
- mask = brush_data.convert('L')
401
- log_msg(f"Máscara PIL direta: {mask.size}")
402
-
403
- # Verificar se conseguimos extrair a máscara
404
  if mask is None:
405
- return None, "❌ Não foi possível extrair a máscara. Pinte sobre o objeto!"
406
 
407
- # Verificar se a máscara não está vazia
408
  mask_array = np.array(mask)
409
  white_pixels = np.sum(mask_array > 128)
410
- log_msg(f"Pixels brancos na máscara: {white_pixels}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
411
 
412
- if white_pixels < 100: # Menos de 100 pixels marcados
413
- return None, "❌ Marque uma área maior sobre o objeto com o pincel!"
414
 
415
- # Redimensionar mantendo proporção
416
  img = resize_image(img, MAX_SIZE)
417
  mask = mask.resize(img.size, Image.Resampling.LANCZOS)
418
 
419
- log_msg(f"Processando - Ação: {action}, Imagem: {img.size}, Máscara válida")
420
 
421
  # Processar baseado na ação
422
  if action == "replace":
@@ -431,7 +486,7 @@ with gr.Blocks(title="🎨 Object Replacer AI") as demo:
431
 
432
  except Exception as e:
433
  import traceback
434
- error = f"❌ Erro: {str(e)}\n{traceback.format_exc()}"
435
  log_msg(error)
436
  return None, error
437
 
 
8
  import numpy as np
9
  import torch
10
  from diffusers import StableDiffusionInpaintPipeline
11
+ from scipy.ndimage import binary_dilation
12
  import tempfile
13
  import time
14
 
 
250
  output_image = gr.Image(
251
  label="",
252
  type="pil",
253
+ interactive=False,
254
  height=350
255
  )
256
 
 
336
  """Processa a imagem com inpainting"""
337
  try:
338
  log_msg("=== INÍCIO DO PROCESSAMENTO ===")
 
 
339
 
340
  if original_img is None:
341
  return None, "❌ Carregue uma imagem primeiro!"
 
343
  if brush_data is None:
344
  return None, "❌ Use o pincel para marcar o objeto!"
345
 
346
+ # ImageMask do Gradio retorna a imagem com composição da máscara
347
+ # Precisamos extrair apenas a máscara das áreas pintadas
348
  img = original_img
349
+
350
+ # Verificar o formato do brush_data
351
+ log_msg(f"Tipo brush_data: {type(brush_data)}")
352
 
353
  if isinstance(brush_data, dict):
354
+ log_msg(f"Keys: {list(brush_data.keys())}")
355
+
356
+ # Obter imagem composta (background + camadas)
357
+ composite = brush_data.get('composite', None)
358
+ background = brush_data.get('background', None)
359
+ layers = brush_data.get('layers', None)
360
 
361
+ log_msg(f"Composite: {composite is not None}")
362
+ log_msg(f"Background: {background is not None}")
363
+ log_msg(f"Layers: {layers is not None}")
 
364
 
365
+ if composite is not None:
366
+ # Usar a imagem composta
367
+ composite_img = composite if isinstance(composite, Image.Image) else Image.fromarray(composite)
 
368
 
369
+ # A máscara é a diferença entre composite e background
370
+ if background is not None:
371
+ bg_img = background if isinstance(background, Image.Image) else Image.fromarray(background)
372
+
373
+ # Converter para arrays numpy
374
+ composite_arr = np.array(composite_img.convert('RGB'))
375
+ bg_arr = np.array(bg_img.convert('RGB'))
376
+
377
+ # Diferença absoluta
378
+ diff = np.abs(composite_arr.astype(int) - bg_arr.astype(int))
379
+ diff_sum = np.sum(diff, axis=2)
380
+
381
+ # Criar máscara onde há diferença
382
+ mask_arr = (diff_sum > 30).astype(np.uint8) * 255
383
+ mask = Image.fromarray(mask_arr, mode='L')
384
+
385
+ log_msg(f"Máscara criada por diferença: {mask.size}")
386
+ else:
387
+ # Se não tem background, tentar detectar as áreas pintadas
388
+ # Assumir que as áreas pintadas são escuras/pretas
389
+ composite_arr = np.array(composite_img.convert('L'))
390
+ mask_arr = (composite_arr < 128).astype(np.uint8) * 255
391
+ mask = Image.fromarray(mask_arr, mode='L')
392
+
393
+ log_msg(f"Máscara criada por threshold: {mask.size}")
394
+
395
+ elif layers is not None and len(layers) > 0:
396
+ # Processar camadas
397
+ log_msg(f"Processando {len(layers)} camadas")
398
+
399
+ # Começar com máscara vazia
400
+ mask = Image.new('L', img.size, 0)
401
+
402
+ for i, layer in enumerate(layers):
403
+ if layer is None:
404
+ continue
405
+
406
+ log_msg(f"Layer {i}: {type(layer)}")
407
 
408
+ if isinstance(layer, np.ndarray):
409
+ # Se for array, converter
410
+ if layer.ndim == 3:
411
+ # Se RGB/RGBA, pegar canal alpha ou converter para cinza
412
+ if layer.shape[2] == 4:
413
+ layer_mask = Image.fromarray(layer[:, :, 3], mode='L')
414
  else:
415
+ layer_img = Image.fromarray(layer)
416
+ layer_mask = layer_img.convert('L')
417
  else:
418
+ layer_mask = Image.fromarray(layer, mode='L')
419
+ elif isinstance(layer, Image.Image):
420
+ layer_mask = layer.convert('L')
421
+ else:
422
+ continue
423
+
424
+ # Combinar com máscara existente
425
+ mask_arr = np.array(mask)
426
+ layer_arr = np.array(layer_mask)
427
+ combined = np.maximum(mask_arr, layer_arr)
428
+ mask = Image.fromarray(combined, mode='L')
429
 
430
+ else:
431
+ return None, "❌ Não foi possível extrair a máscara. Pinte sobre o objeto com o pincel!"
432
+
433
+ elif isinstance(brush_data, Image.Image):
434
+ # Se for uma imagem direta
435
+ # A máscara é onde está pintado (normalmente em preto)
436
+ brush_arr = np.array(brush_data.convert('L'))
437
+ mask_arr = (brush_arr < 128).astype(np.uint8) * 255
438
+ mask = Image.fromarray(mask_arr, mode='L')
439
+ log_msg(f"Máscara de Image direta: {mask.size}")
440
+
441
+ else:
442
+ return None, "❌ Formato de máscara não reconhecido!"
443
+
444
+ # Verificar se a máscara tem conteúdo
 
 
 
 
445
  if mask is None:
446
+ return None, "❌ Não foi possível criar a máscara. Pinte sobre o objeto!"
447
 
 
448
  mask_array = np.array(mask)
449
  white_pixels = np.sum(mask_array > 128)
450
+ total_pixels = mask_array.size
451
+ percentage = (white_pixels / total_pixels) * 100
452
+
453
+ log_msg(f"Pixels brancos: {white_pixels} ({percentage:.2f}% da imagem)")
454
+
455
+ if white_pixels < 100:
456
+ return None, f"❌ Área marcada muito pequena ({white_pixels} pixels). Pinte mais sobre o objeto!"
457
+
458
+ # Dilatar a máscara levemente para cobrir melhor
459
+ mask_array = np.array(mask)
460
+ kernel_size = 5
461
+ kernel = np.ones((kernel_size, kernel_size), np.uint8)
462
+
463
+ from scipy.ndimage import binary_dilation
464
+ mask_dilated = binary_dilation(mask_array > 128, structure=kernel).astype(np.uint8) * 255
465
+ mask = Image.fromarray(mask_dilated, mode='L')
466
 
467
+ # Suavizar bordas
468
+ mask = mask.filter(ImageFilter.GaussianBlur(radius=5))
469
 
470
+ # Redimensionar
471
  img = resize_image(img, MAX_SIZE)
472
  mask = mask.resize(img.size, Image.Resampling.LANCZOS)
473
 
474
+ log_msg(f"✅ Máscara válida! Processando - Ação: {action}")
475
 
476
  # Processar baseado na ação
477
  if action == "replace":
 
486
 
487
  except Exception as e:
488
  import traceback
489
+ error = f"❌ Erro: {str(e)}\n\n{traceback.format_exc()}"
490
  log_msg(error)
491
  return None, error
492