Initial commit
This commit is contained in:
46
split01.py
Normal file
46
split01.py
Normal file
@@ -0,0 +1,46 @@
|
||||
from PIL import Image
|
||||
import os
|
||||
|
||||
|
||||
def split_image(image_path, output_dir, rows=10, cols=10):
|
||||
"""
|
||||
将图片切成指定行列的小块。
|
||||
|
||||
参数:
|
||||
image_path (str): 输入图片的路径。
|
||||
output_dir (str): 保存小块图片的目录。
|
||||
rows (int): 切分的行数。
|
||||
cols (int): 切分的列数。
|
||||
"""
|
||||
# 打开图片
|
||||
img = Image.open(image_path)
|
||||
img_width, img_height = img.size
|
||||
|
||||
# 计算每块的宽和高
|
||||
piece_width = img_width // cols
|
||||
piece_height = img_height // rows
|
||||
|
||||
# 创建输出目录
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
# 遍历切割
|
||||
for row in range(rows):
|
||||
for col in range(cols):
|
||||
# 定义每块的区域 (left, upper, right, lower)
|
||||
left = col * piece_width
|
||||
upper = row * piece_height
|
||||
right = (col + 1) * piece_width
|
||||
lower = (row + 1) * piece_height
|
||||
|
||||
# 裁剪出小块并保存
|
||||
piece = img.crop((left, upper, right, lower))
|
||||
piece_path = os.path.join(output_dir, f"piece_{row}_{col}.png")
|
||||
piece.save(piece_path)
|
||||
|
||||
print(f"图片已分割成 {rows * cols} 小块,保存到:{output_dir}")
|
||||
|
||||
|
||||
# 使用示例
|
||||
image_path = "input.jpg" # 输入图片路径
|
||||
output_dir = "output_pieces" # 输出目录
|
||||
split_image(image_path, output_dir)
|
||||
Reference in New Issue
Block a user