autocrop.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. import cv2
  2. import requests
  3. import os
  4. import numpy as np
  5. from PIL import ImageDraw
  6. GREEN = "#0F0"
  7. BLUE = "#00F"
  8. RED = "#F00"
  9. def crop_image(im, settings):
  10. """ Intelligently crop an image to the subject matter """
  11. scale_by = 1
  12. if is_landscape(im.width, im.height):
  13. scale_by = settings.crop_height / im.height
  14. elif is_portrait(im.width, im.height):
  15. scale_by = settings.crop_width / im.width
  16. elif is_square(im.width, im.height):
  17. if is_square(settings.crop_width, settings.crop_height):
  18. scale_by = settings.crop_width / im.width
  19. elif is_landscape(settings.crop_width, settings.crop_height):
  20. scale_by = settings.crop_width / im.width
  21. elif is_portrait(settings.crop_width, settings.crop_height):
  22. scale_by = settings.crop_height / im.height
  23. im = im.resize((int(im.width * scale_by), int(im.height * scale_by)))
  24. im_debug = im.copy()
  25. focus = focal_point(im_debug, settings)
  26. # take the focal point and turn it into crop coordinates that try to center over the focal
  27. # point but then get adjusted back into the frame
  28. y_half = int(settings.crop_height / 2)
  29. x_half = int(settings.crop_width / 2)
  30. x1 = focus.x - x_half
  31. if x1 < 0:
  32. x1 = 0
  33. elif x1 + settings.crop_width > im.width:
  34. x1 = im.width - settings.crop_width
  35. y1 = focus.y - y_half
  36. if y1 < 0:
  37. y1 = 0
  38. elif y1 + settings.crop_height > im.height:
  39. y1 = im.height - settings.crop_height
  40. x2 = x1 + settings.crop_width
  41. y2 = y1 + settings.crop_height
  42. crop = [x1, y1, x2, y2]
  43. results = []
  44. results.append(im.crop(tuple(crop)))
  45. if settings.annotate_image:
  46. d = ImageDraw.Draw(im_debug)
  47. rect = list(crop)
  48. rect[2] -= 1
  49. rect[3] -= 1
  50. d.rectangle(rect, outline=GREEN)
  51. results.append(im_debug)
  52. if settings.destop_view_image:
  53. im_debug.show()
  54. return results
  55. def focal_point(im, settings):
  56. corner_points = image_corner_points(im, settings) if settings.corner_points_weight > 0 else []
  57. entropy_points = image_entropy_points(im, settings) if settings.entropy_points_weight > 0 else []
  58. face_points = image_face_points(im, settings) if settings.face_points_weight > 0 else []
  59. pois = []
  60. weight_pref_total = 0
  61. if corner_points:
  62. weight_pref_total += settings.corner_points_weight
  63. if entropy_points:
  64. weight_pref_total += settings.entropy_points_weight
  65. if face_points:
  66. weight_pref_total += settings.face_points_weight
  67. corner_centroid = None
  68. if corner_points:
  69. corner_centroid = centroid(corner_points)
  70. corner_centroid.weight = settings.corner_points_weight / weight_pref_total
  71. pois.append(corner_centroid)
  72. entropy_centroid = None
  73. if entropy_points:
  74. entropy_centroid = centroid(entropy_points)
  75. entropy_centroid.weight = settings.entropy_points_weight / weight_pref_total
  76. pois.append(entropy_centroid)
  77. face_centroid = None
  78. if face_points:
  79. face_centroid = centroid(face_points)
  80. face_centroid.weight = settings.face_points_weight / weight_pref_total
  81. pois.append(face_centroid)
  82. average_point = poi_average(pois, settings)
  83. if settings.annotate_image:
  84. d = ImageDraw.Draw(im)
  85. max_size = min(im.width, im.height) * 0.07
  86. if corner_centroid is not None:
  87. color = BLUE
  88. box = corner_centroid.bounding(max_size * corner_centroid.weight)
  89. d.text((box[0], box[1]-15), f"Edge: {corner_centroid.weight:.02f}", fill=color)
  90. d.ellipse(box, outline=color)
  91. if len(corner_points) > 1:
  92. for f in corner_points:
  93. d.rectangle(f.bounding(4), outline=color)
  94. if entropy_centroid is not None:
  95. color = "#ff0"
  96. box = entropy_centroid.bounding(max_size * entropy_centroid.weight)
  97. d.text((box[0], box[1]-15), f"Entropy: {entropy_centroid.weight:.02f}", fill=color)
  98. d.ellipse(box, outline=color)
  99. if len(entropy_points) > 1:
  100. for f in entropy_points:
  101. d.rectangle(f.bounding(4), outline=color)
  102. if face_centroid is not None:
  103. color = RED
  104. box = face_centroid.bounding(max_size * face_centroid.weight)
  105. d.text((box[0], box[1]-15), f"Face: {face_centroid.weight:.02f}", fill=color)
  106. d.ellipse(box, outline=color)
  107. if len(face_points) > 1:
  108. for f in face_points:
  109. d.rectangle(f.bounding(4), outline=color)
  110. d.ellipse(average_point.bounding(max_size), outline=GREEN)
  111. return average_point
  112. def image_face_points(im, settings):
  113. if settings.dnn_model_path is not None:
  114. detector = cv2.FaceDetectorYN.create(
  115. settings.dnn_model_path,
  116. "",
  117. (im.width, im.height),
  118. 0.9, # score threshold
  119. 0.3, # nms threshold
  120. 5000 # keep top k before nms
  121. )
  122. faces = detector.detect(np.array(im))
  123. results = []
  124. if faces[1] is not None:
  125. for face in faces[1]:
  126. x = face[0]
  127. y = face[1]
  128. w = face[2]
  129. h = face[3]
  130. results.append(
  131. PointOfInterest(
  132. int(x + (w * 0.5)), # face focus left/right is center
  133. int(y + (h * 0.33)), # face focus up/down is close to the top of the head
  134. size = w,
  135. weight = 1/len(faces[1])
  136. )
  137. )
  138. return results
  139. else:
  140. np_im = np.array(im)
  141. gray = cv2.cvtColor(np_im, cv2.COLOR_BGR2GRAY)
  142. tries = [
  143. [ f'{cv2.data.haarcascades}haarcascade_eye.xml', 0.01 ],
  144. [ f'{cv2.data.haarcascades}haarcascade_frontalface_default.xml', 0.05 ],
  145. [ f'{cv2.data.haarcascades}haarcascade_profileface.xml', 0.05 ],
  146. [ f'{cv2.data.haarcascades}haarcascade_frontalface_alt.xml', 0.05 ],
  147. [ f'{cv2.data.haarcascades}haarcascade_frontalface_alt2.xml', 0.05 ],
  148. [ f'{cv2.data.haarcascades}haarcascade_frontalface_alt_tree.xml', 0.05 ],
  149. [ f'{cv2.data.haarcascades}haarcascade_eye_tree_eyeglasses.xml', 0.05 ],
  150. [ f'{cv2.data.haarcascades}haarcascade_upperbody.xml', 0.05 ]
  151. ]
  152. for t in tries:
  153. classifier = cv2.CascadeClassifier(t[0])
  154. minsize = int(min(im.width, im.height) * t[1]) # at least N percent of the smallest side
  155. try:
  156. faces = classifier.detectMultiScale(gray, scaleFactor=1.1,
  157. minNeighbors=7, minSize=(minsize, minsize), flags=cv2.CASCADE_SCALE_IMAGE)
  158. except Exception:
  159. continue
  160. if faces:
  161. rects = [[f[0], f[1], f[0] + f[2], f[1] + f[3]] for f in faces]
  162. return [PointOfInterest((r[0] +r[2]) // 2, (r[1] + r[3]) // 2, size=abs(r[0]-r[2]), weight=1/len(rects)) for r in rects]
  163. return []
  164. def image_corner_points(im, settings):
  165. grayscale = im.convert("L")
  166. # naive attempt at preventing focal points from collecting at watermarks near the bottom
  167. gd = ImageDraw.Draw(grayscale)
  168. gd.rectangle([0, im.height*.9, im.width, im.height], fill="#999")
  169. np_im = np.array(grayscale)
  170. points = cv2.goodFeaturesToTrack(
  171. np_im,
  172. maxCorners=100,
  173. qualityLevel=0.04,
  174. minDistance=min(grayscale.width, grayscale.height)*0.06,
  175. useHarrisDetector=False,
  176. )
  177. if points is None:
  178. return []
  179. focal_points = []
  180. for point in points:
  181. x, y = point.ravel()
  182. focal_points.append(PointOfInterest(x, y, size=4, weight=1/len(points)))
  183. return focal_points
  184. def image_entropy_points(im, settings):
  185. landscape = im.height < im.width
  186. portrait = im.height > im.width
  187. if landscape:
  188. move_idx = [0, 2]
  189. move_max = im.size[0]
  190. elif portrait:
  191. move_idx = [1, 3]
  192. move_max = im.size[1]
  193. else:
  194. return []
  195. e_max = 0
  196. crop_current = [0, 0, settings.crop_width, settings.crop_height]
  197. crop_best = crop_current
  198. while crop_current[move_idx[1]] < move_max:
  199. crop = im.crop(tuple(crop_current))
  200. e = image_entropy(crop)
  201. if (e > e_max):
  202. e_max = e
  203. crop_best = list(crop_current)
  204. crop_current[move_idx[0]] += 4
  205. crop_current[move_idx[1]] += 4
  206. x_mid = int(crop_best[0] + settings.crop_width/2)
  207. y_mid = int(crop_best[1] + settings.crop_height/2)
  208. return [PointOfInterest(x_mid, y_mid, size=25, weight=1.0)]
  209. def image_entropy(im):
  210. # greyscale image entropy
  211. # band = np.asarray(im.convert("L"))
  212. band = np.asarray(im.convert("1"), dtype=np.uint8)
  213. hist, _ = np.histogram(band, bins=range(0, 256))
  214. hist = hist[hist > 0]
  215. return -np.log2(hist / hist.sum()).sum()
  216. def centroid(pois):
  217. x = [poi.x for poi in pois]
  218. y = [poi.y for poi in pois]
  219. return PointOfInterest(sum(x) / len(pois), sum(y) / len(pois))
  220. def poi_average(pois, settings):
  221. weight = 0.0
  222. x = 0.0
  223. y = 0.0
  224. for poi in pois:
  225. weight += poi.weight
  226. x += poi.x * poi.weight
  227. y += poi.y * poi.weight
  228. avg_x = round(weight and x / weight)
  229. avg_y = round(weight and y / weight)
  230. return PointOfInterest(avg_x, avg_y)
  231. def is_landscape(w, h):
  232. return w > h
  233. def is_portrait(w, h):
  234. return h > w
  235. def is_square(w, h):
  236. return w == h
  237. def download_and_cache_models(dirname):
  238. download_url = 'https://github.com/opencv/opencv_zoo/blob/91fb0290f50896f38a0ab1e558b74b16bc009428/models/face_detection_yunet/face_detection_yunet_2022mar.onnx?raw=true'
  239. model_file_name = 'face_detection_yunet.onnx'
  240. os.makedirs(dirname, exist_ok=True)
  241. cache_file = os.path.join(dirname, model_file_name)
  242. if not os.path.exists(cache_file):
  243. print(f"downloading face detection model from '{download_url}' to '{cache_file}'")
  244. response = requests.get(download_url)
  245. with open(cache_file, "wb") as f:
  246. f.write(response.content)
  247. if os.path.exists(cache_file):
  248. return cache_file
  249. return None
  250. class PointOfInterest:
  251. def __init__(self, x, y, weight=1.0, size=10):
  252. self.x = x
  253. self.y = y
  254. self.weight = weight
  255. self.size = size
  256. def bounding(self, size):
  257. return [
  258. self.x - size // 2,
  259. self.y - size // 2,
  260. self.x + size // 2,
  261. self.y + size // 2
  262. ]
  263. class Settings:
  264. def __init__(self, crop_width=512, crop_height=512, corner_points_weight=0.5, entropy_points_weight=0.5, face_points_weight=0.5, annotate_image=False, dnn_model_path=None):
  265. self.crop_width = crop_width
  266. self.crop_height = crop_height
  267. self.corner_points_weight = corner_points_weight
  268. self.entropy_points_weight = entropy_points_weight
  269. self.face_points_weight = face_points_weight
  270. self.annotate_image = annotate_image
  271. self.destop_view_image = False
  272. self.dnn_model_path = dnn_model_path