この最適化問題を解く手順は以下のようになります:
1. 前処理・基本情報の計算
code
rect_width = x2 - x1
rect_height = y2 - y1
rect_area = rect_width * rect_height
2. 関心領域を含む最小クロップサイズの計算
code
min_crop_width = ceil(rect_width / 64) * 64
min_crop_height = ceil(rect_height / 64) * 64
3. 制約条件の適用
code
# 短辺制約の適用
if min(min_crop_width, min_crop_height) < min_length:
if min_crop_width < min_crop_height:
min_crop_width = ceil(min_length / 64) * 64
else:
min_crop_height = ceil(min_length / 64) * 64
# 長辺制約のチェック
needs_scaling = max(min_crop_width, min_crop_height) > max_length
4. クロップ候補の生成
64の倍数制約下で以下の範囲でクロップサイズを生成:
- 幅の範囲:min_crop_width から 画像幅(または制約により決まる上限)
- 高さの範囲:min_crop_height から 画像高さ(または制約により決まる上限)
5. 各候補の評価
各クロップサイズ候補について:
code
crop_area = crop_width * crop_height
occupation_ratio = rect_area / crop_area
# 制約チェック
- 関心領域を完全に含むか
- 短辺 >= min_length
- 長辺 <= max_length(縮小考慮)
- 画像境界内に収まるか
6. 最適解の選択
最大の occupation_ratio を持つクロップ領域を選択
7. 画像縮小の適用(必要な場合)
選択されたクロップ領域の長辺がmax_lengthを超える場合:
code
scale_factor = max_length / max(crop_width, crop_height)
# 元画像とクロップ領域を同じ比率で縮小
この手順により、制約条件を満たしながら関心領域の占有率が最大となるクロップ領域を効率的に求めることができます。
import math
from typing import Tuple, Optional, Dict, Any
def find_optimal_crop(
image_width: int,
image_height: int,
rect_x1: int,
rect_y1: int,
rect_x2: int,
rect_y2: int,
min_length: int,
max_length: int
) -> Dict[str, Any]:
"""
関心領域の占有率が最大となるクロップ領域を求める
Args:
image_width: 画像の幅
image_height: 画像の高さ
rect_x1, rect_y1, rect_x2, rect_y2: 関心領域の座標
min_length: クロップ領域の短辺の最小値
max_length: クロップ領域の長辺の最大値
Returns:
最適なクロップ情報を含む辞書
"""
# 1. 入力検証
if rect_x2 <= rect_x1 or rect_y2 <= rect_y1:
raise ValueError("無効な関心領域座標")
if rect_x1 < 0 or rect_y1 < 0 or rect_x2 > image_width or rect_y2 > image_height:
raise ValueError("関心領域が画像境界外")
# 2. 基本情報の計算
rect_width = rect_x2 - rect_x1
rect_height = rect_y2 - rect_y1
rect_area = rect_width * rect_height
print(f"関心領域: {rect_width}x{rect_height}, 面積: {rect_area}")
# 3. 関心領域を含む最小クロップサイズ(64の倍数)
min_crop_width = math.ceil(rect_width / 64) * 64
min_crop_height = math.ceil(rect_height / 64) * 64
print(f"最小クロップサイズ: {min_crop_width}x{min_crop_height}")
# 4. 短辺制約の適用
if min(min_crop_width, min_crop_height) < min_length:
min_length_64 = math.ceil(min_length / 64) * 64
if min_crop_width < min_crop_height:
min_crop_width = max(min_crop_width, min_length_64)
else:
min_crop_height = max(min_crop_height, min_length_64)
print(f"短辺制約適用後: {min_crop_width}x{min_crop_height}")
# 5. クロップ候補の生成と評価
best_crop = None
best_ratio = 0
best_scale = 1.0
# 幅の候補範囲
max_crop_width = min(image_width, max_length)
max_crop_width = (max_crop_width // 64) * 64
# 高さの候補範囲
max_crop_height = min(image_height, max_length)
max_crop_height = (max_crop_height // 64) * 64
print(f"探索範囲: 幅 {min_crop_width}-{max_crop_width}, 高さ {min_crop_height}-{max_crop_height}")
candidates_checked = 0
for crop_width in range(min_crop_width, max_crop_width + 1, 64):
for crop_height in range(min_crop_height, max_crop_height + 1, 64):
candidates_checked += 1
# 制約チェック
if not _is_valid_crop(crop_width, crop_height, rect_width, rect_height,
min_length, max_length, image_width, image_height):
continue
# 縮小が必要か判定
scale_factor = 1.0
actual_long_side = max(crop_width, crop_height)
if actual_long_side > max_length:
scale_factor = max_length / actual_long_side
# 占有率計算
crop_area = crop_width * crop_height
occupation_ratio = rect_area / crop_area
if occupation_ratio > best_ratio:
best_ratio = occupation_ratio
best_scale = scale_factor
best_crop = {
'crop_width': crop_width,
'crop_height': crop_height,
'crop_area': crop_area,
'occupation_ratio': occupation_ratio,
'scale_factor': scale_factor,
'final_width': int(crop_width * scale_factor),
'final_height': int(crop_height * scale_factor)
}
print(f"検証した候補数: {candidates_checked}")
if best_crop is None:
raise RuntimeError("有効なクロップ領域が見つかりません")
return best_crop
def _is_valid_crop(crop_width: int, crop_height: int, rect_width: int, rect_height: int,
min_length: int, max_length: int, image_width: int, image_height: int) -> bool:
"""クロップ領域が制約条件を満たすかチェック"""
# 関心領域を含むか
if crop_width < rect_width or crop_height < rect_height:
return False
# 短辺制約
if min(crop_width, crop_height) < min_length:
return False
# 画像境界内か
if crop_width > image_width or crop_height > image_height:
return False
# 長辺制約(縮小考慮)
long_side = max(crop_width, crop_height)
if long_side > max_length:
# 縮小後も制約を満たすかチェック
scale_factor = max_length / long_side
scaled_short_side = min(crop_width, crop_height) * scale_factor
if scaled_short_side < min_length:
return False
return True
def calculate_crop_position(image_width: int, image_height: int,
crop_width: int, crop_height: int,
rect_x1: int, rect_y1: int, rect_x2: int, rect_y2: int) -> Tuple[int, int]:
"""
関心領域を中央に配置するクロップ位置を計算
"""
rect_center_x = (rect_x1 + rect_x2) // 2
rect_center_y = (rect_y1 + rect_y2) // 2
crop_x = max(0, min(image_width - crop_width, rect_center_x - crop_width // 2))
crop_y = max(0, min(image_height - crop_height, rect_center_y - crop_height // 2))
return crop_x, crop_y
# テスト用の実装例
def test_optimal_crop():
"""テスト関数"""
# テストケース1: 基本的なケース
print("=" * 50)
print("テストケース1: 基本的なケース")
print("=" * 50)
result = find_optimal_crop(
image_width=1920,
image_height=1080,
rect_x1=100, rect_y1=100, rect_x2=300, rect_y2=200, # 200x100の関心領域
min_length=256,
max_length=512
)
print(f"最適解:")
print(f" クロップサイズ: {result['crop_width']}x{result['crop_height']}")
print(f" 占有率: {result['occupation_ratio']:.4f}")
print(f" 縮小倍率: {result['scale_factor']:.4f}")
print(f" 最終サイズ: {result['final_width']}x{result['final_height']}")
# クロップ位置の計算
crop_x, crop_y = calculate_crop_position(
1920, 1080, result['crop_width'], result['crop_height'],
100, 100, 300, 200
)
print(f" クロップ位置: ({crop_x}, {crop_y})")
# テストケース2: 縮小が必要なケース
print("\n" + "=" * 50)
print("テストケース2: 縮小が必要なケース")
print("=" * 50)
result2 = find_optimal_crop(
image_width=2000,
image_height=2000,
rect_x1=500, rect_y1=500, rect_x2=1500, rect_y2=1500, # 1000x1000の関心領域
min_length=512,
max_length=800
)
print(f"最適解:")
print(f" クロップサイズ: {result2['crop_width']}x{result2['crop_height']}")
print(f" 占有率: {result2['occupation_ratio']:.4f}")
print(f" 縮小倍率: {result2['scale_factor']:.4f}")
print(f" 最終サイズ: {result2['final_width']}x{result2['final_height']}")
if __name__ == "__main__":
test_optimal_crop()