Certainly! Below is a Bash script that uses ImageMagick to convert an image to AVIF, automatically finding the quality value that achieves at least 99% similarity (SSIM) with the original. It uses a binary search for efficiency.
Requirements:
magick (ImageMagick 7+)
compare (ImageMagick, for SSIM)
bc (for floating point math)
#!/bin/bash
# Usage: ./to_avif_99ssim.sh input.jpg output.avif
set -e
if [ $# -ne 2 ]; then
echo "Usage: $0 input_image output_avif"
exit 1
fi
input="$1"
output="$2"
tmp_avif="tmp_avif.avif"
tmp_decoded="tmp_decoded.png"
target_ssim=0.99
min_quality=10
max_quality=100
best_quality=$max_quality
# Function to compute SSIM between two images
get_ssim() {
# compare -metric SSIM returns: 0.999999 (1 means identical)
ssim=$(magick compare -metric SSIM "$1" "$2" null: 2>&1 | awk '{print $1}')
echo "$ssim"
}
while [ $min_quality -le $max_quality ]; do
mid_quality=$(( (min_quality + max_quality) / 2 ))
# Convert to AVIF with current quality
magick "$input" -quality $mid_quality "$tmp_avif"
# Decode AVIF back to PNG for comparison
magick "$tmp_avif" "$tmp_decoded"
# Compute SSIM
ssim=$(get_ssim "$input" "$tmp_decoded")
ssim_ok=$(echo "$ssim >= $target_ssim" | bc)
if [ "$ssim_ok" -eq 1 ]; then
# Quality is high enough, try lower
best_quality=$mid_quality
max_quality=$((mid_quality - 1))
else
# Not good enough, try higher
min_quality=$((mid_quality + 1))
fi
done
# Final conversion with best quality
magick "$input" -quality $best_quality "$output"
echo "Best quality: $best_quality (>=99% SSIM)"
# Cleanup
rm -f "$tmp_avif" "$tmp_decoded"
How to use:
chmod +x to_avif_99ssim.sh
./to_avif_99ssim.sh input.jpg output.avif
Notes:
- The script uses a binary search to minimize the number of conversions.
- It compares the original and the AVIF-decoded image using SSIM.
- You can adjust
target_ssim if you want a different threshold.
- For color images, SSIM is a good metric, but for some images, you may want to use other metrics (e.g., PSNR).
Let me know if you need a version for ImageMagick 6 or want to use a different similarity metric!