Pipeline.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 collections(self) -> List[dict]:
  21. return [
  22. self.create_collection('face', 'face detected', autoselect=True),
  23. self.create_collection('none', 'no face detected')
  24. ]
  25. def execute(self, file: MediaFile) -> List[dict]:
  26. print('hcffdv1 execute')
  27. # load image and convert to grayscale
  28. image = cv2.imread(file.path)
  29. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  30. height, width = gray.shape
  31. min_size = int(min(width, height) / 10)
  32. # detect faces
  33. faces = self.face_cascade.detectMultiScale(
  34. gray,
  35. scaleFactor=1.1,
  36. minNeighbors=5,
  37. minSize=(min_size, min_size)
  38. )
  39. # convert faces to result list
  40. result = []
  41. for x, y, w, h in faces:
  42. result.append(self.create_bounding_box_result(
  43. x / width,
  44. y / height,
  45. w / width,
  46. h / height
  47. ))
  48. # set file collection
  49. if len(result) > 0:
  50. result.append(self.create_collection_result('face'))
  51. else:
  52. result.append(self.create_collection_result('none'))
  53. return result