#! /bin/bash -e
# Last edited on 2025-08-20 22:12:38 by stolfi

# Reads a specified PNG file "${ifile}". Writes to {stdout} a 0-1 PNG
# image showing the pixels of the input whose value is above (if
# ${invert} is 0) or below (if ${invert} is 1) a given threshhold
# ${maxval}.

ifile="$1"; shift  # Input image file.
invert="$1"; shift  # Input image file.
maxval="$1"; shift # Max acceptable sample value.

temp="/tmp/$$"

echo "  threshold sample value = ${maxval}" 1>&2

if [[ ${invert} -ne 0 ]]; then
  invert_ops=( -invert )
else
  invert_ops=( )
fi


# Convert the file to PGM to detect overvalued pixels:
convert ${ifile} \
    -set colorspace LinearGray \
    -depth 16 \
    -colorspace LinearGray \
    -compress none PGM:- \
  | gawk -v maxval=${maxval} -v invert=${invert} \
     ' BEGIN { nclip = 0; ntot = 0; maxval += 0; invert += 0 }
       /^65535$/ { print "1"; next; }
       (FNR <= 3) { print; next; }
       //{
         for (i = 1; i <= NF; i++) {
           val = $(i) + 0;
           out = 0;
           ntot++;
           over = (invert ? val < maxval : val > maxval)
           if (over) { nclip++; out = 1; }
           printf " %d", out;
         }
         print ""; next
       }
       END { printf "  pixels = %d  clipped = %d (frac = %7.5f)", ntot, nclip, nclip/ntot > "/dev/stderr"; }
     ' \
  | convert PGM:- \
      -set colorspace LinearGray \
      -depth 8 \
      -morphology Dilate Disk:4.3 \
      -resize '25%' \
      -colorspace LinearGray \
      PNG:-


