Package pyvision :: Package analysis :: Module ImageLog
[hide private]
[frames] | no frames]

Source Code for Module pyvision.analysis.ImageLog

  1  # PyVision License 
  2  # 
  3  # Copyright (c) 2006-2008 David S. Bolme 
  4  # All rights reserved. 
  5  # 
  6  # Redistribution and use in source and binary forms, with or without 
  7  # modification, are permitted provided that the following conditions 
  8  # are met: 
  9  #  
 10  # 1. Redistributions of source code must retain the above copyright 
 11  # notice, this list of conditions and the following disclaimer. 
 12  #  
 13  # 2. Redistributions in binary form must reproduce the above copyright 
 14  # notice, this list of conditions and the following disclaimer in the 
 15  # documentation and/or other materials provided with the distribution. 
 16  #  
 17  # 3. Neither name of copyright holders nor the names of its contributors 
 18  # may be used to endorse or promote products derived from this software 
 19  # without specific prior written permission. 
 20  #  
 21  #  
 22  # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
 23  # ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
 24  # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
 25  # A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR 
 26  # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
 27  # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
 28  # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
 29  # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
 30  # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
 31  # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 32  # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 33   
 34  import time 
 35  from os import makedirs,system,listdir 
 36  from os.path import join 
 37  import csv 
 38  import cPickle 
 39  import sys 
 40  import pyvision as pv 
 41   
42 -class ImageLog:
43 ''' 44 An image log is used to collect data about an experiment. This data can be 45 images, tables, pickled python objects. 46 ''' 47
48 - def __init__(self,topdir = "/tmp",name="pyvis_log"):
49 ''' 50 Create an image log. By default a log is created in the /tmp dir. 51 The name of the log directory start with the date and time the log 52 was created and ends with 'name'. 53 54 @param topdir: The location where the log directory will be created. 55 @param name: a name to append to the directory name. 56 ''' 57 self.date = time.strftime("%Y%m%d_%H%M%S") 58 self.name=name 59 self.dir = topdir+'/'+self.date+'_'+name 60 makedirs(self.dir) 61 self.count = 0
62 #print self.dir 63
64 - def __call__(self,item,*args, **kwargs):
65 if isinstance(item,pv.Image): 66 self.log(item,*args,**kwargs) 67 elif isinstance(item,pv.Timer): 68 self.table(item.table,*args,**kwargs) 69 elif isinstance(item,pv.Table): 70 self.table(item,*args,**kwargs) 71 elif isinstance(item,pv.Plot): 72 self.plot(item,*args,**kwargs) 73 else: 74 self.pickle(item,*args,**kwargs)
75
76 - def log(self,image,label="NOLABEL",ext='png',**kwargs):
77 ''' 78 Save a pyvision image to the log. 79 ''' 80 if kwargs.has_key('format'): 81 sys.stderr.write("WARNING: the format option to ImageLog.plot is no longer supported. Please use 'ext'") 82 ext = kwargs['format'] 83 del kwargs[format] 84 if len(kwargs) > 0: 85 raise ValueError("Unsupported keyword arguments: %s"(kwargs.keys(),)) 86 image.asAnnotated().save(self.dir+'/%06d_%s.%s'%(self.count,label,ext),quality=95) 87 self.count += 1
88 #print message 89
90 - def plot(self,plot,label="NOLABEL",ext='png',**kwargs):
91 ''' 92 Save a pyvision plot to the log. 93 ''' 94 if kwargs.has_key('format'): 95 sys.stderr.write("WARNING: the format option to ImageLog.plot is no longer supported. Please use 'ext'") 96 ext = kwargs['format'] 97 del kwargs[format] 98 if len(kwargs) > 0: 99 raise ValueError("Unsupported keyword arguments: %s"(kwargs.keys(),)) 100 plot.asImage().asAnnotated().save(self.dir+'/%06d_%s.%s'%(self.count,label,ext),quality=95) 101 self.count += 1
102 #print message 103
104 - def table(self,table,label="NOLABEL"):
105 ''' 106 Save a pyvision table to the log as a csv file. 107 ''' 108 filename = join(self.dir,'%06d_%s.csv'%(self.count,label)) 109 table.save(filename) 110 self.count += 1
111
112 - def csv(self,data,label="NOLABEL",headers=None):
113 ''' 114 Save a list of lists or matrix to the log as a csv file. 115 ''' 116 filename = join(self.dir,'%06d_%s.csv'%(self.count,label)) 117 writer = csv.writer(open(filename, "wb")) 118 if headers: 119 writer.writerow(headers) 120 writer.writerows(data) 121 self.count += 1
122 #print message 123
124 - def pickle(self,data,label="NOLABEL"):
125 ''' 126 Pickle a python data to the log directory. This may not be supported 127 by all objects. 128 129 ''' 130 filename = join(self.dir,'%06d_%s.pkl'%(self.count,label)) 131 f = open(filename,'wb') 132 cPickle.dump(data, f, protocol=2) 133 f.close() 134 self.count += 1
135
136 - def file(self,data=None,label="NOLABEL",ext='.dat'):
137 ''' 138 Write the buffer data to a file. If data == None then the file object is returned. 139 ''' 140 filename = join(self.dir,'%06d_%s%s'%(self.count,label,ext)) 141 self.count += 1 142 f = open(filename,'wb') 143 if data != None: 144 f.write(data) 145 f.close() 146 else: 147 return f
148
149 - def show(self):
150 ''' 151 Show any images that are in the directory. 152 ''' 153 files = listdir(self.dir) 154 file_list = "" 155 for each in files: 156 if len(file_list) > 30000: 157 sys.stderr.write("<ImageLog> Warning can't display all images.\n") 158 break 159 if each.split('.')[-1].upper() in ['JPG','PNG','TIFF','TIF','GIF']: 160 file_list += " %s/%s"%(self.dir,each) 161 162 if file_list == "": 163 sys.stderr.write('<ImageLog> No images to show.\n') 164 return 165 166 if sys.platform.startswith("darwin"): 167 system("open %s"%file_list) 168 elif sys.platform.startswith("linux"): 169 files.sort() 170 startfile = join(self.dir, files.pop(0)) 171 #gthumb will show thumbnails for all files in same directory as startfile. 172 #If you use KDE, gwenview might be better... 173 system("gthumb %s"%startfile) 174 elif sys.platform.startswith("windows"): 175 print "ImageLog.show() is not supported on windows."
176