Blame view

python/phantom.py 1.4 KB
a69fee9d   David Mayerich   added python scri...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
  # -*- coding: utf-8 -*-
  """
  Created on Thu May 18 15:56:20 2017
  
  @author: david
  """
  
  import numpy as np
  import scipy as sp
  import scipy.misc
  import scipy.ndimage
  import matplotlib.pyplot as plt
  import os
  
  #calculate a 3D image from a 2D binary mask
  def binary(infile, sigma=2):
      
      I = sp.misc.imread(infile).astype(np.bool)
      
      #if the image has more than one channel, just keep the first one
      if(I.ndim == 3):
          I = I[:, :, 0]
      
      L = []
      while np.count_nonzero(I) != 0:
          L.append(I)
          I = sp.ndimage.binary_erosion(I)
          
      #create a 3D image representing the new stack    
      S = np.zeros( (I.shape[0], I.shape[1], len(L) * 2 - 1) )
      
      #for each image in the list
      for i in range(0, len(L)):
          if(i == 0):
              S[:, :, len(L) - 1] = L[0]
          else:
              S[:, :, len(L) - 1 + i] = L[i]
              S[:, :, len(L) - 1 - i] = L[i]
              
      S = sp.ndimage.filters.gaussian_filter(S, sigma)
      return S
  
  #generate a 3D image stack from a 2D binary mask
  def binary_stack(infile, outdir, sigma=2):
      outfile_base = os.path.basename(infile)
      outfile_prefix, outfile_ext = os.path.splitext(outfile_base)
      
      S = binary(infile, sigma)
  
      zcount = len(str(S.shape[2]))
      for f in range(0, S.shape[2]):
          fname = outdir + "/" + outfile_prefix + str(f).zfill(zcount) + outfile_ext
      
          sp.misc.imsave(fname, S[:, :, f])