Files
scripts/image/crop_image_to_object_pixels.py
2024-12-02 19:38:23 +03:00

39 lines
1.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import os
import argparse
from PIL import Image
def crop_to_object(input_folder, output_folder=None):
# Если выходная папка не указана, используем входную
if output_folder is None:
output_folder = input_folder
# Проверяем, существует ли выходная папка, если нет, создаем ее
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Проходим по всем файлам в входной папке
for filename in os.listdir(input_folder):
if filename.endswith('.png'):
img_path = os.path.join(input_folder, filename)
img = Image.open(img_path)
# Получаем границы непрозрачных пикселей
bbox = img.getbbox()
if bbox:
# Обрезаем изображение
img_cropped = img.crop(bbox)
# Сохраняем обработанное изображение
img_cropped.save(os.path.join(output_folder, filename))
print(f"Processed {filename}")
def main():
parser = argparse.ArgumentParser(description="Crop PNG images to the size of the visible object.")
parser.add_argument('input_folder', type=str, help='Path to the input folder containing PNG images.')
parser.add_argument('output_folder', type=str, nargs='?', default=None, help='Path to the output folder to save processed images. If not provided, the input folder will be used.')
args = parser.parse_args()
crop_to_object(args.input_folder, args.output_folder)
if __name__ == "__main__":
main()