Created
May 2, 2025 17:17
-
-
Save h1romas4/6168da2667bebe2a76b3e8714c89740f to your computer and use it in GitHub Desktop.
A Bash script to crop 9 images and create a 3x3 montage using ImageMagick
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# ./crop9_montage3x3.sh souryoku_20250502/char 1265x1265+1422+366 result_char.png | |
# ./crop9_montage3x3.sh souryoku_20250502/mamono 1284x1284+1323+169 result_mamono.png | |
# | |
# Get the absolute path to the script's directory and set tmp directory | |
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" | |
TMP_DIR="$SCRIPT_DIR/tmp" | |
# Argument check | |
if [ -z "$1" ] || [ -z "$2" ]; then | |
echo "\nError: Missing required arguments.\n" >&2 | |
echo "Usage: $0 <image_directory> <crop_param> [output_file]" >&2 | |
echo "Example: $0 souryoku_20250502/char 1265x1265+1422+366 [output.png]" >&2 | |
echo "\n <image_directory> : Directory containing 9 images (sorted by filename)" >&2 | |
echo " <crop_param> : Crop parameter, e.g., 1265x1265+1422+366" >&2 | |
echo " [output_file] : (Optional) Output file name, default is result.png" >&2 | |
exit 1 | |
fi | |
IMG_DIR="$1" | |
CROP_PARAM="$2" | |
OUTPUT_FILE="${3:-result.png}" | |
# 1. Get the first 9 files sorted by filename | |
files=($(ls "$IMG_DIR" | sort | head -n 9)) | |
# 2. Crop each image and save to tmp directory | |
for i in "${!files[@]}"; do | |
convert "$IMG_DIR/${files[$i]}" -crop "$CROP_PARAM" +repage "$TMP_DIR/crop_$i.png" | |
done | |
# 3. Combine the 9 cropped images into a 3x3 grid | |
montage "$TMP_DIR"/crop_{0..8}.png -tile 3x3 -geometry +0+0 "$OUTPUT_FILE" | |
# 4. Remove temporary cropped images | |
rm "$TMP_DIR"/crop_{0..8}.png |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment