Skip to content

Instantly share code, notes, and snippets.

@antoineMoPa
Created November 11, 2015 02:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antoineMoPa/8395bfff6d7c24eb59c3 to your computer and use it in GitHub Desktop.
Save antoineMoPa/8395bfff6d7c24eb59c3 to your computer and use it in GitHub Desktop.
# Pixel sorts an image
# Takes 2 arguments:
# $1 is the original filename
# $2 is the field to order:
# 1 r
# 2 g
# 3 b
# 4 r + g + b
# Example:
# sh sort.sh me.jpg 4
# We first need an uncompressed ppm
convert $1 -compress none image.ppm
# take data and put in one column
cat image.ppm | tail -n+4 | sed 's/ /\n/g' | sed '/^$/d' > 1-column.ppm
# organise data in 3 columns (r,g,b)
cat 1-column.ppm | paste -d\ - - - > 3-columns.ppm
# calculate the sum of every (r,g,b) values
cat 3-columns.ppm | sed 's/ /+/g' | bc > sums.ppm
# join (r,g,b) columns with sum column
paste -d\ 3-columns.ppm sums.ppm > 4-columns.ppm
# order by given field ($2) and take back only (r,g,b) values
cat 4-columns.ppm | sort -k$2,$2nr | cut -d" " -f1,2,3 > sorted.ppm
# create identical header with first 3 lines
cat image.ppm | head -n 3 > final.ppm
# put sorted data in the file
cat sorted.ppm >> final.ppm
# create jpg version
convert final.ppm final.jpg
# put original and result side by side (montage)
montage image.ppm final.ppm montage.jpg
# remove temporary files
rm 3-columns.ppm 4-columns.ppm sums.ppm
# display montage or final image
# display montage.jpg
display final.jpg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment