回答編集履歴

2

d

2020/01/14 09:36

投稿

tiitoi
tiitoi

スコア21956

test CHANGED
@@ -161,3 +161,145 @@
161
161
 
162
162
 
163
163
  ![イメージ説明](dcbf642c807688b474d4068f4863b226.png)
164
+
165
+
166
+
167
+ ## 追記
168
+
169
+
170
+
171
+ 1. アスペクト比を固定して、短辺をサムネイル枠に合わせてリサイズする。
172
+
173
+ 2. リサイズした画像を、画像の中心を基準にして、サムネイル枠に合わせてクロップする。
174
+
175
+
176
+
177
+ ![イメージ説明](d01d3d920e5fc7ce868d19e45279c92a.png)
178
+
179
+
180
+
181
+ ```python
182
+
183
+ from pathlib import Path
184
+
185
+
186
+
187
+ from PIL import Image
188
+
189
+
190
+
191
+
192
+
193
+ def get_img_paths(img_dir):
194
+
195
+ """画像のパスを取得する。
196
+
197
+ """
198
+
199
+ IMG_EXTENSIONS = (".jpg", ".jpeg", ".png", ".bmp")
200
+
201
+ img_paths = [p for p in img_dir.iterdir() if p.suffix in IMG_EXTENSIONS]
202
+
203
+
204
+
205
+ return img_paths
206
+
207
+
208
+
209
+
210
+
211
+ def resize(img, box_size):
212
+
213
+ box_width, box_height = box_size
214
+
215
+ scale_x = box_width / img.width
216
+
217
+ scale_y = box_height / img.height
218
+
219
+ scale = max(scale_x, scale_y)
220
+
221
+
222
+
223
+ # リサイズ後の大きさを計算する。
224
+
225
+ if scale_x > scale_y:
226
+
227
+ new_width = box_width
228
+
229
+ new_height = int(img.height * scale)
230
+
231
+ else:
232
+
233
+ new_width = int(img.width * scale)
234
+
235
+ new_height = box_height
236
+
237
+
238
+
239
+ # リサイズする。
240
+
241
+ resized = img.resize((new_width, new_height))
242
+
243
+
244
+
245
+ # 中心で切り抜く
246
+
247
+ left = (new_width - box_width) // 2
248
+
249
+ top = (new_height - box_height) // 2
250
+
251
+ right = (new_width + box_width) // 2
252
+
253
+ bottom = (new_height + box_height) // 2
254
+
255
+ cropped = resized.crop((left, top, right, bottom))
256
+
257
+ return cropped
258
+
259
+
260
+
261
+
262
+
263
+ box_size = (800, 400) # サムネイルの大きさ
264
+
265
+ input_dir = Path("samples")
266
+
267
+ output_dir = Path("resized")
268
+
269
+ output_dir.mkdir(exist_ok=True)
270
+
271
+
272
+
273
+ for path in get_img_paths(input_dir):
274
+
275
+ # 画像を読み込む。
276
+
277
+ img = Image.open(path)
278
+
279
+
280
+
281
+ # リサイズする。
282
+
283
+ resized = resize(img, box_size)
284
+
285
+ print(f"{path.name}: {img.size} --> {resized.size}")
286
+
287
+
288
+
289
+ # 保存する。
290
+
291
+ resized.save(output_dir / path.name)
292
+
293
+ ```
294
+
295
+
296
+
297
+ ![イメージ説明](e979a290fb9f1892b0331d1607cd0372.png)
298
+
299
+
300
+
301
+
302
+
303
+
304
+
305
+ ![イメージ説明](178c6059eaa1ca4691754ed87f5a89cd.png)

1

d

2020/01/14 09:36

投稿

tiitoi
tiitoi

スコア21956

test CHANGED
@@ -16,7 +16,7 @@
16
16
 
17
17
 
18
18
 
19
- という制約条件を満たす scale 最大値を求めるという問題になります。
19
+ という制約条件を満たす scale 最大問題になります。
20
20
 
21
21
  変形すると、
22
22