imagestack.py 1.9 KB
import glob
import numpy
import progressbar
import skimage.io
import skimage.transform
import os

def load(fmask, dtype=numpy.float32):
    #read the input files
    F = glob.glob(fmask)
    if(len(F)==0):
        print("No image files found.")
        return
    
    #load the first file
    I = skimage.io.imread(F[0])
    
    #generate the image stack
    if I.ndim == 3:
    	S = numpy.zeros((len(F), I.shape[0], I.shape[1], I.shape[2]), dtype)
    else:
    	S = numpy.zeros((len(F), I.shape[0], I.shape[1]), dtype)
    
    bar = progressbar.ProgressBar(max_value=len(F))
    
    for i in range(0, len(F)):
        I = skimage.io.imread(F[i])
        S[i, ...] = I
        bar.update(i+1)
        
    return S

def rgb2gray(rgb):
    r, g, b = rgb[...,0], rgb[...,1], rgb[...,2]
    gray = 0.2989 * r + 0.5870 * g + 0.1140 * b

    return gray

def save(I, fname, extension = "bmp"):
    #output the final images
    bar = progressbar.ProgressBar(max_value=I.shape[0])
    #save the output files
    for i in range(0, I.shape[0]):        
        skimage.io.imsave(fname + "%03d" % i + "." + extension, I[i, ...])
        bar.update(i+1)

#rescale a stack of images along X and Y by an integer value n and save to directory dest        
def resize(fmask, dest, n, outformat=None):
    #read the input files
    F = glob.glob(fmask)
    if(len(F)==0):
        print("No image files found.")
        return
    
    #initialize a progress bar
    bar = progressbar.ProgressBar(max_value=len(F))
    
    #for each file
    for i in range(0, len(F)):
        
        #load the file to memory
        I = skimage.io.imread(F[i])
        R = skimage.transform.downscale_local_mean(I, (n, n))
        if outformat is None:
            skimage.io.imwrite(dest+"/"+os.path.basename(F[i]), R)
        else:
            skimage.io.imwrite(dest+"/"+os.path.basename(F[i]).split('.')[0] + "." + outformat, R)
        bar.update(i+1)