Yolov/cajian.py

78 lines
2.6 KiB
Python

from PIL import Image
import os
def smart_crop_to_multiple(input_path, output_dir, tile_size=(512, 512)):
"""
智能裁剪,尽量保持重要内容不被分割
"""
os.makedirs(output_dir, exist_ok=True)
with Image.open(input_path) as img:
img_width, img_height = img.size
tile_width, tile_height = tile_size
# 计算行列数(取整)
cols = img_width // tile_width
rows = img_height // tile_height
# 处理余数,均匀分配到各列/行
width_remainder = img_width % tile_width
height_remainder = img_height % tile_height
# 调整每列的宽度(如果有余数)
col_widths = []
if cols > 0:
base_width = tile_width
extra_per_col = width_remainder // cols
extra_for_last = width_remainder % cols
for i in range(cols):
width = base_width + extra_per_col
if i == cols - 1: # 最后一列
width += extra_for_last
col_widths.append(width)
# 调整每行的高度(如果有余数)
row_heights = []
if rows > 0:
base_height = tile_height
extra_per_row = height_remainder // rows
extra_for_last = height_remainder % rows
for i in range(rows):
height = base_height + extra_per_row
if i == rows - 1: # 最后一行
height += extra_for_last
row_heights.append(height)
count = 0
current_y = 0
for row in range(rows):
current_x = 0
for col in range(cols):
# 计算裁剪区域
left = current_x
upper = current_y
right = left + col_widths[col] if col < len(col_widths) else left + tile_width
lower = upper + row_heights[row] if row < len(row_heights) else upper + tile_height
# 裁剪
tile = img.crop((left, upper, right, lower))
# 保存
filename = f"smart_tile_{row + 1:03d}_{col + 1:03d}_{tile.width}x{tile.height}.png"
output_path = os.path.join(output_dir, filename)
tile.save(output_path)
print(f"已保存: {filename}")
current_x = right
count += 1
current_y = lower
print(f"\n总共裁剪出 {count} 个智能小图片")
# 使用示例
smart_crop_to_multiple(r"E:\DC\Yolov\uploads\费县8-13-19-9-14-20-148.JPG", "smart_tiles", tile_size=(1280, 1280))