Skip to content

Instantly share code, notes, and snippets.

@frock81
Last active April 26, 2023 23:54
Show Gist options
  • Save frock81/8f6788a477a6015b191c77b630f94e03 to your computer and use it in GitHub Desktop.
Save frock81/8f6788a477a6015b191c77b630f94e03 to your computer and use it in GitHub Desktop.
Loop through a barcode grayscale image with different threshold values and tries to read them. Requires imagemagick and zbarimg.
#!/bin/bash
# This script will run zbarimg on a thresholded image
# for a range of threshold values.
usage() {
echo "Usage: $0 <filename> [-s <symbology>] [-a <start_threshold>] [-o <stop_threshold>]"
echo " <filename> Required. Specifies the input file name"
echo " -s, --symbology Optional. Specifies the symbology type"
echo " -a, --start-threshold Optional. Specifies the start threshold (default: 45)"
echo " -o, --stop-threshold Optional. Specifies the stop threshold (default: 55)"
exit 1
}
PARAMS=""
while (( "$#" )); do
case "$1" in
-f|--filename)
if [ -n "$2" ] && [ ${2:0:1} != "-" ]; then
FILENAME=$2
shift 2
else
echo "Error: Argument for $1 is missing" >&2
exit 1
fi
;;
-s|--symbology)
if [ -n "$2" ] && [ ${2:0:1} != "-" ]; then
SYMBOLOGY=$2
shift 2
else
echo "Error: Argument for $1 is missing" >&2
exit 1
fi
;;
-a|--start_threshold)
if [ -n "$2" ] && [ ${2:0:1} != "-" ]; then
START_THRESHOLD=$2
shift 2
else
echo "Error: Argument for $1 is missing" >&2
exit 1
fi
;;
-o|--stop_threshold)
if [ -n "$2" ] && [ ${2:0:1} != "-" ]; then
STOP_THRESHOLD=$2
shift 2
else
echo "Error: Argument for $1 is missing" >&2
exit 1
fi
;;
--) # end argument parsing
shift
break
;;
-*|--*=) # unsupported flags
echo "Error: Unsupported flag $1" >&2
exit 1
;;
*) # preserve positional arguments
PARAMS="$PARAMS $1"
shift
;;
esac
done
# set positional arguments in their proper place
eval set -- "$PARAMS"
FILENAME="$1"
# check if filename was provided
if [ -z "$FILENAME" ]; then
echo "Error: filename is a required argument" >&2
exit 1
fi
# set defaults for start and stop thresholds
START_THRESHOLD=${START_THRESHOLD:-45}
STOP_THRESHOLD=${STOP_THRESHOLD:-55}
echo "Filename: $FILENAME"
echo "Symbology: $SYMBOLOGY"
echo "Start threshold: $START_THRESHOLD"
echo "Stop threshold: $STOP_THRESHOLD"
echo "Positional arguments: $@"
if [[ -n "$SYMBOLOGY" ]]; then
SYMBOL_OPTS="-Sdisable -S${SYMBOLOGY}.enable"
fi
for i in $(seq "$START_THRESHOLD" "$STOP_THRESHOLD"); do
echo "Running $i"
convert "$FILENAME" -threshold "$i"% threshold_"$i".png
#shellcheck disable=SC2086
zbarimg --quiet --raw $SYMBOL_OPTS threshold_"$i".png
if [[ $? -eq 0 ]]; then
echo "Found at threshold $i"
break
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment