test_paint_by_example.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import cv2
  2. import pytest
  3. from PIL import Image
  4. from sorawm.iopaint.helper import encode_pil_to_base64
  5. from sorawm.iopaint.model_manager import ModelManager
  6. from sorawm.iopaint.schema import HDStrategy
  7. from sorawm.iopaint.tests.utils import (
  8. check_device,
  9. current_dir,
  10. get_config,
  11. get_data,
  12. save_dir,
  13. )
  14. model_name = "Fantasy-Studio/Paint-by-Example"
  15. def assert_equal(
  16. model,
  17. config,
  18. save_name: str,
  19. fx: float = 1,
  20. fy: float = 1,
  21. img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
  22. mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
  23. example_p=current_dir / "bunny.jpeg",
  24. ):
  25. img, mask = get_data(fx=fx, fy=fy, img_p=img_p, mask_p=mask_p)
  26. example_image = cv2.imread(str(example_p))
  27. example_image = cv2.cvtColor(example_image, cv2.COLOR_BGRA2RGB)
  28. example_image = cv2.resize(
  29. example_image, None, fx=fx, fy=fy, interpolation=cv2.INTER_AREA
  30. )
  31. print(f"Input image shape: {img.shape}, example_image: {example_image.shape}")
  32. config.paint_by_example_example_image = encode_pil_to_base64(
  33. Image.fromarray(example_image), 100, {}
  34. ).decode("utf-8")
  35. res = model(img, mask, config)
  36. cv2.imwrite(str(save_dir / save_name), res)
  37. @pytest.mark.parametrize("device", ["cuda", "mps", "cpu"])
  38. def test_paint_by_example(device):
  39. sd_steps = check_device(device)
  40. model = ModelManager(name=model_name, device=device, disable_nsfw=True)
  41. cfg = get_config(strategy=HDStrategy.ORIGINAL, sd_steps=sd_steps)
  42. assert_equal(
  43. model,
  44. cfg,
  45. f"paint_by_example_device_{device}.png",
  46. img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
  47. mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
  48. fy=0.9,
  49. fx=1.3,
  50. )