Average color by row (bash)
Posted: 2019-01-28T12:26:10-07:00
I'm looking for a way to get the average color of each row for a grayscale image. I've gotten a functional solution, but it's rather slow and inelegant. I'm sure that there's a better way to do this (likely within a single ImageMagick command), but I'm unable to figure it out. Any assistance would be greatly appreciated.
Current solution:
Current solution:
Code: Select all
imageHeight="$(magick identify -format "%[fx:h]" "$f")"
rows="$(convert "$f" txt:)"
rowMeans=()
# example of `rows` content:
# 0,0: (150,150,150) #969696 gray(150)
# 1,0: (154,154,154) #9A9A9A gray(154)
# 2,0: (154,154,154) #9A9A9A gray(154)
for rowNum in `seq 0 $(( ${imageHeight} - 1 ))`; do
# Read the pixel value for each row, and store the value in an array
pixArr=(`echo "$rows" | grep ",${rowNum}:" | awk 'BEGIN { FS="[,]" } {print $3}'`)
# Append each value in the array with a '+' and calculate the sum
# (this causes the last value to have a trailing '+', so it is added to '0')
rowSum=$(echo "${pixArr[@]/%/+}"0 | bc -l)
# Divide the sum by the total number of elements and add the value to the array
rowMeans=(${rowMeans} `echo $((rowSum / ${#pixArr[@]} )) ` )
done