Shell Script Toolbox

When you work in image processing, you keep running into the same recurring problem: you need to preprocess images to test a new feature, try a different dataset, or compare algorithms. Renaming and resizing images by hand is painful and boring once you have more than 3-4 images.

I started collecting useful shell scripts for quick and easy image preprocessing for computer vision and deep learning tasks.

For all tasks below, I assume images are in .png format. I also always save processed images into a new folder instead of overwriting originals, just in case. So please create a folder first, then replace /folder in the scripts with your own folder name.

I also assume you want to process all images in the current folder.

Navigate in your terminal to the folder that contains your images, run the scripts below, and press Enter. Some scripts can take a couple of minutes depending on the operation and number of images.

Transform RGB images to one-channel grayscale

for a in *.png; do convert "$a" -set colorspace gray -separate -average folder/"$a"; done

Resize images by percentage (width and height)

for a in *.png; do convert "$a" -resize 50% folder/"$a"; done

Resize images to a specific size

for a in *.png; do convert "$a" -resize 640x270 folder/"$a"; done

Rename images in consecutive order

This script is longer, so I keep it in a file called rename.sh:

#!/bin/ksh
a=1
for i in *.png; do
  new=$(printf "$a.png")
  mv -i -- "$i" "$new"
  a=$(($a+1))
done

Place this file in the same folder as your images and run:

sh rename.sh

Crop a specific region from each image

Open the first image in GIMP. Use the rectangle selection tool and select the region you want to crop.

In the toolbox, note:

Replace those values in this script:

for a in *.png; do convert "$a" -crop WIDTHxHEIGHT+X+Y folder/"$a"; done

Example:

for a in *.png; do convert "$a" -crop 530x460+7+13 cropped/"$a"; done