Chika
Chika

Reputation: 17

How to sort images by aspect ratio

I want to sort images by aspect ratio, then use MPV to browse them, and I got some codes from Google:

identify * |
    gawk '{split($3,sizes,"x"); print $1,sizes[1]/sizes[2]}' |
    sed 's/\[.\]//' | sort -gk 2

This is a output:

28.webp 0.698404
1.webp 0.699544
27.webp 0.706956
10.webp 0.707061
25.webp 0.707061
9.webp 0.707061
2.webp 0.707241
22.webp 1.41431
23.webp 1.41431
24.webp 1.41431

Then I made some adaptations to fit my need:

identify * |
    gawk '{split($3,sizes,"x"); print $1,sizes[1]/sizes[2]}' | 
    sed 's/\[.\]//' | sort -gk 2 |
    gawk '{print $1}' |
    mpv --no-resume-playback --really-quiet --playlist=-

It works, but isn't perfect. It can't deal with filename with space and identify is too slower than exiftool especially when handling WebP format, besides, exiftool has a -r option, so I want to use exiftool to get this output instead, but I don't know how to deal with the output of exiftool -r -s -ImageSize, anyone could help me?

Upvotes: 0

Views: 532

Answers (2)

LMC
LMC

Reputation: 12662

Display aspect ratio and image filename without additional calculations with identify

identify -format '%f %[fx:w/h]\n' *.jpg | sort -n -k2,2
file1.jpg 1
file2.jpg 1.46789
file6.jpg 1.50282
file5.jpg 1.52
file7.jpg 1.77778
file3.jpg 1.90476

Regarding performance of identify vs exiftool, identify makes less calls but exiftool looks faster

strace -c identify -format '%f %[fx:w/h]\n' *.jpg 2>&1 | grep -E 'syscall|total'
% time     seconds  usecs/call     calls    errors syscall
100.00    0.001256                   867        43 total

strace -c exiftool -r -s -ImageSize *.jpg 2>&1 | grep -E 'syscall|total'
% time     seconds  usecs/call     calls    errors syscall
100.00    0.000582                  1138       311 total

Upvotes: 1

StarGeek
StarGeek

Reputation: 5771

Using exiftool you could use
exiftool -p '$filename ${ImageSize;m/(\d+)x(\d+)/;$_=$1/$2}' /path/to/files | sort -gk 2

This will format the output the same as your example and I assume the same sort command will work with that. If not, then the sort part would need editing.

Upvotes: 3

Related Questions