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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# このスクリプトのライセンスは、train_dreambooth.pyと同じくApache License 2.0とします
|
2 |
+
# (c) 2022 Kohya S. @kohya_ss
|
3 |
+
|
4 |
+
# 横長の画像から顔検出して正立するように回転し、そこを中心に正方形に切り出す
|
5 |
+
|
6 |
+
# v2: extract max face if multiple faces are found
|
7 |
+
# v3: add crop_ratio option
|
8 |
+
# v4: add multiple faces extraction and min/max size
|
9 |
+
|
10 |
+
import argparse
|
11 |
+
import math
|
12 |
+
import cv2
|
13 |
+
import glob
|
14 |
+
import os
|
15 |
+
from anime_face_detector import create_detector
|
16 |
+
from tqdm import tqdm
|
17 |
+
import numpy as np
|
18 |
+
from library.utils import setup_logging
|
19 |
+
setup_logging()
|
20 |
+
import logging
|
21 |
+
logger = logging.getLogger(__name__)
|
22 |
+
|
23 |
+
KP_REYE = 11
|
24 |
+
KP_LEYE = 19
|
25 |
+
|
26 |
+
SCORE_THRES = 0.90
|
27 |
+
|
28 |
+
|
29 |
+
def detect_faces(detector, image, min_size):
|
30 |
+
preds = detector(image) # bgr
|
31 |
+
# logger.info(len(preds))
|
32 |
+
|
33 |
+
faces = []
|
34 |
+
for pred in preds:
|
35 |
+
bb = pred['bbox']
|
36 |
+
score = bb[-1]
|
37 |
+
if score < SCORE_THRES:
|
38 |
+
continue
|
39 |
+
|
40 |
+
left, top, right, bottom = bb[:4]
|
41 |
+
cx = int((left + right) / 2)
|
42 |
+
cy = int((top + bottom) / 2)
|
43 |
+
fw = int(right - left)
|
44 |
+
fh = int(bottom - top)
|
45 |
+
|
46 |
+
lex, ley = pred['keypoints'][KP_LEYE, 0:2]
|
47 |
+
rex, rey = pred['keypoints'][KP_REYE, 0:2]
|
48 |
+
angle = math.atan2(ley - rey, lex - rex)
|
49 |
+
angle = angle / math.pi * 180
|
50 |
+
|
51 |
+
faces.append((cx, cy, fw, fh, angle))
|
52 |
+
|
53 |
+
faces.sort(key=lambda x: max(x[2], x[3]), reverse=True) # 大きい順
|
54 |
+
return faces
|
55 |
+
|
56 |
+
|
57 |
+
def rotate_image(image, angle, cx, cy):
|
58 |
+
h, w = image.shape[0:2]
|
59 |
+
rot_mat = cv2.getRotationMatrix2D((cx, cy), angle, 1.0)
|
60 |
+
|
61 |
+
# # 回転する分、すこし画像サイズを大きくする→とりあえず無効化
|
62 |
+
# nh = max(h, int(w * math.sin(angle)))
|
63 |
+
# nw = max(w, int(h * math.sin(angle)))
|
64 |
+
# if nh > h or nw > w:
|
65 |
+
# pad_y = nh - h
|
66 |
+
# pad_t = pad_y // 2
|
67 |
+
# pad_x = nw - w
|
68 |
+
# pad_l = pad_x // 2
|
69 |
+
# m = np.array([[0, 0, pad_l],
|
70 |
+
# [0, 0, pad_t]])
|
71 |
+
# rot_mat = rot_mat + m
|
72 |
+
# h, w = nh, nw
|
73 |
+
# cx += pad_l
|
74 |
+
# cy += pad_t
|
75 |
+
|
76 |
+
result = cv2.warpAffine(image, rot_mat, (w, h), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT)
|
77 |
+
return result, cx, cy
|
78 |
+
|
79 |
+
|
80 |
+
def process(args):
|
81 |
+
assert (not args.resize_fit) or args.resize_face_size is None, f"resize_fit and resize_face_size can't be specified both / resize_fitとresize_face_sizeはどちらか片方しか指定できません"
|
82 |
+
assert args.crop_ratio is None or args.resize_face_size is None, f"crop_ratio指定時はresize_face_sizeは指定できません"
|
83 |
+
|
84 |
+
# アニメ顔検出モデルを読み込む
|
85 |
+
logger.info("loading face detector.")
|
86 |
+
detector = create_detector('yolov3')
|
87 |
+
|
88 |
+
# cropの引数を解析する
|
89 |
+
if args.crop_size is None:
|
90 |
+
crop_width = crop_height = None
|
91 |
+
else:
|
92 |
+
tokens = args.crop_size.split(',')
|
93 |
+
assert len(tokens) == 2, f"crop_size must be 'width,height' / crop_sizeは'幅,高さ'で指定してください"
|
94 |
+
crop_width, crop_height = [int(t) for t in tokens]
|
95 |
+
|
96 |
+
if args.crop_ratio is None:
|
97 |
+
crop_h_ratio = crop_v_ratio = None
|
98 |
+
else:
|
99 |
+
tokens = args.crop_ratio.split(',')
|
100 |
+
assert len(tokens) == 2, f"crop_ratio must be 'horizontal,vertical' / crop_ratioは'幅,高さ'の倍率で指定してください"
|
101 |
+
crop_h_ratio, crop_v_ratio = [float(t) for t in tokens]
|
102 |
+
|
103 |
+
# 画像を処理する
|
104 |
+
logger.info("processing.")
|
105 |
+
output_extension = ".png"
|
106 |
+
|
107 |
+
os.makedirs(args.dst_dir, exist_ok=True)
|
108 |
+
paths = glob.glob(os.path.join(args.src_dir, "*.png")) + glob.glob(os.path.join(args.src_dir, "*.jpg")) + \
|
109 |
+
glob.glob(os.path.join(args.src_dir, "*.webp"))
|
110 |
+
for path in tqdm(paths):
|
111 |
+
basename = os.path.splitext(os.path.basename(path))[0]
|
112 |
+
|
113 |
+
# image = cv2.imread(path) # 日本語ファイル名でエラーになる
|
114 |
+
image = cv2.imdecode(np.fromfile(path, np.uint8), cv2.IMREAD_UNCHANGED)
|
115 |
+
if len(image.shape) == 2:
|
116 |
+
image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
|
117 |
+
if image.shape[2] == 4:
|
118 |
+
logger.warning(f"image has alpha. ignore / 画像の透明度が設定されているため無視します: {path}")
|
119 |
+
image = image[:, :, :3].copy() # copyをしないと内部的に透明度情報が付いたままになるらしい
|
120 |
+
|
121 |
+
h, w = image.shape[:2]
|
122 |
+
|
123 |
+
faces = detect_faces(detector, image, args.multiple_faces)
|
124 |
+
for i, face in enumerate(faces):
|
125 |
+
cx, cy, fw, fh, angle = face
|
126 |
+
face_size = max(fw, fh)
|
127 |
+
if args.min_size is not None and face_size < args.min_size:
|
128 |
+
continue
|
129 |
+
if args.max_size is not None and face_size >= args.max_size:
|
130 |
+
continue
|
131 |
+
face_suffix = f"_{i+1:02d}" if args.multiple_faces else ""
|
132 |
+
|
133 |
+
# オプション指定があれば回転する
|
134 |
+
face_img = image
|
135 |
+
if args.rotate:
|
136 |
+
face_img, cx, cy = rotate_image(face_img, angle, cx, cy)
|
137 |
+
|
138 |
+
# オプション指定があれば顔を中心に切り出す
|
139 |
+
if crop_width is not None or crop_h_ratio is not None:
|
140 |
+
cur_crop_width, cur_crop_height = crop_width, crop_height
|
141 |
+
if crop_h_ratio is not None:
|
142 |
+
cur_crop_width = int(face_size * crop_h_ratio + .5)
|
143 |
+
cur_crop_height = int(face_size * crop_v_ratio + .5)
|
144 |
+
|
145 |
+
# リサイズを必要なら行う
|
146 |
+
scale = 1.0
|
147 |
+
if args.resize_face_size is not None:
|
148 |
+
# 顔サイズを基準にリサイズする
|
149 |
+
scale = args.resize_face_size / face_size
|
150 |
+
if scale < cur_crop_width / w:
|
151 |
+
logger.warning(
|
152 |
+
f"image width too small in face size based resizing / 顔を基準にリサイズすると画像の幅がcrop sizeより小さい(顔が相対的に大きすぎる)ので顔サイズが変わります: {path}")
|
153 |
+
scale = cur_crop_width / w
|
154 |
+
if scale < cur_crop_height / h:
|
155 |
+
logger.warning(
|
156 |
+
f"image height too small in face size based resizing / 顔を基準にリサイズすると画像の高さがcrop sizeより小さい(顔が相対的に大きすぎる)ので顔サイズが変わります: {path}")
|
157 |
+
scale = cur_crop_height / h
|
158 |
+
elif crop_h_ratio is not None:
|
159 |
+
# 倍率指定の時にはリサイズしない
|
160 |
+
pass
|
161 |
+
else:
|
162 |
+
# 切り出しサイズ指定あり
|
163 |
+
if w < cur_crop_width:
|
164 |
+
logger.warning(f"image width too small/ 画像の幅がcrop sizeより小さいので画質が劣化します: {path}")
|
165 |
+
scale = cur_crop_width / w
|
166 |
+
if h < cur_crop_height:
|
167 |
+
logger.warning(f"image height too small/ 画像の高さがcrop sizeより小さいので画質が劣化します: {path}")
|
168 |
+
scale = cur_crop_height / h
|
169 |
+
if args.resize_fit:
|
170 |
+
scale = max(cur_crop_width / w, cur_crop_height / h)
|
171 |
+
|
172 |
+
if scale != 1.0:
|
173 |
+
w = int(w * scale + .5)
|
174 |
+
h = int(h * scale + .5)
|
175 |
+
face_img = cv2.resize(face_img, (w, h), interpolation=cv2.INTER_AREA if scale < 1.0 else cv2.INTER_LANCZOS4)
|
176 |
+
cx = int(cx * scale + .5)
|
177 |
+
cy = int(cy * scale + .5)
|
178 |
+
fw = int(fw * scale + .5)
|
179 |
+
fh = int(fh * scale + .5)
|
180 |
+
|
181 |
+
cur_crop_width = min(cur_crop_width, face_img.shape[1])
|
182 |
+
cur_crop_height = min(cur_crop_height, face_img.shape[0])
|
183 |
+
|
184 |
+
x = cx - cur_crop_width // 2
|
185 |
+
cx = cur_crop_width // 2
|
186 |
+
if x < 0:
|
187 |
+
cx = cx + x
|
188 |
+
x = 0
|
189 |
+
elif x + cur_crop_width > w:
|
190 |
+
cx = cx + (x + cur_crop_width - w)
|
191 |
+
x = w - cur_crop_width
|
192 |
+
face_img = face_img[:, x:x+cur_crop_width]
|
193 |
+
|
194 |
+
y = cy - cur_crop_height // 2
|
195 |
+
cy = cur_crop_height // 2
|
196 |
+
if y < 0:
|
197 |
+
cy = cy + y
|
198 |
+
y = 0
|
199 |
+
elif y + cur_crop_height > h:
|
200 |
+
cy = cy + (y + cur_crop_height - h)
|
201 |
+
y = h - cur_crop_height
|
202 |
+
face_img = face_img[y:y + cur_crop_height]
|
203 |
+
|
204 |
+
# # debug
|
205 |
+
# logger.info(path, cx, cy, angle)
|
206 |
+
# crp = cv2.resize(image, (image.shape[1]//8, image.shape[0]//8))
|
207 |
+
# cv2.imshow("image", crp)
|
208 |
+
# if cv2.waitKey() == 27:
|
209 |
+
# break
|
210 |
+
# cv2.destroyAllWindows()
|
211 |
+
|
212 |
+
# debug
|
213 |
+
if args.debug:
|
214 |
+
cv2.rectangle(face_img, (cx-fw//2, cy-fh//2), (cx+fw//2, cy+fh//2), (255, 0, 255), fw//20)
|
215 |
+
|
216 |
+
_, buf = cv2.imencode(output_extension, face_img)
|
217 |
+
with open(os.path.join(args.dst_dir, f"{basename}{face_suffix}_{cx:04d}_{cy:04d}_{fw:04d}_{fh:04d}{output_extension}"), "wb") as f:
|
218 |
+
buf.tofile(f)
|
219 |
+
|
220 |
+
|
221 |
+
def setup_parser() -> argparse.ArgumentParser:
|
222 |
+
parser = argparse.ArgumentParser()
|
223 |
+
parser.add_argument("--src_dir", type=str, help="directory to load images / 画像を読み込むディレクトリ")
|
224 |
+
parser.add_argument("--dst_dir", type=str, help="directory to save images / 画像を保存するディレクトリ")
|
225 |
+
parser.add_argument("--rotate", action="store_true", help="rotate images to align faces / 顔が正立するように画像を回転する")
|
226 |
+
parser.add_argument("--resize_fit", action="store_true",
|
227 |
+
help="resize to fit smaller side after cropping / 切り出し後の画像の短辺がcrop_sizeにあうようにリサイズする")
|
228 |
+
parser.add_argument("--resize_face_size", type=int, default=None,
|
229 |
+
help="resize image before cropping by face size / 切り出し前に顔がこのサイズになるようにリサイズする")
|
230 |
+
parser.add_argument("--crop_size", type=str, default=None,
|
231 |
+
help="crop images with 'width,height' pixels, face centered / 顔を中心として'幅,高さ'のサイズで切り出す")
|
232 |
+
parser.add_argument("--crop_ratio", type=str, default=None,
|
233 |
+
help="crop images with 'horizontal,vertical' ratio to face, face centered / 顔を中心として顔サイズの'幅倍率,高さ倍率'のサイズで切り出す")
|
234 |
+
parser.add_argument("--min_size", type=int, default=None,
|
235 |
+
help="minimum face size to output (included) / 処理対象とする顔の最小サイズ(この値以上)")
|
236 |
+
parser.add_argument("--max_size", type=int, default=None,
|
237 |
+
help="maximum face size to output (excluded) / 処理対象とする顔の最大サイズ(この値未満)")
|
238 |
+
parser.add_argument("--multiple_faces", action="store_true",
|
239 |
+
help="output each faces / 複数の顔が見つかった場合、それぞれを切り出す")
|
240 |
+
parser.add_argument("--debug", action="store_true", help="render rect for face / 処理後画像の顔位置に矩形を描画します")
|
241 |
+
|
242 |
+
return parser
|
243 |
+
|
244 |
+
|
245 |
+
if __name__ == '__main__':
|
246 |
+
parser = setup_parser()
|
247 |
+
|
248 |
+
args = parser.parse_args()
|
249 |
+
|
250 |
+
process(args)
|