Skip to content

Instantly share code, notes, and snippets.

@darencard
Created March 3, 2017 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darencard/8577ce1bb03083992dcc9a107c699456 to your computer and use it in GitHub Desktop.
Save darencard/8577ce1bb03083992dcc9a107c699456 to your computer and use it in GitHub Desktop.
Python script that determines image dimensions using ImageJ

Overview:

Below is a ImageJ Python script that will read a user-provided image file and output the width and height, with units, to stdout. This macro is designed to be called from the command line using the ImageJ executable. With my Mac OSX computer running Fiji, the path is /Applications/Fiji.app/Contents/MacOS/ImageJ-macosx. This has not been tested elsewhere and may not work without some effort. It relies on the Bio-Formats plugin to read the file and was written to convert from Zeiss's .czi files, so no guarantee that it works with others as desired. It is especially important to note that this does not set the scale, but infers it based on the metadata stored in the .czi files. Therefore, it will probably not work well with other file types.

Usage:

/Applications/Fiji.app/Contents/MacOS/ImageJ-macosx --headless get_image_dims.py input

Python script:

#!/usr/bin/env python

import sys
from loci.plugins import BF

infile = sys.argv[1]
imps = BF.openImagePlus(infile)
imp = imps[0]

cal = imp.getCalibration()

out_list = []
out_list.append(infile)
out_list.append(cal.pixelWidth * imp.getDimensions()[0])
out_list.append(cal.pixelHeight * imp.getDimensions()[1])
out_list.append(cal.unit)

sys.stdout.write('\t'.join(map(str, out_list)) + '\n')

Batching:

It is easy to batch process a set of files using simple Shell scripting. Here is an example that will process all .czi files in a directory. Given my installation always throws up a bunch of Java errors to stderr, I decided just to direct that to /dev/null.

for i in *.czi; do /Applications/Fiji.app/Contents/MacOS/ImageJ-macosx --headless get_image_dims.py $i 2> /dev/null; done

Additonal info:

Here are some links to pages where I extracted information useful for creating this script.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment