Зацикливание сценария переименования, преобразование 3 файлов с помощью ImageMagick в монтаж, а затем отправка файла в другую папку - PullRequest
0 голосов
/ 09 января 2019

В настоящее время я использую Raspberry Pi 3B и хотел бы создать bash-скрипт, который будет непрерывно работать в фоновом режиме в ожидании:

В папке с именем PHOTOS, содержащей последовательный файл .jpg с именами photobooth_shot_00001.jpg, photobooth_shot_00002.jpg, photobooth_shot_00003.jpg и т. Д.

Я бы хотел переименовать каждые 3 вновь сгенерированных .jpg с именами «GROUP-1-1.jpg», «GROUP-1-2.jpg», «GROUP-1-3.jpg», WITH GROUP - * - [1-3] .jpg последовательно увеличивается.

Затем, преобразовывая каждые 3 изображения из каждой "GROUP- *" в монтаж, используя следующий скрипт bash с использованием ImageMagick:

    convert \
\( -size 600x400 xc:white \) \
\( GROUP-*-1.jpg -resize 370x \) -geometry +19+29 -compose over -composite \
\( GROUP-*-2.jpg -resize 187x \) -geometry +398+29 -compose over -composite \
\( GROUP-*-3.jpg -resize 187x \) -geometry +398+175 -compose over -composite \
\( watermark.png \) -geometry +0-10  -compose over -composite \
-density 100 GROUP-*-RESULT.jpg

Наконец, отправка «GROUP - * - RESULT.jpg» в другую папку с именем «PRINT»

Было очень сложно просто переименовать их ... Спасибо за любую помощь!

1 Ответ

0 голосов
/ 09 января 2019

Предполагая, что вы пропустили часть, как вы можете переименовать файлы изображений, попробуйте что-то вроде:

#!/bin/bash

photodir="PHOTOS"           # dir to store originally generated images
donedir="$photodir/done"    # dir to backup processed files
seqfile="$photodir/seq"     # file to keep the sequential group number

# read file names in $photodir, sort in increasing order and store in an array
while read -r -d "" f; do
    ary+=("$f")
done < <(find "$photodir" -type f -name "photobooth_shot_*.jpg" -print0 | sort -z)

# abort if #files is less than three
if (( ${#ary[@]} < 3 )); then
    echo "hoge"
    exit
fi

# read last group number if the file exists
if [[ -f $seqfile ]]; then
    seq=$(<"$seqfile")
else
    seq=0
fi
seq=$((++seq))

mkdir -p "$donedir"

# rename top three files
for ((i=0; i<3; i++)); do
    newname=$(printf "%s/GROUP-%d-%d.jpg" "$photodir" "$seq" "$((++i))")
    newary+=("$newname")
    mv -- "${ary[$i]}" "$newname"
done

# perform ImageMagick "convert" here
#   for the files "GROUP-${seq}-[1-3].jpg" or "${newary[@]}"

# backup processed files
mv -- "${newary[@]}" "$donedir"

# store the group number for next invocation
echo "$seq" > "$seqfile"
  • Пожалуйста, поместите вашу команду ImageMagick вокруг строки "execute ImageMagick".
  • Сценарий должен вызываться периодически (например, каждые 1 минуту или около того, в зависимости от частоты генерации нового изображения).
  • Скрипт не должен выполняться одновременно (параллельно).

Надеюсь, это поможет.

[РЕДАКТИРОВАТЬ]

Сценарий ниже является обновленной версией в соответствии с вашими требованиями:

#!/bin/bash

photodir="PHOTOS"           # dir to store originally generated images
donedir="$photodir/done"    # dir to backup processed files
seqfile="$photodir/seq"     # file to keep the sequential group number

# wait for the growing file to be completed by watching the filesize
# it may not be 100% reliable depending on the file creation process

waitfile() {
    file=$1

    if [[ ! -f "$file" ]]; then
        return
    fi
    while true; do
        size0=$(stat -c %s "$file")
        sleep 1
        size1=$(stat -c %s "$file")
        sleep 1
        size2=$(stat -c %s "$file")
        if (( $size0 == $size1 && $size1 == $size2 )); then
            return
        fi
    done
}

# exit immediately if the same name process still exists
#  (the previous execution is still working..)
scriptname=${0##*/}
count=$(ps -aux | grep "$scriptname" | wc -l)
if (( $count > 3 )); then
    exit
fi

# read file names in $photodir, sort in increasing order and store in an array
while read -r -d "" f; do
    ary+=("$f")
done < <(find "$photodir" -type f -name "photobooth_shot_*.jpg" -print0 | sort -z)

# abort if #files is less than three
if (( ${#ary[@]} < 3 )); then
#   echo "hoge"             # this line is for debugging purpose
    exit
fi

# find auto-composite photos
while read -r -d "" f; do
    ary2+=("$f")
done < <(find "$photodir" -type f -name "photobooth[0-9]*.jpg" -print0 | sort -z
)

# abort if no auto-composite photos are found
if (( ${#ary2[@]} < 1)); then
#   echo "hoge"         # this is for debugging purpose
    exit
fi

composite="${ary2[0]}"
waitfile "$composite"       # wait for the auto-composite file to be complete

# read last group number if the file exists
if [[ -f $seqfile ]]; then
    seq=$(<"$seqfile")
else
    seq=0
fi
seq=$((++seq))

mkdir -p "$donedir"

# rename top three files
for ((i=0; i<3; i++)); do
    newname=$(printf "%s/GROUP-%d-%d.jpg" "$photodir" "$seq" "$((++i))")
    newary+=("$newname")
    mv -- "${ary[$i]}" "$newname"
done

# rename the auto-composite file
newname2=$(printf "%s/GROUP-%d-ORIGINAL.jpg" "$photodir" "$seq")
mv -- "$composite" "$newname2"

# perform ImageMagick "convert" here
#   for the files "GROUP-${seq}-[1-3].jpg" or "${newary[@]}"

# move the auto-composite file to the designated folder
# mv -- "$newname2" "destdir"

# backup processed files
mv -- "${newary[@]}" "$donedir"

# store the group number for next invocation
echo "$seq" > "$seqfile"
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...