main.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import uvicorn
  2. from fastapi import FastAPI, File, UploadFile
  3. import cv2
  4. import numpy as np
  5. import os
  6. app = FastAPI()
  7. face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_alt2.xml")
  8. anime_cascade = cv2.CascadeClassifier(os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "animu.xml"))
  9. @app.post("/process")
  10. def process(img_data: bytes = File(None)):
  11. try:
  12. im = cv2.imdecode(np.frombuffer(img_data, np.uint8), cv2.IMREAD_COLOR)
  13. gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
  14. normGray = cv2.equalizeHist(gray)
  15. animeFaces = anime_cascade.detectMultiScale(normGray,
  16. 1.1,
  17. 5,
  18. 0,
  19. (24, 24))
  20. normalFaces = face_cascade.detectMultiScale(normGray)
  21. return {
  22. "ok": True,
  23. "animeFaces": [{"x": x.item(), "y": y.item(), "w": w.item(), "h": h.item()} for (x, y, w, h) in animeFaces],
  24. "normalFaces": [{"x": x.item(), "y": y.item(), "w": w.item(), "h": h.item()} for (x, y, w, h) in normalFaces]
  25. }
  26. except Exception as err:
  27. return {
  28. "ok": False,
  29. "error": str(err)
  30. }
  31. if __name__ == "__main__":
  32. uvicorn.run(app, host="0.0.0.0", port=8081)