Skip to content

Instantly share code, notes, and snippets.

@leonidk
Last active June 6, 2016 05:14
Show Gist options
  • Save leonidk/df6baa17057a03942066 to your computer and use it in GitHub Desktop.
Save leonidk/df6baa17057a03942066 to your computer and use it in GitHub Desktop.
ImageJ TiFF Stack Reader
import sys,os,csv
from pylab import *
from PIL import Image
import time
#from mayavi import mlab
#returns a list (length = 3) of channels, each of which is a list (length = Z stack depth) of images
def getImages(fN):
returnArr= [ [], [], [] ]
tiff = Image.open(fN)
i = 0
while True:
try:
tiff.seek(i)
npa = ndarray((tiff.size[1],tiff.size[0]),uint64,array(tiff.getdata()))
returnArr[i%2].append(npa)
i += 1
except EOFError:
break
return returnArr
#given a list of images, displays them
def showImages(inList):
ion()
#close()
for p in inList:
fig = figure()
imshow(p,figure=fig,cmap='RdBu')
colorbar()
fig.canvas.draw()
pause(0.01)
#fig.canvas.flush_events()
ioff()
return 0
#given a list of images, computes statistics on them
def getStats(zS):
zA = array(zS)
zAF = array(zA.flatten())
rStats = {}
tzAF = zAF[zAF > 140]
rStats['num140'] = tzAF.shape[0]
rStats['prct140'] = 100 * tzAF.shape[0]/(1.0*zAF.shape[0])
rStats['mean140'] = mean(tzAF)
rStats['sum140'] = sum(tzAF)
autoThresh = sorted(zAF)[int(zAF.shape[0]*0.95)]
rStats['threshAuto'] = autoThresh
tzAF = zAF[zAF > autoThresh]
rStats['numAuto'] = tzAF.shape[0]
rStats['prctAuto'] = 100 * tzAF.shape[0]/(1.0*zAF.shape[0])
rStats['meanAuto'] = mean(tzAF)
rStats['sumAuto'] = sum(tzAF)
rStats['min'] = min(zAF)
rStats['sum'] = sum(zAF)
rStats['mean'] = mean(zAF)
rStats['max'] = max(zAF)
rStats['maxStack'] = where(zA == zA.max())[0][0]
return rStats
if __name__ == "__main__":
dirToProc = "./"
statNames = sorted(getStats(array([0xffffff])).keys(), key=lambda sName: sName[::-1]) #use reverse sorted names
if len(sys.argv) > 1:
dirToProc = sys.argv[1]
if dirToProc[-1] != '/':
dirToProc += '/'
if not os.path.isdir(dirToProc):
raise IOError(dirToProc + " is not a valid directory")
with open(dirToProc + 'stats.csv','wb') as outFile:
csvOut = csv.writer(outFile)
csvOut.writerow(['Filename'] + statNames)
for f in os.listdir(dirToProc):
fb, e = os.path.splitext(f)
if e != '.tif':
continue
#if '-' not in f:
#continue
try:
zStack = getImages(dirToProc + f)
#showImages(zStack[1])
stats = getStats(zStack[1]) #only use the second channel
csvOut.writerow([f] + [str(stats[n]) for n in statNames])
except:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment