util.py
Go to the documentation of this file.
00001 
00002 #Used for first set of util functions
00003 import os
00004 import numpy as np
00005 import pickle as pk
00006 import time
00007 # ** Do we need this? **
00008 ###from hrl_lib.msg import NumpyArray
00009 # ** removed dependancy for laser_camera_segmentation use **
00010 
00011 #Used for second set of util functions 
00012 from opencv.cv import *
00013 from opencv.highgui import *
00014 import numpy as np
00015 import Image as Image
00016 
00017 
00018 ## Returns a string that can be used as a timestamp (hours and minutes) in logfiles
00019 # @return timestamp-string
00020 def getTime():
00021     return '['+time.strftime("%H:%M:%S", time.localtime())+']'
00022 
00023 def standard_rad(t):
00024     if t > 0:
00025         return ((t + np.pi) % (np.pi * 2))  - np.pi
00026     else:
00027         return ((t - np.pi) % (np.pi * -2)) + np.pi
00028 
00029 ##
00030 # Converts a list of numpy matrices to one large matrix
00031 # @param list_mat the list of little matrices
00032 # @param axis axis to concatenate little matrices
00033 # @return one large numpy matrix
00034 def list_mat_to_mat(list_mat, axis=0):
00035     return np.concatenate(tuple(list_mat), axis=axis)
00036 
00037 
00038 ## returns current time as a string: year|month|date_hours|min|sec.
00039 ## @return current time as a string: year|month|date_hours|min|sec.
00040 def formatted_time():
00041     date_name = time.strftime('%Y%h%d_%H%M%S', time.localtime())
00042 #    curtime = time.localtime()
00043 #    date_name = time.strftime('%Y%m%d_%I%M%S', curtime)
00044     return date_name
00045 
00046 ## read a pickle and return the object.
00047 # @param filename - name of the pkl
00048 # @return - object that had been pickled.
00049 def load_pickle(filename):
00050     p = open(filename, 'r')
00051     picklelicious = pk.load(p)
00052     p.close()
00053     return picklelicious
00054 
00055 ## Pickle an object.
00056 # @param object - object to be pickled
00057 # @param filename - name of the pkl file
00058 def save_pickle(object, filename):
00059     pickle_file = open(filename, 'w')
00060     pk.dump(object, pickle_file)
00061     pickle_file.close()
00062 
00063 ## Calculate L2 norm for column vectors in a matrix 
00064 # @param mat - numpy matrix
00065 def norm(mat):
00066     return np.power(np.sum(np.power(mat,2), axis=0), 0.5)
00067 
00068 
00069 def approx_equal(a, b, epsilon=.001):
00070     return (b < (a+epsilon)) and ((a-epsilon) < b)
00071 
00072 
00073 def unipolar_limit( x, upper ):
00074     """ limit the value of x such that
00075         0 <= x <= upper
00076     """
00077 
00078     if x > upper:
00079         x=upper
00080     if x < 0:
00081         x=0
00082 
00083     return x
00084 
00085 def cart_of_pol(p):
00086    """ Finds cartesian coordinates of polar points [r, t]' """
00087    r = p[0,:]
00088    t = p[1,:]
00089    x = numpy.multiply(numpy.cos(t), r)
00090    y = numpy.multiply(numpy.sin(t), r)
00091    return numpy.vstack((x,y))
00092 
00093 def pol_of_cart(p):
00094     """ Find polar coordinates of cartesian points [x, y]' """
00095     norm = numpy.linalg.norm(p)
00096     ang = math.atan2(p[1,0], p[0,0])
00097     return numpy.matrix([norm, ang]).T
00098 
00099 ##
00100 # Bound the value of a number to be above lower, and lower than upper
00101 # @return a number
00102 def bound(value, lower, upper):
00103     if lower >= upper:
00104         t = lower
00105         lower = upper
00106         upper = t
00107 #    print 'bound', value, 'lower', lower, 'upper', upper
00108     #return min(max(value, lower), upper)
00109     ret_val = min(max(value, lower), upper)
00110 #    if ret_val != value:
00111 #        print 'ut.boud bounded something.'
00112     return ret_val
00113 
00114 
00115 
00116 ## wraps a numpy array into hrl's datatype for sending np arrays
00117 # over ros.
00118 # @param np array
00119 # @return NumpyArray object (hrl_lib/msg/NumpyArray.msg)
00120 def wrap_np_array(nparr):
00121     shp = nparr.shape
00122     npstr = nparr.tostring()
00123     npdtype = str(nparr.dtype)
00124     nparr_ros = NumpyArray(None,npstr,shp,npdtype)
00125     return nparr_ros
00126 
00127 ## convert hrl's ros wrapped numpy array to a numpy array
00128 # @param NumpyArray object (hrl_lib/msg/NumpyArray.msg)
00129 # @return np array
00130 def unwrap_np_array(nparr_ros):
00131     npstr,shp,npdtype = nparr_ros.data,nparr_ros.shape,nparr_ros.dtype
00132     nparr = np.fromstring(npstr,dtype=npdtype)
00133     nparr = nparr.reshape(shp)
00134     return nparr
00135 
00136 
00137 ## cartesian product of list of lists.
00138 # code copied from: http://automatthias.wordpress.com/2007/04/28/cartesian-product-of-multiple-sets/
00139 # @return generator. can loop over it, or list(generator) will give
00140 # the entire list.
00141 # NOTE - itertools in python 2.6 provides this functionality. We
00142 # should switch over to it soon.
00143 def cartesian_product(lists, previous_elements = []):
00144     if len(lists) == 1:
00145         for elem in lists[0]:
00146             yield previous_elements + [elem, ]
00147     else:
00148         for elem in lists[0]:
00149             for x in cartesian_product(lists[1:], previous_elements + [elem, ]):
00150                 yield x
00151 
00152 ## choose n elements from list without replacement.
00153 # adapted code from cartesian_product
00154 # @return generator.
00155 def choose_without_replacement(list, n):
00156     lists = [list for i in range(n)]
00157     return _choose_without_replacement(lists)
00158 
00159 def _choose_without_replacement(lists,previous_elements=[],ignore_count=0):
00160     if len(lists) == 1:
00161         for elem in lists[0][ignore_count:]:
00162             yield previous_elements + [elem, ]
00163     else:
00164         for i,elem in enumerate(lists[0][ignore_count:]):
00165             for x in _choose_without_replacement(lists[1:],previous_elements + [elem, ],ignore_count+i+1):
00166                 yield x
00167 
00168 ##
00169 # use festival text to speech to make a soud.
00170 # @param text - string to be said.
00171 def say(text):
00172     os.system( 'echo "' + text + '" | festival --tts' )
00173 
00174 
00175 ## compute rank of a matrix.
00176 # code copied from:
00177 # http://mail.scipy.org/pipermail/numpy-discussion/2008-February/031218.html
00178 def matrixrank(A,tol=1e-8):
00179     s = np.linalg.svd(A,compute_uv=0)
00180     return sum( np.where( s>tol, 1, 0 ) )
00181 
00182 ##################################################
00183 
00184 #!usr/bin/python
00185 #
00186 #util_additional.py
00187 #
00188 #The following definitions are utility and conversion definitions that used
00189 # to be part of the gt-ros-pkg scripts in hrl_lib/util.py
00190 #Since they have been taken out sometime during summer 2010, they are added
00191 # as explicit dependancies to the laser_camera_segmentation project.
00192 
00193 cv2np_type_dict = {CV_16S      : (np.int16, 1),  
00194                    CV_16SC1  : (np.int16, 1),   
00195                    CV_16SC2  : (np.int16, 2),   
00196                    CV_16SC3  : (np.int16, 3),   
00197                    CV_16SC4  : (np.int16, 4),   
00198                    CV_16U      : (np.uint16, 1),   
00199                    CV_16UC1  : (np.uint16, 1),   
00200                    CV_16UC2  : (np.uint16, 2),   
00201                    CV_16UC3  : (np.uint16, 3),   
00202                    CV_16UC4  : (np.uint16, 4),   
00203                    CV_32F      : (np.float32, 1),   
00204                    CV_32FC1  : (np.float32, 1),   
00205                    CV_32FC2  : (np.float32, 2),   
00206                    CV_32FC3  : (np.float32, 3),   
00207                    CV_32FC4  : (np.float32, 4),   
00208                    CV_32S      : (np.int32, 1),   
00209                    CV_32SC1  : (np.int32, 1),   
00210                    CV_32SC2  : (np.int32, 2),   
00211                    CV_32SC3  : (np.int32, 3),   
00212                    CV_32SC4  : (np.int32, 4),   
00213                    CV_64F      : (np.float64, 1),   
00214                    CV_64FC1  : (np.float64, 1),   
00215                    CV_64FC2  : (np.float64, 2),   
00216                    CV_64FC3  : (np.float64, 3),   
00217                    CV_64FC4  : (np.float64, 4),   
00218                    CV_8S    : (np.int8, 1),   
00219                    CV_8SC1    : (np.int8, 1),   
00220                    CV_8SC2    : (np.int8, 2),   
00221                    CV_8SC3    : (np.int8, 3),   
00222                    CV_8SC4    : (np.int8, 4),   
00223                    CV_8U    : (np.uint8, 1),   
00224                    CV_8UC1    : (np.uint8, 1),   
00225                    CV_8UC2    : (np.uint8, 2),   
00226                    CV_8UC3    : (np.uint8, 3),   
00227                    CV_8UC4    : (np.uint8, 4)}
00228 
00229 
00230 cv2np_type_dict_invertible = {CV_16SC1   : (np.int16, 1),   
00231                               CV_16SC2   : (np.int16, 2),   
00232                               CV_16SC3   : (np.int16, 3),   
00233                               CV_16SC4   : (np.int16, 4),   
00234                               CV_16UC1   : (np.uint16, 1),   
00235                               CV_16UC2   : (np.uint16, 2),   
00236                               CV_16UC3   : (np.uint16, 3),   
00237                               CV_16UC4   : (np.uint16, 4),   
00238                               CV_32FC1   : (np.float32, 1),   
00239                               CV_32FC2   : (np.float32, 2),   
00240                               CV_32FC3   : (np.float32, 3),   
00241                               CV_32FC4   : (np.float32, 4),   
00242                               CV_32SC1   : (np.int32, 1),   
00243                               CV_32SC2   : (np.int32, 2),   
00244                               CV_32SC3   : (np.int32, 3),   
00245                               CV_32SC4   : (np.int32, 4),   
00246                               CV_64FC1   : (np.float64, 1),   
00247                               CV_64FC2   : (np.float64, 2),   
00248                               CV_64FC3   : (np.float64, 3),   
00249                               CV_64FC4   : (np.float64, 4),   
00250                               CV_8SC1     : (np.int8, 1),   
00251                               CV_8SC2     : (np.int8, 2),   
00252                               CV_8SC3     : (np.int8, 3),   
00253                               CV_8SC4     : (np.int8, 4),   
00254                               CV_8UC1     : (np.uint8, 1),   
00255                               CV_8UC2     : (np.uint8, 2),   
00256                               CV_8UC3     : (np.uint8, 3),   
00257                               CV_8UC4     : (np.uint8, 4)}
00258 
00259 
00260 #def cv2np(im):
00261 #   numpy_type, nchannels = cv2np_type_dict[cv.cvGetElemType(im)]
00262 #   array_size = [im.height, im.width, nchannels]
00263 #   np_im = np.frombuffer(im.imageData, dtype=numpy_type)
00264 #   return np.reshape(np_im, array_size)
00265 
00266 def cv2np(im, format='RGB'):
00267     """This function converts an image from openCV format to a numpy array.
00268        This utility needs both NUMPY and OPENCV to accomplish the conversion.
00269        cv2np(im, format='RGB')
00270     """
00271     if format == 'BGR':
00272         cvCvtColor( im, im, CV_BGR2RGB )
00273     numpy_type, nchannels = cv2np_type_dict[cvGetElemType(im)]
00274     array_size = [im.height, im.width, nchannels]
00275     #Removed multiplication of size by (im.depth/8) as numpy takes
00276     #into account of that in numpy_type
00277 
00278     if im.__doc__ == None:
00279         # ctypes-opencv
00280         return im.as_numpy_array()
00281     else:
00282         np_im = np.array( np.frombuffer(im.imageData, dtype=numpy_type, 
00283                             count=im.height*im.width*nchannels))
00284 
00285     return np.reshape(np_im, array_size)
00286     
00287     
00288     
00289 def np2pil( im ):
00290     """ for grayscale - all values must be between 0 and 255.
00291             not sure about color yet.
00292         np2pil(im)
00293     """
00294     #TODO: print 'util.np2cv: works for texseg.py'
00295     #TODO: print 'util.np2cv: more extensive tests would be useful'
00296     if len(im.shape) == 3:
00297         shp = im.shape
00298         channels = shp[2]
00299         height, width = shp[0], shp[1]
00300     elif len(im.shape) == 2:
00301         height, width = im.shape
00302         channels = 1
00303     else:
00304         raise AssertionError("unrecognized shape for the input image. should be 3 or 2, but was %d." % len(im.shape))
00305 
00306     if channels == 3:
00307         image = Image.fromstring( "RGB", (width, height), im.tostring() )
00308     if channels == 1:
00309         im = np.array(im, dtype=np.uint8)
00310         #image = Image.fromarray(im)
00311         image = Image.fromstring( "L", (width, height), im.tostring() )
00312 
00313     return image
00314 
00315 
00316 if True:
00317     np2cv_type_dict = dict([(str(np.dtype(v[0])), v[1]), k] for
00318                            k,v in cv2np_type_dict_invertible.items())
00319 
00320 
00321     def np2cv(im, force_color=False):
00322         ''' Note: force_color -- force grayscale np image into a color cv image
00323             np2cv(im, force_color=False)
00324         '''
00325         image = np2pil( im )
00326         image.save('test.bmp', 'BMP')
00327         if len(im.shape) == 3:
00328             cvim = cvLoadImage('test.bmp')
00329         elif len(im.shape) == 2:
00330             if force_color == False:
00331                 cvim = cvLoadImage('test.bmp', CV_LOAD_IMAGE_GRAYSCALE)
00332             else:
00333                 cvim = cvLoadImage('test.bmp')
00334         else:
00335             raise AssertionError("unrecognized shape for the input image. should be 3 or 2, but was %d." % len(im.shape))
00336 
00337         return cvim
00338 


clutter_segmentation
Author(s): Jason Okerman, Martin Schuster, Advisors: Prof. Charlie Kemp and Jim Regh, Lab: Healthcare Robotics Lab at Georgia Tech
autogenerated on Wed Nov 27 2013 12:07:15