[Python开发] 使用 Python 切割图像

使用 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')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值