thumbnailer.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/env python
  2. from __future__ import print_function
  3. from pathlib import Path
  4. import cv2
  5. import numpy as np
  6. import os.path
  7. import sys
  8. def detect(path):
  9. img = cv2.imread(path)
  10. cascade = cv2.CascadeClassifier("detectors/haarcascade_frontalface_alt2.xml")
  11. rects = cascade.detectMultiScale(img, 1.3, 4, cv2.CASCADE_SCALE_IMAGE, (20,20))
  12. if len(rects) == 0:
  13. return [], img
  14. rects[:, 2:] += rects[:, :2]
  15. return rects, img
  16. def box(rects, img):
  17. for x1, y1, x2, y2 in rects:
  18. cv2.rectangle(img, (x1, y1), (x2, y2), (127, 255, 0), 2)
  19. return img
  20. def smart_crop(rects, img):
  21. # Initialize
  22. height, width, _ = img.shape
  23. left, top = 0, 0
  24. max_x, max_y, min_x, min_y = left, top, width, height
  25. # Find extremes of detected features
  26. if len(rects):
  27. print("Detected objects:", len(rects))
  28. for x0, y0, x1, y1 in rects:
  29. min_x = min_x if min_x < x0 else x0
  30. min_y = min_y if min_y < y0 else y0
  31. max_x = max_x if max_x > x1 else x1
  32. max_y = max_y if max_y > y1 else y1
  33. # Focus in the center of detected features
  34. focus = 0.5 * (np.array([min_x, min_y]) + np.array([max_x, max_y]))
  35. crop_size = width if width < height else height
  36. x0, y0 = focus - crop_size / 2
  37. x1, y1 = focus + crop_size / 2
  38. # Move crop box towards center when it goes beyond
  39. x_vector, y_vector = 0, 0
  40. if x0 < 0:
  41. x_vector = -x0
  42. elif x1 > width:
  43. x_vector = width - x1
  44. if y0 < 0:
  45. y_vector = -y0
  46. elif y1 > height:
  47. y_vector = height - y1
  48. x0 = int(x0 + x_vector)
  49. y0 = int(y0 + y_vector)
  50. return img[y0 : y0 + crop_size,
  51. x0 : x0 + crop_size]
  52. if __name__ == '__main__':
  53. file_name = sys.argv[1]
  54. print("Cropping:", file_name)
  55. rects, img = detect(file_name)
  56. thumb = cv2.resize(smart_crop(rects, img), (410, 410),
  57. fx=0, fy=0, interpolation=cv2.INTER_CUBIC)
  58. source = Path(file_name)
  59. cv2.imwrite(str(source.parent/"thumb"/source.name), thumb)