Python Quick Tip #4: Batching Over Files in a Directory
Updated: Jul 27, 2020
TL;DR
Here is the full script to load all PNGs in a given folder, convert them to 8bit grayscale TIFF, then save them to a different folder:
import os
from skimage import io
from skimage.util import img_as_ubyte
# You need to change these to valid directories on your computer
input_dir = os.path.dirname('C:/FILES/leaves/')
output_dir = os.path.dirname('C:/FILES/leaves converted/')
for f in os.listdir(input_dir):
if f.lower().endswith('.png') is True:
image_gray = io.imread(os.path.join(input_dir, f),
as_gray=True)
image_gray = img_as_ubyte(image_gray)
output_file = f.replace('.png', '_gray.tiff')
io.imsave(os.path.join(output_dir, output_file), image_gray)

You can also access this script on our GitHub.
Line by Line
Let's import the functionality we’ll need:
import os
from skimage import io
from skimage.util import img_as_ubyte
Let’s set the paths to the input and output file folders we’re using as variables for easy access. My input files are in a folder at C:/FILES/leaves/, and I have an empty folder at C:/FILES/leaves converted/ for the output. The os.path submodule helps ensure that code to work with paths will w