Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
TheLastBen
GitHub Repository: TheLastBen/fast-stable-diffusion
Path: blob/main/Dreambooth/smart_crop.py
540 views
1
#Based on A1111 cropping script
2
import cv2
3
import os
4
from math import log, sqrt
5
import numpy as np
6
from PIL import Image, ImageDraw
7
8
GREEN = "#0F0"
9
BLUE = "#00F"
10
RED = "#F00"
11
12
13
def crop_image(im, size):
14
15
def focal_point(im, settings):
16
corner_points = image_corner_points(im, settings) if settings.corner_points_weight > 0 else []
17
entropy_points = image_entropy_points(im, settings) if settings.entropy_points_weight > 0 else []
18
face_points = image_face_points(im, settings) if settings.face_points_weight > 0 else []
19
20
pois = []
21
22
weight_pref_total = 0
23
if len(corner_points) > 0:
24
weight_pref_total += settings.corner_points_weight
25
if len(entropy_points) > 0:
26
weight_pref_total += settings.entropy_points_weight
27
if len(face_points) > 0:
28
weight_pref_total += settings.face_points_weight
29
30
corner_centroid = None
31
if len(corner_points) > 0:
32
corner_centroid = centroid(corner_points)
33
corner_centroid.weight = settings.corner_points_weight / weight_pref_total
34
pois.append(corner_centroid)
35
36
entropy_centroid = None
37
if len(entropy_points) > 0:
38
entropy_centroid = centroid(entropy_points)
39
entropy_centroid.weight = settings.entropy_points_weight / weight_pref_total
40
pois.append(entropy_centroid)
41
42
face_centroid = None
43
if len(face_points) > 0:
44
face_centroid = centroid(face_points)
45
face_centroid.weight = settings.face_points_weight / weight_pref_total
46
pois.append(face_centroid)
47
48
average_point = poi_average(pois, settings)
49
50
return average_point
51
52
53
def image_face_points(im, settings):
54
55
np_im = np.array(im)
56
gray = cv2.cvtColor(np_im, cv2.COLOR_BGR2GRAY)
57
58
tries = [
59
[ f'{cv2.data.haarcascades}haarcascade_eye.xml', 0.01 ],
60
[ f'{cv2.data.haarcascades}haarcascade_frontalface_default.xml', 0.05 ],
61
[ f'{cv2.data.haarcascades}haarcascade_profileface.xml', 0.05 ],
62
[ f'{cv2.data.haarcascades}haarcascade_frontalface_alt.xml', 0.05 ],
63
[ f'{cv2.data.haarcascades}haarcascade_frontalface_alt2.xml', 0.05 ],
64
[ f'{cv2.data.haarcascades}haarcascade_frontalface_alt_tree.xml', 0.05 ],
65
[ f'{cv2.data.haarcascades}haarcascade_eye_tree_eyeglasses.xml', 0.05 ],
66
[ f'{cv2.data.haarcascades}haarcascade_upperbody.xml', 0.05 ]
67
]
68
for t in tries:
69
classifier = cv2.CascadeClassifier(t[0])
70
minsize = int(min(im.width, im.height) * t[1]) # at least N percent of the smallest side
71
try:
72
faces = classifier.detectMultiScale(gray, scaleFactor=1.1,
73
minNeighbors=7, minSize=(minsize, minsize), flags=cv2.CASCADE_SCALE_IMAGE)
74
except:
75
continue
76
77
if len(faces) > 0:
78
rects = [[f[0], f[1], f[0] + f[2], f[1] + f[3]] for f in faces]
79
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]
80
return []
81
82
83
def image_corner_points(im, settings):
84
grayscale = im.convert("L")
85
86
# naive attempt at preventing focal points from collecting at watermarks near the bottom
87
gd = ImageDraw.Draw(grayscale)
88
gd.rectangle([0, im.height*.9, im.width, im.height], fill="#999")
89
90
np_im = np.array(grayscale)
91
92
points = cv2.goodFeaturesToTrack(
93
np_im,
94
maxCorners=100,
95
qualityLevel=0.04,
96
minDistance=min(grayscale.width, grayscale.height)*0.06,
97
useHarrisDetector=False,
98
)
99
100
if points is None:
101
return []
102
103
focal_points = []
104
for point in points:
105
x, y = point.ravel()
106
focal_points.append(PointOfInterest(x, y, size=4, weight=1/len(points)))
107
108
return focal_points
109
110
111
def image_entropy_points(im, settings):
112
landscape = im.height < im.width
113
portrait = im.height > im.width
114
if landscape:
115
move_idx = [0, 2]
116
move_max = im.size[0]
117
elif portrait:
118
move_idx = [1, 3]
119
move_max = im.size[1]
120
else:
121
return []
122
123
e_max = 0
124
crop_current = [0, 0, settings.crop_width, settings.crop_height]
125
crop_best = crop_current
126
while crop_current[move_idx[1]] < move_max:
127
crop = im.crop(tuple(crop_current))
128
e = image_entropy(crop)
129
130
if (e > e_max):
131
e_max = e
132
crop_best = list(crop_current)
133
134
crop_current[move_idx[0]] += 4
135
crop_current[move_idx[1]] += 4
136
137
x_mid = int(crop_best[0] + settings.crop_width/2)
138
y_mid = int(crop_best[1] + settings.crop_height/2)
139
140
return [PointOfInterest(x_mid, y_mid, size=25, weight=1.0)]
141
142
143
def image_entropy(im):
144
# greyscale image entropy
145
# band = np.asarray(im.convert("L"))
146
band = np.asarray(im.convert("1"), dtype=np.uint8)
147
hist, _ = np.histogram(band, bins=range(0, 256))
148
hist = hist[hist > 0]
149
return -np.log2(hist / hist.sum()).sum()
150
151
def centroid(pois):
152
x = [poi.x for poi in pois]
153
y = [poi.y for poi in pois]
154
return PointOfInterest(sum(x)/len(pois), sum(y)/len(pois))
155
156
157
def poi_average(pois, settings):
158
weight = 0.0
159
x = 0.0
160
y = 0.0
161
for poi in pois:
162
weight += poi.weight
163
x += poi.x * poi.weight
164
y += poi.y * poi.weight
165
avg_x = round(weight and x / weight)
166
avg_y = round(weight and y / weight)
167
168
return PointOfInterest(avg_x, avg_y)
169
170
171
def is_landscape(w, h):
172
return w > h
173
174
175
def is_portrait(w, h):
176
return h > w
177
178
179
def is_square(w, h):
180
return w == h
181
182
183
class PointOfInterest:
184
def __init__(self, x, y, weight=1.0, size=10):
185
self.x = x
186
self.y = y
187
self.weight = weight
188
self.size = size
189
190
def bounding(self, size):
191
return [
192
self.x - size//2,
193
self.y - size//2,
194
self.x + size//2,
195
self.y + size//2
196
]
197
198
class Settings:
199
def __init__(self, crop_width=512, crop_height=512, corner_points_weight=0.5, entropy_points_weight=0.5, face_points_weight=0.5):
200
self.crop_width = crop_width
201
self.crop_height = crop_height
202
self.corner_points_weight = corner_points_weight
203
self.entropy_points_weight = entropy_points_weight
204
self.face_points_weight = face_points_weight
205
206
settings = Settings(
207
crop_width = size,
208
crop_height = size,
209
face_points_weight = 0.9,
210
entropy_points_weight = 0.15,
211
corner_points_weight = 0.5,
212
)
213
214
scale_by = 1
215
if is_landscape(im.width, im.height):
216
scale_by = settings.crop_height / im.height
217
elif is_portrait(im.width, im.height):
218
scale_by = settings.crop_width / im.width
219
elif is_square(im.width, im.height):
220
if is_square(settings.crop_width, settings.crop_height):
221
scale_by = settings.crop_width / im.width
222
elif is_landscape(settings.crop_width, settings.crop_height):
223
scale_by = settings.crop_width / im.width
224
elif is_portrait(settings.crop_width, settings.crop_height):
225
scale_by = settings.crop_height / im.height
226
227
im = im.resize((int(im.width * scale_by), int(im.height * scale_by)))
228
im_debug = im.copy()
229
230
focus = focal_point(im_debug, settings)
231
232
# take the focal point and turn it into crop coordinates that try to center over the focal
233
# point but then get adjusted back into the frame
234
y_half = int(settings.crop_height / 2)
235
x_half = int(settings.crop_width / 2)
236
237
x1 = focus.x - x_half
238
if x1 < 0:
239
x1 = 0
240
elif x1 + settings.crop_width > im.width:
241
x1 = im.width - settings.crop_width
242
243
y1 = focus.y - y_half
244
if y1 < 0:
245
y1 = 0
246
elif y1 + settings.crop_height > im.height:
247
y1 = im.height - settings.crop_height
248
249
x2 = x1 + settings.crop_width
250
y2 = y1 + settings.crop_height
251
252
crop = [x1, y1, x2, y2]
253
254
results = []
255
256
results.append(im.crop(tuple(crop)))
257
258
return results
259
260