Skip to content

Instantly share code, notes, and snippets.

@yknishidate
Created October 29, 2023 11:20
Show Gist options
  • Save yknishidate/4e85676778d73245401638e10f3bd93f to your computer and use it in GitHub Desktop.
Save yknishidate/4e85676778d73245401638e10f3bd93f to your computer and use it in GitHub Desktop.
crop all images
# pip install pillow
import sys
import os
from PIL import Image
def crop_images(directory, x, y, width, height):
# サブディレクトリを作成
output_dir = os.path.join(directory, "cropped")
os.makedirs(output_dir, exist_ok=True)
# ディレクトリ内のすべてのファイルをチェック
for filename in os.listdir(directory):
filepath = os.path.join(directory, filename)
# 画像ファイルの場合
if os.path.isfile(filepath) and filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
try:
# 画像を開く
img = Image.open(filepath)
# 画像を切り抜く
cropped_img = img.crop((x, y, x + width, y + height))
# 切り抜いた画像を保存
cropped_img.save(os.path.join(output_dir, filename))
print(f"Image {filename} cropped and saved.")
except Exception as e:
print(f"Failed to crop image {filename}: {str(e)}")
if __name__ == "__main__":
if len(sys.argv) != 6:
print("Usage: python crop.py <directory_path> <x> <y> <width> <height>")
else:
directory, x, y, width, height = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]), int(sys.argv[5])
crop_images(directory, x, y, width, height)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment