test_rembg.py 1004 B

12345678910111213141516171819202122232425262728293031323334353637
  1. """测试 rembg 背景移除 API"""
  2. import sys
  3. import io
  4. sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
  5. import httpx
  6. from pathlib import Path
  7. REMBG_URL = "http://47.84.182.56:8001"
  8. TEST_DIR = Path(__file__).parent
  9. INPUT_IMAGE = TEST_DIR / "20260421-175044.jpg"
  10. OUTPUT_IMAGE = TEST_DIR / "output.png"
  11. def test_rembg():
  12. print(f"输入图片: {INPUT_IMAGE} ({INPUT_IMAGE.stat().st_size / 1024:.1f} KB)")
  13. with open(INPUT_IMAGE, "rb") as f:
  14. response = httpx.post(
  15. f"{REMBG_URL}/api/remove",
  16. files={"file": ("input.jpg", f, "image/jpeg")},
  17. timeout=120.0,
  18. )
  19. print(f"HTTP Status: {response.status_code}")
  20. if response.status_code == 200:
  21. OUTPUT_IMAGE.write_bytes(response.content)
  22. print(f"输出图片: {OUTPUT_IMAGE} ({len(response.content) / 1024:.1f} KB)")
  23. print("背景移除成功!")
  24. else:
  25. print(f"失败: {response.text[:200]}")
  26. if __name__ == "__main__":
  27. test_rembg()