Python批量将图片分割成多张小图片
时间: 2024-03-28 19:12:22 浏览: 94
以下是使用Python批量将图片分割成多张小图片的示例代码。
```python
from PIL import Image
import os
def split_image(image_path, output_path, row, col):
"""
将图片分割成row * col张小图片
"""
if not os.path.exists(output_path):
os.makedirs(output_path)
img = Image.open(image_path)
width, height = img.size
cell_width = width // col
cell_height = height // row
for r in range(row):
for c in range(col):
box = (c * cell_width, r * cell_height, (c+1) * cell_width, (r+1) * cell_height)
cell = img.crop(box)
cell.save(os.path.join(output_path, f"{r}_{c}.png"))
if __name__ == '__main__':
image_path = "test.jpg"
output_path = "output"
row = 2
col = 3
split_image(image_path, output_path, row, col)
```
该示例代码使用了Pillow库(Python Imaging Library的一个分支),通过指定分割行列数,将原始图片分割成多张小图片,并保存到指定的输出路径中。可以根据实际需求修改参数来实现批量分割图片。
阅读全文