Pipeline.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. from os import path
  2. from typing import List
  3. from urllib.request import urlretrieve
  4. import cv2
  5. from pycs.interfaces.MediaFile import MediaFile
  6. from pycs.interfaces.Pipeline import Pipeline as Interface
  7. class Pipeline(Interface):
  8. URL = 'https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml'
  9. def __init__(self, root_folder, distribution):
  10. print('hcffdv1 init')
  11. # get path to xml file
  12. xml_file = path.join(root_folder, 'haarcascade_frontalface_default.xml')
  13. # download
  14. if not path.exists(xml_file):
  15. urlretrieve(self.URL, xml_file)
  16. # load
  17. self.face_cascade = cv2.CascadeClassifier(xml_file)
  18. def close(self):
  19. print('hcffdv1 close')
  20. def execute(self, file: MediaFile) -> List[dict]:
  21. print('hcffdv1 execute')
  22. # load image and convert to grayscale
  23. image = cv2.imread(file.path)
  24. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  25. height, width = gray.shape
  26. min_size = int(min(width, height) / 10)
  27. # detect faces
  28. faces = self.face_cascade.detectMultiScale(
  29. gray,
  30. scaleFactor=1.1,
  31. minNeighbors=5,
  32. minSize=(min_size, min_size)
  33. )
  34. # convert faces to result list
  35. result = []
  36. for x, y, w, h in faces:
  37. result.append(self.create_bounding_box_result(
  38. x / width,
  39. y / height,
  40. w / width,
  41. h / height
  42. ))
  43. return result