thumbnailer.py 2.0 KB

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