|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +# Copyright (c) 2025 PaddlePaddle Authors. All Rights Reserved. |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | + |
| 17 | +# @Time : 2025/4/19 下午8:37 |
| 18 | +# @Author : zhaop-l(zhaopuzxjc@126.com) |
| 19 | + |
| 20 | +import os |
| 21 | +from typing import List, Tuple |
| 22 | + |
| 23 | +from PIL import Image |
| 24 | + |
| 25 | +from .dynamic_high_resolution import factorize_number |
| 26 | + |
| 27 | + |
| 28 | +def construct_mapping_dict(max_splits: int = 12) -> dict: |
| 29 | + """Construct a mapping dictionary for the given max_splits. |
| 30 | +
|
| 31 | + Args: |
| 32 | + max_splits (int, optional): The maximum number of splits. |
| 33 | + Defaults to 12. |
| 34 | +
|
| 35 | + Returns: |
| 36 | + dict: A mapping dictionary for the given max_splits. |
| 37 | + """ |
| 38 | + mapping_dict = {} |
| 39 | + for i in range(1, max_splits + 1): |
| 40 | + factor_list = factorize_number(i) |
| 41 | + for factor in factor_list: |
| 42 | + ratio = factor[0] / factor[1] |
| 43 | + if ratio not in mapping_dict: |
| 44 | + mapping_dict[ratio] = [factor] |
| 45 | + else: |
| 46 | + mapping_dict[ratio].append(factor) |
| 47 | + return mapping_dict |
| 48 | + |
| 49 | + |
| 50 | +def save_image_list(image_list: List[Image.Image], save_folder: str) -> None: |
| 51 | + """Save a list of images to a folder. |
| 52 | +
|
| 53 | + Args: |
| 54 | + image_list (List[Image.Image]): A list of images. |
| 55 | + save_folder (str): The folder to save the images to. |
| 56 | + """ |
| 57 | + os.makedirs(save_folder, exist_ok=True) |
| 58 | + for i, image in enumerate(image_list): |
| 59 | + image.save(os.path.join(save_folder, f"{i}.png")) |
| 60 | + |
| 61 | + |
| 62 | +def resize_to_best_size( |
| 63 | + image: Image.Image, |
| 64 | + best_slices: tuple, |
| 65 | + width_slices: int, |
| 66 | + height_slices: int, |
| 67 | + sub_image_size: int, |
| 68 | +) -> Image.Image: |
| 69 | + """Resize an image to the best size for the given number of slices. |
| 70 | +
|
| 71 | + Args: |
| 72 | + image (Image.Image): The image to resize. |
| 73 | + best_slices (tuple): The best number of slices for the image. |
| 74 | + width_slices (int): The number of horizontal slices. |
| 75 | + height_slices (int): The number of vertical slices. |
| 76 | + sub_image_size (int): The size of the sub-images. |
| 77 | +
|
| 78 | + Returns: |
| 79 | + Image.Image: The resized image. |
| 80 | + """ |
| 81 | + width, height = image.size |
| 82 | + best_width_slices, best_height_slices = best_slices |
| 83 | + if width_slices < height_slices: |
| 84 | + new_image_width = best_width_slices * sub_image_size |
| 85 | + new_image_height = int(height / width * new_image_width) |
| 86 | + else: |
| 87 | + new_image_height = best_height_slices * sub_image_size |
| 88 | + new_image_width = int(width / height * new_image_height) |
| 89 | + new_image = image.resize((new_image_width, new_image_height), resample=2) |
| 90 | + return new_image |
| 91 | + |
| 92 | + |
| 93 | +def compute_strides(height: int, width: int, sub_image_size: int, slices: Tuple[int, int]) -> Tuple[int, int]: |
| 94 | + """Compute the strides for the given image size and slices. |
| 95 | +
|
| 96 | + Args: |
| 97 | + height (int): The height of the image. |
| 98 | + width (int): The width of the image. |
| 99 | + sub_image_size (int): The size of the sub-images. |
| 100 | + slices (Tuple[int, int]): The number of horizontal and vertical slices. |
| 101 | +
|
| 102 | + Returns: |
| 103 | + Tuple[int, int]: The strides for the given image size and slices. |
| 104 | + """ |
| 105 | + slice_width, slice_height = slices |
| 106 | + if slice_width > 1: |
| 107 | + stride_x = (width - sub_image_size) // (slice_width - 1) |
| 108 | + else: |
| 109 | + stride_x = 0 |
| 110 | + if slice_height > 1: |
| 111 | + stride_y = (height - sub_image_size) // (slice_height - 1) |
| 112 | + else: |
| 113 | + stride_y = 0 |
| 114 | + return stride_x, stride_y |
| 115 | + |
| 116 | + |
| 117 | +def sliding_window_crop(image: Image.Image, window_size: int, slices: Tuple[int, int]) -> List[Image.Image]: |
| 118 | + """Crop an image into sub-images using a sliding window. |
| 119 | +
|
| 120 | + Args: |
| 121 | + image (Image.Image): The image to crop. |
| 122 | + window_size (int): The size of the sub-images. |
| 123 | + slices (Tuple[int, int]): The number of horizontal and vertical slices. |
| 124 | +
|
| 125 | + Returns: |
| 126 | + List[Image]: A list of cropped images. |
| 127 | + """ |
| 128 | + width, height = image.size |
| 129 | + stride_x, stride_y = compute_strides(height, width, window_size, slices) |
| 130 | + sub_images = [] |
| 131 | + if stride_x == 0: |
| 132 | + stride_x = window_size |
| 133 | + if stride_y == 0: |
| 134 | + stride_y = window_size |
| 135 | + for y in range(0, height - window_size + 1, stride_y): |
| 136 | + for x in range(0, width - window_size + 1, stride_x): |
| 137 | + sub_image = image.crop((x, y, x + window_size, y + window_size)) |
| 138 | + sub_images.append(sub_image) |
| 139 | + return sub_images |
| 140 | + |
| 141 | + |
| 142 | +def find_best_slices(width_slices: int, height_slices: int, aspect_ratio: float, max_splits: int = 12) -> list: |
| 143 | + """Find the best slices for the given image size and aspect ratio. |
| 144 | +
|
| 145 | + Args: |
| 146 | + width_slices (int): The number of horizontal slices. |
| 147 | + height_slices (int): The number of vertical slices. |
| 148 | + aspect_ratio (float): The aspect ratio of the image. |
| 149 | + max_splits (int, optional): The maximum number of splits. |
| 150 | + Defaults to 12. |
| 151 | +
|
| 152 | + Returns: |
| 153 | + list: the best slices for the given image. |
| 154 | + """ |
| 155 | + mapping_dict = construct_mapping_dict(max_splits) |
| 156 | + if aspect_ratio < 1: |
| 157 | + mapping_dict = {k: v for k, v in mapping_dict.items() if k <= aspect_ratio} |
| 158 | + elif aspect_ratio > 1: |
| 159 | + mapping_dict = {k: v for k, v in mapping_dict.items() if k >= aspect_ratio} |
| 160 | + best_ratio = min(mapping_dict.keys(), key=lambda x: abs(x - aspect_ratio)) |
| 161 | + best_image_sizes = mapping_dict[best_ratio] |
| 162 | + best_slices = min(best_image_sizes, key=lambda x: abs(x[0] * x[1] - width_slices * height_slices)) |
| 163 | + return best_slices |
| 164 | + |
| 165 | + |
| 166 | +def split_image_with_catty( |
| 167 | + pil_image: Image.Image, |
| 168 | + image_size: int = 336, |
| 169 | + max_crop_slices: int = 8, |
| 170 | + save_folder: str = None, |
| 171 | + add_thumbnail: bool = True, |
| 172 | + do_resize: bool = False, |
| 173 | + **kwargs, |
| 174 | +) -> List[Image.Image]: |
| 175 | + """Split an image into sub-images using Catty. |
| 176 | +
|
| 177 | + Args: |
| 178 | + pil_image (Image.Image): The image to split. |
| 179 | + image_size (int, optional): The size of the image. |
| 180 | + Defaults to 336. |
| 181 | + max_crop_slices (int, optional): The maximum number of slices. |
| 182 | + Defaults to 8. |
| 183 | + save_folder (str, optional): The folder to save the sub-images. |
| 184 | + Defaults to None. |
| 185 | + add_thumbnail (bool, optional): Whether to add a thumbnail. |
| 186 | + Defaults to False. |
| 187 | + do_resize (bool, optional): Whether to resize the image to fit the |
| 188 | + maximum number of slices. Defaults to False. |
| 189 | +
|
| 190 | + Returns: |
| 191 | + List[Image.Image]: A list of cropped images. |
| 192 | + """ |
| 193 | + width, height = pil_image.size |
| 194 | + ratio = width / height |
| 195 | + if ratio > max_crop_slices or ratio < 1 / max_crop_slices: |
| 196 | + if do_resize: |
| 197 | + print(f"Resizing image to fit maximum number of slices ({max_crop_slices})") |
| 198 | + if width > height: |
| 199 | + new_width = max_crop_slices * height |
| 200 | + new_height = height |
| 201 | + else: |
| 202 | + new_width = width |
| 203 | + new_height = max_crop_slices * width |
| 204 | + pil_image = pil_image.resize((new_width, new_height), resample=2) |
| 205 | + width, height = pil_image.size |
| 206 | + ratio = width / height |
| 207 | + else: |
| 208 | + print( |
| 209 | + f"Image aspect ratio ({ratio:.2f}) is out of range: ({1 / max_crop_slices:.2f}, {max_crop_slices:.2f})" |
| 210 | + ) |
| 211 | + return None |
| 212 | + width_slices = width / image_size |
| 213 | + height_slices = height / image_size |
| 214 | + best_slices = find_best_slices(width_slices, height_slices, ratio, max_crop_slices) |
| 215 | + pil_image = resize_to_best_size(pil_image, best_slices, width_slices, height_slices, image_size) |
| 216 | + width, height = pil_image.size |
| 217 | + sub_images = sliding_window_crop(pil_image, image_size, best_slices) |
| 218 | + if add_thumbnail: |
| 219 | + thumbnail_image = pil_image.resize((image_size, image_size), resample=2) |
| 220 | + sub_images.append(thumbnail_image) |
| 221 | + if save_folder is not None: |
| 222 | + save_image_list(sub_images, save_folder) |
| 223 | + return sub_images |
0 commit comments