使用 Python 来切割图像,分别是按高度和宽度切割成若干张小图像。
如高宽分别为 7000 和 1080 的图片 img1.jpg
,按最大高度 1920 从上到下切割成 3 张
1920
×
1080
1920 \times 1080
1920×1080 的图和 1 张
1240
×
1080
1240 \times 1080
1240×1080 的图。
而高宽分别为 1920 和 3000 的图片 img2.jpg
,按最大宽度 1080 从左到右切割成 2 张
1920
×
1080
1920 \times 1080
1920×1080 的图和 1 张
1920
×
840
1920 \times 840
1920×840 的图。
# -*- coding: utf-8 -*-
#
# @Author: lijiancheng0614
# @Date: 2021-04-29
#
"""demo_split_image.py
"""
from PIL import Image
import numpy as np
def split_height(file_path, max_height=4096):
"""Split image by height.
Args:
file_path (str): file path.
max_height (int, optional): maximum height of the split images.
"""
image = Image.open(file_path)
height = image.size[1]
if height <= max_height:
print('[WARN] No need to split since height {} <= {}'.format(
height, max_height))
return
image = np.array(image)
suffix = file_path.split('.')[-1]
prefix = file_path.rstrip(suffix)[:-1]
count = 0
for from_height in range(0, height, max_height):
count += 1
output_file_path = '{}_{}.{}'.format(prefix, count, suffix)
print('[INFO] Saving part {} {}'.format(count, output_file_path))
to_height = min(from_height + max_height, height)
image_new = Image.fromarray(image[from_height:to_height, ...])
image_new.save(output_file_path)
def split_width(file_path, max_width=1080):
"""Split image by width.
Args:
file_path (str): file path.
max_width (int, optional): maximum width of the split images.
"""
image = Image.open(file_path)
width = image.size[0]
if width <= max_width:
print('[WARN] No need to split since width {} <= {}'.format(
width, max_width))
return
image = np.array(image)
suffix = file_path.split('.')[-1]
prefix = file_path.rstrip(suffix)[:-1]
count = 0
for from_width in range(0, width, max_width):
count += 1
output_file_path = '{}_{}.{}'.format(prefix, count, suffix)
print('[INFO] Saving part {} {}'.format(count, output_file_path))
to_width = min(from_width + max_width, width)
image_new = Image.fromarray(image[:, from_width:to_width, ...])
image_new.save(output_file_path)
split_height('img1.jpg')
split_width('img2.jpg')