Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an array of .png files in a folder using Bash

Tags:

linux

bash

Hi I am a newbe to bash programming and need some help. I am building a pipeline for image processing. I would like to be able to take the png images in a folder and pass them to clusterImage.pl once that is done I would like to then pass the outputted file to seperateObjects.pl the outputted file is of the same name but has kmeansOutput.all.matrix attached to the end. Below is what I have so far, but it is not working. Any help would be greatly appreciated. Thank you

#!/bin/bash
#This script will take in an image and a matrix file.
#The output will be an image and a matrix file.

list=`ls *.png`
for i in $list
do
$file="./$list"
$image_array = $list
echo $file
#Cheching to see if the file exists.
for((j=0;j<=i;j++))
do
if [ -e image_array[j] ]; then
echo $file
echo "Begining processing"
#Take in an image and create a matrix from it.
perl clusterImage.pl SampleImage.png
#Take in a matrix and draw a picture showing the centers of all
#of the colonies.
perl seperateObjects.pl SampleImage.png.kmeansOutput.all.matrix
echo "Ending processing"
else
echo "There is an issue"
fi
done
done
like image 706
Alos Avatar asked Dec 12 '22 21:12

Alos


2 Answers

this should work:

for file in *.png; do
    # do stuff with your file:
    perl clusterImage.pl "$file";
    # …
done
like image 173
knittl Avatar answered Dec 17 '22 23:12

knittl


I see a few problems (or potential improvements) with your code:

  1. You don't need the loop for i in $list because you never use $i in the script - that results in just doing the same thing over and over again (the same number of times as the number of .png files in the directory)
  2. You don't need to use a Bash array, since Bash can iterate over the different filenames in a list like *.png.
  3. I suspect you mean to run perl clusterImage.pl on each .png file in the directory... or did you? It's kind of hard to tell. Edit your question to explain more clearly what you mean to do, and I can edit my answer accordingly.
  4. You can use short-circuiting, as they call it, instead of an if statement: [ -f file.png ] && echo "file exists" is shorter than

    if [ -f file.png ]; then
        echo "file exists"
    fi
    

If I understand what you're trying to do (and I'm not sure I do), I think this might work for you. For each image in the directory, this will run perl clusterImage.pl <name_of_image.png> and perl separateObjects.pl <name_of_image.png>.kmeansOutput.all.matrix.

for image in *.png
do
  [[ -f $image ]] && perl clusterImage.pl $image && perl separateObjects.pl $image.kmeansOutput.all.matrix
done
like image 23
David Z Avatar answered Dec 18 '22 00:12

David Z