RRtoolbox.lib package¶
Subpackages¶
Submodules¶
RRtoolbox.lib.cache module¶
platform: | Unix, Windows |
---|---|
synopsis: | Serialize and Memoize. |
Contains memoizing, caching, serializing and memory-mapping methods so as to let the package save its state (persistence) and to let a method “remember” what it processed in a session (with cache) or between sessions (memoization and serializization) of the same input contend once processed. It also wraps mmapping functions to let objects “live” in the disk (slower but almost unlimited) rather than in memory (faster but limited).
@cache is used as replacement of @property to compute a class method once. It is computed only one time after which an attribute of the same name is generated in its place.
@cachedProperty is used as replacement of @property to compute a class method depending on changes in its watched variables.
@memoize used as a general memoizer decorator for functions where metadata is generated to disk for persistence.
Made by Davtoh, powered by joblib. Dependent project: https://github.com/joblib/joblib
-
class
RRtoolbox.lib.cache.
Cache
(func)[source]¶ Bases:
future.types.newobject.newobject
Descriptor (non-data) for building an attribute on-demand at first use. @cache decorator is used for class methods without inputs (only self reference to the object) and it caches on first compute. ex:
class x(object): @cache def method_x(self): return self.data
Note
Cached data can be deleted in the decorated object to recalculate its value.
-
class
RRtoolbox.lib.cache.
DynamicMemoizedFunc
(func, cachedir=None, ignore=None, mmap_mode=None, compress=False, verbose=1, timestamp=None, banned=False)[source]¶ Bases:
future.types.newobject.newobject
-
cachedir
¶
-
compress
¶
-
enabled
¶
-
func
¶
-
ignore
¶
-
mmap_mode
¶
-
verbose
¶
-
-
class
RRtoolbox.lib.cache.
LazyDict
(getter, dictionary=None)[source]¶ Bases:
_abcoll.MutableMapping
Create objects on demand if needed. call the instance with keys to prevent it from using lazy evaluations (e.g. instead of self[key] use self(key) to prevent recursion). Containing operations are safe to prevent recursion (e.g. if key in self instead of self[key]). In addition use self.isLazy flag to enable or disable lazy operations to prevent possible recursions when getter is called.
-
class
RRtoolbox.lib.cache.
MemoizedDict
(path, mode=None)[source]¶ Bases:
_abcoll.MutableMapping
Memoized dictionary with keys and values persisted to files.
Parameters: - path – path to save memo file
- mode – loading mode from memo file {None, ‘r+’, ‘r’, ‘w+’, ‘c’}
Note
If saveAtKey is True it will attempt to memoize each time a keyword is added and throw an error if not successful. But if saveAtKey is False this process will be carried out when the MemoizedDict instance is being destroyed in a proper deletion, that is, if the program ends unexpectedly all data will be lost or if data cannot be saved it will be lost without warning.
Warning
Some data structures cannot be memoize, so this structure is not save yet. Use at your own risk.
-
class
RRtoolbox.lib.cache.
Memoizer
(ignore=(), ignoreAll=False)[source]¶ Bases:
future.types.newobject.newobject
-
ignore
¶
-
makememory
(cachedir=None, mmap_mode=None, compress=False, verbose=0)[source]¶ Make memory for
memoize()
decorator.Parameters: - cachedir – path to save metadata, if left None function is not cached.
- mmap_mode – {None, ‘r+’, ‘r’, ‘w+’, ‘c’}, optional. The memmapping mode used when loading from cache numpy arrays. See numpy.load for the meaning of the arguments.
- compress – (boolean or integer) Whether to zip the stored data on disk. If an integer is given, it should be between 1 and 9, and sets the amount of compression. Note that compressed arrays cannot be read by memmapping.
- verbose – (int, optional) Verbosity flag, controls the debug messages that are issued as functions are evaluated.
Returns:
-
memoize
(memory=None, ignore=None, verbose=0, mmap_mode=False)[source]¶ Decorated functions are faster by trading memory for time, only hashable values can be memoized.
Parameters: - memory – (Memory or path to folder) if left None function is not cached.
- ignore – (list of strings) A list of arguments name to ignore in the hashing.
- verbose – (integer) Verbosity flag, controls the debug messages that are issued as functions are evaluated.
- mmap_mode – {None, ‘r+’, ‘r’, ‘w+’, ‘c’}, optional. The memmapping mode used when loading from cache numpy arrays. See numpy.load for the meaning of the arguments.
Returns: decorator
-
memoizers
= {139810276534992: <weakref at 0x7f281ddf2418; to 'Memoizer' at 0x7f281dde6ad0>}¶
-
-
class
RRtoolbox.lib.cache.
MemorizedFunc
(func, cachedir, ignore=None, mmap_mode=None, compress=False, verbose=1, timestamp=None)[source]¶ Bases:
joblib.memory.MemorizedFunc
-
class
RRtoolbox.lib.cache.
Memory
(cachedir, mmap_mode=None, compress=False, verbose=1)[source]¶ Bases:
joblib.memory.Memory
A wrapper to joblib Memory to have better control.
-
class
RRtoolbox.lib.cache.
ObjectGetter
(callfunc=None, obj=None, callback=None, **annotations)[source]¶ Bases:
future.types.newobject.newobject
Creates or get instance object depending if it is alive.
-
create
(throw=False)[source]¶ Creates an object and keep reference.
Parameters: throw – if there is not creation function throws error. Returns: created object. Warning
previous object reference is lost even if it was alive.
Note
Recommended only to use when object from current reference is dead.
-
-
class
RRtoolbox.lib.cache.
ResourceManager
(maxMemory=None, margin=0.8, unit='MB', all=True)[source]¶ Bases:
RRtoolbox.lib.cache.Retriever
keep track of references, create objects on demand, manage their memory and optimize for better performance.
Parameters: - maxMemory – (None) max memory in specified unit to keep in check optimization (it does not mean that memory never surpasses maxMemory).
- margin – (0.8) margin from maxMemory to trigger optimization. It is in percentage of maxMemory ranging from 0 (0%) to maximum 1 (100%). So optimal memory is inside range: maxMemory*margin < Memory < maxMemory
- unit – (MB) maxMemory unit, it can be GB (Gigabytes), MB (Megabytes), B (bytes)
- all – if True used memory is from all alive references, if False used memory is only from keptAlive references.
-
all
¶ Returns: all flag, if True: used memory is from all alive references, if False: used memory is only from keptAlive references.
-
margin
¶ Returns: margin used for triggering memory optimization from maxMemory.
-
maxMemory
¶
-
register
(key, method=None, instance=None)[source]¶ Register object to retrieve.
Parameters: - key – hashable key to retrieve
- method – callable method to get object
- instance – object instance already created from method
Note
This method is used in __setitem__ as self.register(key, value). Overwrite this method to change key assignation behaviour.
Example:
def mymethod(): class constructor: pass return constructor() ret = retriever() ret["obj"] = mymethod # register creating method in "obj" im = ret["obj"] # get object (created obj +1, with reference) assert im is ret["obj"] # check that it gets the same object # it remembers that "obj" is last registered or fetched object too assert ret() is ret() # lets register with better control (created obj2 +1, no reference) ret.register("obj2",mymethod(),mymethod) # proves that obj2 is not the same as obj (created obj2 +1, no reference) assert ret() is not ret["obj"] print list(ret.iteritems()) # get items
-
static
resetGetter
(getter)[source]¶ Helper function to reset getter parameters.
Parameters: getter – any instance of objectGetter
-
unit
¶ Returns: user defined units
-
usedMemory
¶ Returns: used memory in user units
-
class
RRtoolbox.lib.cache.
Retriever
[source]¶ Bases:
_abcoll.MutableMapping
keep track of references and create objects on demand if needed.
-
register
(key, method=None, instance=None)[source]¶ Register object to retrieve.
Parameters: - key – hashable key to retrieve
- method – callable method to get object
- instance – object instance already created from method
Returns: Example:
def mymethod(): class constructor: pass return constructor() ret = retriever() ret["obj"] = mymethod # register creating method in "obj" im = ret["obj"] # get object (created obj +1, with reference) assert im is ret["obj"] # check that it gets the same object # it remembers that "obj" is last registered or fetched object too assert ret() is ret() # lets register with better control (created obj2 +1, no reference) ret.register("obj2",mymethod(),mymethod) # proves that obj2 is not the same as obj (created obj2 +1, no reference) assert ret() is not ret["obj"] print list(ret.iteritems()) # get items
-
-
RRtoolbox.lib.cache.
cachedProperty
(watch=[], handle=[])[source]¶ A memoize decorator of @property decorator specifying what to trigger caching.
Parameters: - watch – (list of strings) A list of arguments name to watch in the hashing.
- handle – (list of handles or empty list) Provided list is appended with the Memo handle were data is stored for the method and where a clear() function is provided.
Returns:
-
RRtoolbox.lib.cache.
mapper
(path, obj=None, mode=None, onlynumpy=False)[source]¶ Save and load or map live objects to disk to free RAM memory.
Parameters: - path – path to save mapped file.
- obj – the object to map, if None it tries to load obj from path if exist
- mode – {None, ‘r+’, ‘r’, ‘w+’, ‘c’}.
- onlynumpy – if True, it saves a numpy mapper from obj.
Returns: mmap image, names of mmap files
RRtoolbox.lib.config module¶
platform: | Unix, Windows |
---|---|
synopsis: | Looking for a reference? look here!. |
This module contains all config data to the package.
-
class
RRtoolbox.lib.config.
ConfigTool
[source]¶ Bases:
future.types.newobject.newobject
Manage the configured Tools.
-
class
RRtoolbox.lib.config.
DirectoryManager
(path=None, raiseError=True, autosave=False)[source]¶ Bases:
future.types.newobject.newobject
Manage the configured variables, paths and files.
Parameters: - path – (None) path to configuration file. If None uses default path.
- raiseError – True to raise when not attribute in ConfigFile.
- autosave – (True) if True saves at each change.
Note
Any attribute that is not in ConfigFile returns None. Use raiseError to control this behaviour.
-
default
¶ get directories from dictionary representing environment variables.
Returns: dictionary of directories. Note
Only directories in the scope of the module are detected.
-
load
()[source]¶ loads the configuration file and update.
Returns: loaded configuration file dictionary. Warning
Unsaved instance variables will be replaced by configuration file variables.
-
RRtoolbox.lib.config.
findModules
(package, exclude=None)[source]¶ Find modules from a package.
Parameters: - package – imported packaged or path (str).
- exclude – list of modules to exclude.
Returns: dictionary containing importer, ispkg
-
RRtoolbox.lib.config.
getModules
(package, exclude=None)[source]¶ Import modules from a package.
Parameters: package – imported packaged or path (str). Returns: dictionary containing imported modules.
RRtoolbox.lib.descriptors module¶
-
RRtoolbox.lib.descriptors.
ASIFT
(feature_name, img, mask=None, pool=<multiprocessing.pool.ThreadPool object>)[source]¶ asift(feature_name, img, mask=None, pool=None) -> keypoints, descrs
Apply a set of affine transformations to the image, detect keypoints and reproject them into initial image coordinates. See http://www.ipol.im/pub/algo/my_affine_sift/ for the details.
ThreadPool object may be passed to speedup the computation.
Parameters: - feature_name – feature name to create detector.
- img – image to find keypoints and its descriptors
- mask – mask to detect keypoints (it uses default, mask[:] = 255)
- pool – multiprocessing pool (dummy, it uses multithreading)
Returns: keypoints,descriptors
-
RRtoolbox.lib.descriptors.
ASIFT_iter
(imgs, feature_name='sift-flann')[source]¶ Affine-SIFT for N images.
Parameters: - imgs – images to apply asift
- feature_name – eg. SIFT SURF ORB
Returns: [(kp1,desc1),...,(kpN,descN)]
-
RRtoolbox.lib.descriptors.
ASIFT_multiple
(imgs, feature_name='sift-flann')[source]¶ Affine-SIFT for N images.
Parameters: - imgs – images to apply asift
- feature_name – eg. SIFT SURF ORB
Returns: [(kp1,desc1),...,(kpN,descN)]
-
class
RRtoolbox.lib.descriptors.
Feature
(pool=<multiprocessing.pool.ThreadPool object>, useASIFT=True, debug=True)[source]¶ Bases:
future.types.newobject.newobject
Class to manage detection and computation of features
Parameters: - pool – multiprocessing pool (dummy, it uses multithreading)
- useASIFT – if True adds Affine perspectives to the detector.
- debug – if True prints to the stdout debug messages.
-
RRtoolbox.lib.descriptors.
MATCH
(feature_name, kp1, desc1, kp2, desc2)[source]¶ Use matcher and asift output to obtain Transformation matrix (TM).
Parameters: - feature_name – feature name to create detector. It is the same used in the detector which is used in init_feature function but the detector itself is ignored. e.g. if ‘detector’ uses BFMatcher, if ‘detector-flann’ uses FlannBasedMatcher.
- kp1 – keypoints of source image
- desc1 – descriptors of kp1
- kp2 – keypoints of destine image
- desc2 – descriptors of kp2
Returns: TM
-
RRtoolbox.lib.descriptors.
MATCH_multiple
(pairlist, feature_name='sift-flann')[source]¶ Parameters: - pairlist – list of keypoint and descriptors pair e.g. [(kp1,desc1),...,(kpN,descN)]
- feature_name – feature name to create detector
Returns: [(H1, mask1, kp_pairs1),....(HN, maskN, kp_pairsN)]
-
RRtoolbox.lib.descriptors.
affine_skew
(tilt, phi, img, mask=None)[source]¶ Increase robustness to descriptors by calculating other invariant perspectives to image.
Parameters: - tilt – tilting of image
- phi – rotation of image (in degrees)
- img – image to find Affine transforms
- mask – mask to detect keypoints (it uses default, mask[:] = 255)
Returns: skew_img, skew_mask, Ai (invert Affine Transform)
Ai - is an affine transform matrix from skew_img to img
-
RRtoolbox.lib.descriptors.
filter_matches
(kp1, kp2, matches, ratio=0.75)[source]¶ This function applies a ratio test.
Parameters: - kp1 – raw keypoints 1
- kp2 – raw keypoints 2
- matches – raw matches
- ratio – filtering ratio of distance
Returns: filtered keypoint 1, filtered keypoint 2, keypoint pairs
-
RRtoolbox.lib.descriptors.
init_feature
(name, separator='-', features={})[source]¶ This function takes parameters from a command to initialize a detector and matcher.
Parameters: - name – “<sift|surf|orb>[-flann]” (str) Ex: “sift-flann”
- separator – separator character
- features – it is a dictionary containing the mapping from name to the initialized detector, matcher pair. If None it is created. This feature is to reduce time by reusing created features.
Returns: detector, matcher
RRtoolbox.lib.directory module¶
This module holds all path manipulation methods and a string concept called directory (referenced paths and strings)
designed to support config
and be used with session
.
keywords:¶
path: it can be to a folder or file or url if specified filename: the file name without its path filepath: the path to a file dirname: the path to a folder url: Universal Resource Locator
-
class
RRtoolbox.lib.directory.
Directory
[source]¶ Bases:
str
semi-mutable string representation of a inmutable string with support for path representations.
Parameters: - data – list, directory instance, dictionary or string.
- ispath – True to add support for paths.
- copy – when data is a directory if copy is True then this instance data is independent of the passed directory otherwise both directories are a reference to the same dictionary data but they are not the same object.
- kwargs – additional data to add in directory.
-
correctSTRBuiltin
()[source]¶ Decorate all the built-in functions of class directory.
Returns: built-in decorated function.
-
static
filterdata
(data, ispath=None, kwargs=None)[source]¶ Adequate data for dictionary creation.
Parameters: - data – any supported object.
- ispath – True to add support for paths.
- kwargs – additional data to add in directory.
Returns: dictionary
-
static
repr2list
(data, level=0)[source]¶ Converts the representation of a directory.repr to pickleable.
Parameters: data – directory.repr of the form [“string”,directory,...,directory.repr]. Returns: pickleable list.
-
static
repr2str
(data, ispath=True)[source]¶ Converts the representation of a directory.repr to string.
Parameters: data – directory.repr of the form [“string”,directory,...,directory.repr]. Returns: converted string.
-
update
(data=None)[source]¶ Return an updated copy with provided data.
Parameters: data – any supported object. If None return updated and referenced copy of itself. Returns: new directory referenced to itself.
-
class
RRtoolbox.lib.directory.
FileDirectory
[source]¶ Bases:
RRtoolbox.lib.directory.Directory
Saves contents of a file as with directories.
Parameters: - data – list, directory instance, dictionary or string.
- filename – name of file.
- path – path to folder where file is (it must finish in /).
- notes – optional description string
- kwargs – additional data to add in directory.
-
RRtoolbox.lib.directory.
changedir
(filepath, dirname, ext=True)[source]¶ Change path to file with dirname.
Parameters: - filepath – path to file.
- dirname – new path to replace in filepath.
- ext – True to keep extension of file if any.
Returns: directory object of changed path.
-
RRtoolbox.lib.directory.
checkDir
(dirname)[source]¶ checks if dirname exists.
Parameters: dirname – path to folder Returns: True if exits, False if not
-
RRtoolbox.lib.directory.
checkFile
(path)[source]¶ checks if filepath or filename exists.
Parameters: path – filepath or filename Returns: True if exits, False if not
-
RRtoolbox.lib.directory.
checkPath
(path)[source]¶ checks if path exists.
Parameters: path – path to folder or file. Returns: True if exits, False if not
-
RRtoolbox.lib.directory.
checkURL
(url)[source]¶ checks if url exists. :param url: path to url :return: True if exits, False if not
-
RRtoolbox.lib.directory.
correctPath
(path, relative)[source]¶ Get path corrected from its relative path or level index.
Parameters: - path – path or file name.
- relative – pattern or level in directory.
Returns: corrected path.
-
RRtoolbox.lib.directory.
correctSep
(path='/mnt/4E443F99443F82AF/Dropbox/PYTHON/RRtools/RRtoolbox/lib/directory.pyc', separator='/')[source]¶ Replaces the path separators by custom or OS standard separator.
Parameters: - path – relative or absolute path (str). Default is __file__ or module’s path.
- separator – desired separators, By default uses system separator (os.path.sep).
Returns: path with corrected separator.
-
RRtoolbox.lib.directory.
decoratePath
(relative, sep='/')[source]¶ Decorated path is controlled to give absolute path from relative path.
Parameters: - relative – int or path.
- sep – path separator
Returns: decorator
-
RRtoolbox.lib.directory.
getData
(path='/mnt/4E443F99443F82AF/Dropbox/PYTHON/RRtools/RRtoolbox/lib/directory.pyc')[source]¶ Get standard path from path.
Parameters: path – it can be to a folder or file. Default is __file__ or module’s path. Returns: [drive,dirname,filename,ext]. 1. drive or UNC (Universal Naming Convention) 2. dirname is path to folder. 3. filename is name of file. 4. ext is extension of file.
-
RRtoolbox.lib.directory.
getFileHandle
(path)[source]¶ Gets a file handle from url or disk file.
Parameters: path – filepath or url Returns: file object
-
RRtoolbox.lib.directory.
getFileSize
(path)[source]¶ Gets a size from url or disk file.
Parameters: path – filepath or url Returns: size in bytes
-
RRtoolbox.lib.directory.
getPath
(path='/mnt/4E443F99443F82AF/Dropbox/PYTHON/RRtools/RRtoolbox/lib/directory.pyc')[source]¶ Get standard path from path. It supports ~ as home directory.
Parameters: path – it can be to a folder or file. Default is __file__ or module’s path. If file exists it selects its folder. Returns: dirname (path to a folder) Note
It is the same as os.path.dirname(os.path.abspath(path)).
-
RRtoolbox.lib.directory.
getSep
(path, pattern='/\\')[source]¶ Get path separator or indicator.
Parameters: - path – relative or absolute path (str).
- pattern – guess characters to compare path (str).
Returns: sep (str).
Note
It is equivalent to os.path.sep but obtained from the given path and patterns.
-
RRtoolbox.lib.directory.
getShortenedPath
(path, comp)[source]¶ Path is controlled to give absolute path from relative path or integer.
Parameters: - path – absolute path (str).
- comp – pattern or relative path (str) or integer representing level of folder determined by the separator Ex. “/level 1/level 2/.../level N or -1”.
Returns: path before matched to comp Ex: “C://level 1//comp –> C://level 1”
Example:
>>> path = 'LEVEL1/LEVEL2/LEVEL3/LEVEL4/LEVEL5' >>> print getShortenedPath(path,-2) # minus two levels LEVEL1/LEVEL2/LEVEL3 >>> print getShortenedPath(path,2) # until three levels LEVEL1/LEVEL2 >>> print getShortenedPath(path,'LEVEL1/LEVEL2/LEVEL3/') LEVEL1/LEVEL2/LEVEL3/ >>> print getShortenedPath(path,'LEVEL4/REPLACE5/NEWLEVEL') LEVEL1/LEVEL2/LEVEL3/LEVEL4/REPLACE5/NEWLEVEL >>> print getShortenedPath(path,'../../SHOULD_BE_LEVEL4') LEVEL1/LEVEL2/LEVEL3/SHOULD_BE_LEVEL4
-
RRtoolbox.lib.directory.
getSplitted
(path='/mnt/4E443F99443F82AF/Dropbox/PYTHON/RRtools/RRtoolbox/lib/directory.pyc')[source]¶ Splits a file path by its separators.
Parameters: path – it can be to a folder or file. Default is __file__ or module’s path. Returns: splitted path.
-
RRtoolbox.lib.directory.
increment_if_exits
(path, add='_{num}', force=None)[source]¶ Generates new name if it exits.
Parameters: - path – absolute path or filename
- add – if fn exists add pattern
- force – (None) force existent files even if they don’t. if True treats fn as existent or if it is a list it treats names from the list as existent names.
Returns: un-existent fn
-
RRtoolbox.lib.directory.
joinPath
(absolute, relative)[source]¶ Joins an absolute path to a relative path.
Parameters: - absolute – directory or path.
- relative – directory or path.
Returns: joined path.
Note
It is equivalent to os.path.join but works with directories.
-
RRtoolbox.lib.directory.
mkPath
(path)[source]¶ Make path (i.e. creating folder) for filepath.
Parameters: path – path to nonexistent folder or file. Returns: created path.
-
RRtoolbox.lib.directory.
quickOps
(path, comp)[source]¶ (IN DEVELOPMENT) make quick matching operations in path.
Parameters: - path – path to folder
- comp – pattern
Returns: Requirements:
path = 'LEVEL1/LEVEL2/LEVEL3/LEVEL4/LEVEL5' print quickOps(path,'../ROOT/../LEVEL1/../LEVEL2/LEVEL3/../../LEVEL4') 'LEVEL4' print quickOps(path,'ROOT/../LEVEL1/LEVEL2/../../LEVEL4') 'LEVEL3/LEVEL4' print quickOps(path,'../LEVEL2/../') 'LEVEL1/LEVEL3/LEVEL4/LEVEL5' print quickOps(path,'../LEVEL2/..') 'LEVEL1/LEVEL3/LEVEL4/LEVEL5/' print quickOps(path,'LEVEL2/../../LEVEL4/') 'LEVEL2/LEVEL3/LEVEL4/' print quickOps(path,'ROOT/../LEVEL2/../../LEVEL4') 'ROOT/LEVEL3/LEVEL4' print quickOps(path,'LEVEL-1/../NEW7/LEVEL8') 'LEVEL-1/LEVEL1/LEVEL2/LEVEL3/LEVEL4/LEVEL5/NEW7/LEVEL8' print
-
RRtoolbox.lib.directory.
resource_path
(relative_path='')[source]¶ Get absolute path to resource, works for dev and for PyInstaller
-
RRtoolbox.lib.directory.
rmFile
(filepath)[source]¶ Remove file.
Parameters: filepath – path to file. Returns: None
-
RRtoolbox.lib.directory.
rmPath
(path, ignore_errors=False, onerror=None)[source]¶ Remove path from path.
Parameters: path – path to nonexistent folder or file. Returns: None See also
shutil.rmtree
-
RRtoolbox.lib.directory.
strdifference
(s1, s2)[source]¶ Get string differences.
Parameters: - s1 – string 1
- s2 – string 2
Returns: (splitted string 1, splitted string 2, index). A splitted string is a list with the string parts. Index is a list containing the indexes of different parts of the two splitted strings.
RRtoolbox.lib.image module¶
Bundle of methods for handling images. Rather than manipulating specialized operations in images methods in this module are used for loading, outputting and format-converting methods, as well as color manipulation.
SUPPORTED FORMATS
see http://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html#imread
Format | Extension |
---|---|
Windows bitmaps | *.bmp, *.dib (always supported) |
JPEG files | *.jpeg, *.jpg, *.jpe (see the Notes section) |
JPEG 2000 files | *.jp2 (see the Notes section) |
Portable Network Graphics | *.png (see the Notes section) |
Portable image format | *.pbm, *.pgm, *.ppm (always supported) |
Sun rasters | *.sr, *.ras (always supported) |
TIFF files | *.tiff, *.tif (see the Notes section) |
-
class
RRtoolbox.lib.image.
GetCoors
(im, win='get coordinates', updatefunc=<function drawcoorpoints>, unique=True, col_out=(0, 0, 0), col_in=(0, 0, 255))[source]¶ Bases:
RRtoolbox.lib.plotter.Plotim
Create window to select points from image.
Parameters: - im – image to get points.
- win – window name.
- updatefunc – function to draw interaction with points. (e.g. limitaxispoints, drawcoorperspective, etc.).
- prox – proximity to identify point.
- radius – radius of drawn points.
- unique – If True no point can be repeated, else selected points can be repeated.
- col_out – outer color of point.
- col_in – inner color of point.
-
coors
¶
-
class
RRtoolbox.lib.image.
ImCoors
(pts, dtype=<type 'numpy.float32'>, deg=False)[source]¶ Bases:
future.types.newobject.newobject
Image’s coordinates class. Example:
a = ImCoors(np.array([(116, 161), (295, 96), (122, 336), (291, 286)])) print a.__dict__ print "mean depend on min and max: ", a.mean print a.__dict__ print "after mean max has been already been calculated: ", a.max a.data = np.array([(116, 161), (295, 96)]) print a.__dict__ print "mean and all its dependencies are processed again: ", a.mean
-
boundingRect
()[source]¶ Rectangular box dimensions enclosing points.
example:
P = np.ones((400,400)) a = ImCoors(np.array([(116, 161), (295, 96), (122, 336), (291, 286)])) x0,y0,w,h = a.boundingRect P[y0:y0+h,x0:x0+w] = 0
Returns: x0,y0,w,h
-
center
()¶ Center or mean. :return: x,y
-
dtype
¶
-
pointsAngles
()[source]¶ Angle of vectors formed by points in Cartesian plane with respect to x axis.
i.e. angle between vector “v01” (formed by points “p0-p1”) and vector unity in axis x.
Returns: angles.
-
pts
¶
-
rectangularArea
()[source]¶ Area of rectangle enclosing points aligned with x,y axes.
Returns: area number
-
rectangularity
()[source]¶ Ratio that represent a perfect square aligned with x,y axes.
Returns: ratio from 1 to 0, 1 representing a perfect rectangle.
-
rectbox
()[source]¶ Rectangular box enclosing points (origin and end point or rectangle).
Returns: (x0,y0),(x,y)
-
regularity
()[source]¶ Ratio of forms with similar measurements and angles. e.g. squares and rectangles have rect angles so they are regular. For regularity object must give 1.
Returns:
-
relativeVectors
()[source]¶ Form vectors from points.
Returns: array of vectors [V0, ... , (V[n] = x[n+1]-x[n],y[n+1]-y[n])].
-
rotatedRectangularity
()[source]¶ Ratio that represent a perfect rotated square fitting points.
Returns: ratio from 1 to 0, 1 representing a perfect rotated rectangle.
-
-
class
RRtoolbox.lib.image.
ImFactory
(**kwargs)[source]¶ Bases:
future.types.newobject.newobject
image factory for RRToolbox to create scripts to standardize loading images and provide lazy loading (it can load images from disk with the customized options and/or create mapping images to load when needed) to conserve memory.
Warning
In development.
-
class
RRtoolbox.lib.image.
ImLoader
(path, flag=0, dsize=None, dst=None, fx=None, fy=None, interpolation=None, mmode=None, mpath=None, throw=True)[source]¶ Bases:
future.types.newobject.newobject
Class to load image array from path, url, server, string or directly from numpy array (supports databases).
Parameters: - flag –
(default: 0) 0 to read as gray, 1 to read as BGR, -1 to read as BGRA, 2 to read as RGB, -2 to read as RGBA.
- It supports openCV flags:
- cv2.CV_LOAD_IMAGE_COLOR
- cv2.CV_LOAD_IMAGE_GRAYSCALE
- cv2.CV_LOAD_IMAGE_UNCHANGED
value openCV flag output N/A RGB cv2.CV_LOAD_IMAGE_COLOR BGR cv2.CV_LOAD_IMAGE_GRAYSCALE GRAY (-1) cv2.CV_LOAD_IMAGE_UNCHANGED BGRA (-2) N/A RGBA - dsize –
(None) output image size; if it equals zero, it is computed as:
exttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}
- dst – (None) output image; it has the size dsize (when it is non-zero) or the size computed from src.size(), fx, and fy; the type of dst is uint8.
- fx –
scale factor along the horizontal axis; when it equals 0, it is computed as
exttt{(double)dsize.width/src.cols}
- fy –
scale factor along the vertical axis; when it equals 0, it is computed as
exttt{(double)dsize.height/src.rows}
- interpolation –
interpolation method compliant with opencv:
flag Operation Description INTER_NEAREST nearest-neighbor interpolation INTER_LINEAR bilinear interpolation (used by default) INTER_CUBIC bicubic interpolation over 4x4 pixel neighborhood INTER_AREA resampling using pixel area relation. It may be a preferred method for image decimation, as it gives moire’-free results. But when the image is zoomed, it is similar to the INTER_NEAREST method. INTER_LANCZOS4 Lanczos interpolation over 8x8 pixel neighborhood - mmode – (None) mmode to create mapped file. if mpath is specified loads image, converts to mapped file and then loads mapping file with mode {None, ‘r+’, ‘r’, ‘w+’, ‘c’} (it is slow for big images). If None, loads mapping file to memory (useful to keep image copy for session even if original image is deleted or modified).
- mpath – (None) path to create mapped file. None, do not create mapping file “”, uses path directory; “*”, uses working directory; else, uses specified directory.
Note
If mmode is None and mpath is given it creates mmap file but loads from it to memory. It is useful to create physical copy of data to keep loading from (data can be reloaded even if original file is moved or deleted).
- flag –
-
class
RRtoolbox.lib.image.
Image
(name=None, ext=None, path=None, shape=None, verbosity=False)[source]¶ Bases:
future.types.newobject.newobject
Structure to load and save images
-
BGR
¶
-
BGRA
¶
-
RGB
¶
-
RGBA
¶
-
ext
¶
-
gray
¶
-
path
¶
-
save
(name=None, image=None, overwrite=None)[source]¶ save restored image in path.
Parameters: - name – filename, string to format or path to save image. if path is not a string it would be replaced with the string “{path}restored_{name}{ext}” to format with the formatting “{path}”, “{name}” and “{ext}” from the baseImage variable.
- image – (self.BGRA)
- overwrite – If True and the destine filename for saving already exists then it is replaced, else a new filename is generated with an index “{filename}_{index}.{extension}”
Returns: saved path, status (True for success and False for fail)
-
shape
¶
-
-
class
RRtoolbox.lib.image.
LoaderDict
(loader=None, maxMemory=None, margin=0.8, unit='MB', all=True, config=None)[source]¶ Bases:
RRtoolbox.lib.cache.ResourceManager
Class to standardize loading objects and manage memory efficiently.
Parameters: - loader – default loader for objects (e.g. load from file or create instance object)
- maxMemory – (None) max memory in specified unit to keep in check optimization (it does not mean that memory never surpasses maxMemory).
- margin – (0.8) margin from maxMemory to trigger optimization. It is in percentage of maxMemory ranging from 0 (0%) to maximum 1 (100%). So optimal memory is inside range: maxMemory*margin < Memory < maxMemory
- unit – (MB) maxMemory unit, it can be GB (Gigabytes), MB (Megabytes), B (bytes)
- all – if True used memory is from all alive references, if False used memory is only from keptAlive references.
- config – (Not Implemented)
-
class
RRtoolbox.lib.image.
PathLoader
(fns=None, loader=None)[source]¶ Bases:
_abcoll.MutableSequence
Class to standardize loading images from list of paths and offer lazy evaluations.
Parameters: - fns – list of paths
- loader – path loader (loadcv,loadsfrom, or function from loadFunc)
Also see::
loadcv()
,loadsfrom()
,loadFunc()
Example:
fns = ["/path to/image 1.ext","/path to/image 2.ext"] imgs = pathLoader(fns) print imgs[0] # loads image in path 0 print imgs[1] # loads image in path 1
-
RRtoolbox.lib.image.
bgra2bgr
(im, bgrcolor=(255, 255, 255))[source]¶ Convert BGR to BGRA image.
Parameters: - im – image
- bgrcolor – BGR color representing transparency. (information is lost when converting BGRA to BGR) e.g. [200,200,200].
Returns:
-
RRtoolbox.lib.image.
checkLoaded
(obj, fn='', raiseError=False)[source]¶ Simple function to determine if variable is valid.
Parameters: - obj – loaded object
- fn – path of file
- raiseError – if True and obj is None, raise
Returns: None
-
RRtoolbox.lib.image.
convertAs
(fns, base=None, folder=None, name=None, ext=None, overwrite=False, loader=None, simulate=False)[source]¶ Reads a file and save as other file based in a pattern.
Parameters: - fns – file name or list of file names. It supports glob operations. By default glob operations ignore folders.
- base – path to place images.
- folder – (None) folder to place images in base’s path. If True it uses the folder in which image was loaded. If None, not folder is used.
- name – string for formatting new name of image with the {name} tag. Ex: if name is ‘new_{name}’ and image is called ‘img001’ then the formatted new image’s name is ‘new_img001’
- ext – (None) extension to save all images. If None uses the same extension as the loaded image.
- overwrite – (False) If True and the destine filename for saving already exists then it is replaced, else a new filename is generated with an index “{name}_{index}.{extension}”
- loader – (None) loader for the image file to change image attributes. If None reads the original images untouched.
- simulate – (False) if True, no saving is performed but the status is returned to confirm what images where adequately processed.
Returns: list of statuses (0 - no error, 1 - image not loaded, 2 - image not saved, 3 - error in processing image)
-
RRtoolbox.lib.image.
drawcoorarea
(vis, points, col_out=(0, 0, 0), col_in=(0, 0, 255), radius=2)[source]¶ Function to draw interaction with points to obtain area.
Parameters: - vis – image array.
- points – list of points.
- col_out – outer color of point.
- col_in – inner color of point.
- radius – radius of drawn points.
Returns:
-
RRtoolbox.lib.image.
drawcooraxes
(vis, points, col_out=(0, 0, 0), col_in=(0, 255, 0), radius=2)[source]¶ Function to draw axes instead of points.
Parameters: - vis – image array.
- points – list of points.
- col_out – outer color of point.
- col_in – inner color of point.
- radius – radius of drawn points.
Returns:
-
RRtoolbox.lib.image.
drawcoorperspective
(vis, points, col_out=(0, 0, 0), col_in=(0, 0, 255), radius=2)[source]¶ Function to draw interaction with points to obtain perspective.
Parameters: - vis – image array.
- points – list of points.
- col_out – outer color of point.
- col_in – inner color of point.
- radius – radius of drawn points.
Returns:
-
RRtoolbox.lib.image.
drawcoorpoints
(vis, points, col_out=(0, 0, 0), col_in=(0, 0, 255), radius=2)[source]¶ Funtion to draw points.
Parameters: - vis – image array.
- points – list of points.
- col_out – outer color of point.
- col_in – inner color of point.
- radius – radius of drawn points.
Returns:
-
RRtoolbox.lib.image.
drawcoorpolyArrow
(vis, points, col_out=(0, 0, 0), col_in=(0, 0, 255), radius=2)[source]¶ Function to draw interaction with vectors to obtain polygonal.
Parameters: - vis – image array.
- points – list of points.
- col_out – outer color of point.
- col_in – inner color of point.
- radius – radius of drawn points.
Returns:
-
RRtoolbox.lib.image.
drawcoorpolyline
(vis, points, col_out=(0, 0, 0), col_in=(0, 0, 255), radius=2)[source]¶ Function to draw interaction with points to obtain polygonal.
Parameters: - vis – image array.
- points – list of points.
- col_out – outer color of point.
- col_in – inner color of point.
- radius – radius of drawn points.
Returns:
-
RRtoolbox.lib.image.
fig2bgr
(fig)[source]¶ Convert a Matplotlib figure to a RGB image.
Parameters: fig – a matplotlib figure Returns: RGB image.
-
RRtoolbox.lib.image.
fig2bgra
(fig)[source]¶ Convert a Matplotlib figure to a RGBA image.
Parameters: fig – a matplotlib figure Returns: RGBA image.
-
RRtoolbox.lib.image.
getcoors
(im, win='get coordinates', updatefunc=<function drawcoorpoints>, coors=None, prox=8, radius=3, unique=True, col_out=(0, 0, 0), col_in=(0, 0, 255))[source]¶
-
RRtoolbox.lib.image.
getgeometrycoors
(*data)[source]¶ Get filled object coordinates. (function in progress)
-
RRtoolbox.lib.image.
getrectcoors
(*data)[source]¶ - Get ordered points.
Parameters: data – list of points Returns: [Top_left,Top_right,Bottom_left,Bottom_right]
-
RRtoolbox.lib.image.
gray2qi
(gray)[source]¶ Convert the 2D numpy array gray into a 8-bit QImage with a gray colormap. The first dimension represents the vertical image axis.
ATTENTION: This QImage carries an attribute ndimage with a reference to the underlying numpy array that holds the data. On Windows, the conversion into a QPixmap does not copy the data, so that you have to take care that the QImage does not get garbage collected (otherwise PyQt will throw away the wrapper, effectively freeing the underlying memory - boom!).
source from: https://kogs-www.informatik.uni-hamburg.de/~meine/software/vigraqt/qimage2ndarray.py
-
RRtoolbox.lib.image.
hist_match
(source, template, alpha=None)[source]¶ Adjust the pixel values of an image to match those of a template image.
Parameters: - source – image to transform colors to template
- template – template image ()
- alpha –
Returns: transformed source
-
RRtoolbox.lib.image.
interpretImage
(toparse, flags)[source]¶ Interprets to get image.
Parameters: - toparse –
string to parse or array. It can interpret:
- connection to server (i.e. host:port)
- path to file (e.g. /path_to_image/image_name.ext)
- URL to image (e.g. http://domain.com/path_to_image/image_name.ext)
- image as string (i.g. numpy converted to string)
- image itself (i.e. numpy array)
- flags –
openCV flags:
value openCV flag output cv2.CV_LOAD_IMAGE_COLOR BGR cv2.CV_LOAD_IMAGE_GRAYSCALE GRAY (-1) cv2.CV_LOAD_IMAGE_UNCHANGED format
Returns: image or None if not successfull
- toparse –
-
RRtoolbox.lib.image.
limitaxispoints
(c, maxc, minc=0)[source]¶ Limit a point in axis.
Parameters: - c – list of points..
- maxc – maximum value of point.
- minc – minimum value of point.
Returns: return limited points.
-
RRtoolbox.lib.image.
loadFunc
(flag=0, dsize=None, dst=None, fx=None, fy=None, interpolation=None, mmode=None, mpath=None, throw=True, keepratio=True)[source]¶ Creates a function that loads image array from path, url, server, string or directly from numpy array (supports databases).
Parameters: - flag –
(default: 0) 0 to read as gray, 1 to read as BGR, -1 to read as BGRA, 2 to read as RGB, -2 to read as RGBA.
- It supports openCV flags:
- cv2.CV_LOAD_IMAGE_COLOR
- cv2.CV_LOAD_IMAGE_GRAYSCALE
- cv2.CV_LOAD_IMAGE_UNCHANGED
value openCV flag output N/A RGB cv2.CV_LOAD_IMAGE_COLOR BGR cv2.CV_LOAD_IMAGE_GRAYSCALE GRAY (-1) cv2.CV_LOAD_IMAGE_UNCHANGED BGRA (-2) N/A RGBA - dsize –
(None) output image size; if it equals zero, it is computed as:
exttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}If (integer,None) or (None,integer) it completes the values according to keepratio parameter.
- dst – (None) output image; it has the size dsize (when it is non-zero) or the size computed from src.size(), fx, and fy; the type of dst is uint8.
- fx – scale factor along the horizontal axis
- fy – scale factor along the vertical axis
- interpolation –
interpolation method compliant with opencv:
flag Operation Description INTER_NEAREST nearest-neighbor interpolation INTER_LINEAR bilinear interpolation (used by default) INTER_CUBIC bicubic interpolation over 4x4 pixel neighborhood INTER_AREA resampling using pixel area relation. It may be a preferred method for image decimation, as it gives moire’-free results. But when the image is zoomed, it is similar to the INTER_NEAREST method. INTER_LANCZOS4 Lanczos interpolation over 8x8 pixel neighborhood - mmode – (None) mmode to create mapped file. if mpath is specified loads image, converts to mapped file and then loads mapping file with mode {None, ‘r+’, ‘r’, ‘w+’, ‘c’} (it is slow for big images). If None, loads mapping file to memory (useful to keep image copy for session even if original image is deleted or modified).
- mpath – (None) path to create mapped file. None, do not create mapping file “”, uses path directory; “*”, uses working directory; else, uses specified directory.
- keepratio – True to keep image ratio when completing data from dsize,fx and fy, False to not keep ratio.
Note
If mmode is None and mpath is given it creates mmap file but loads from it to memory. It is useful to create physical copy of data to keep loading from (data can be reloaded even if original file is moved or deleted).
:return loader function
- flag –
-
RRtoolbox.lib.image.
loadcv
(path, flags=-1, shape=None)[source]¶ Simple function to load using opencv.
Parameters: - path – path to image.
- flag –
openCV flags:
value openCV flag output cv2.CV_LOAD_IMAGE_COLOR BGR cv2.CV_LOAD_IMAGE_GRAYSCALE GRAY (-1) cv2.CV_LOAD_IMAGE_UNCHANGED format - shape – shape to resize image.
Returns: loaded image
-
RRtoolbox.lib.image.
loadsfrom
(path, flags=1L)[source]¶ Loads Image from URL or file.
Parameters: - path – filepath or url
- flags –
openCV flags:
value openCV flag output cv2.CV_LOAD_IMAGE_COLOR BGR cv2.CV_LOAD_IMAGE_GRAYSCALE GRAY (-1) cv2.CV_LOAD_IMAGE_UNCHANGED format
Returns:
-
RRtoolbox.lib.image.
myline
(img, pt1, pt2, color, thickness=None)[source]¶ Funtion to draw points (experimental).
Parameters: - img –
- pt1 –
- pt2 –
- color –
- thickness –
Returns:
-
RRtoolbox.lib.image.
np2qi
(array)[source]¶ Convert numpy array to Qt Image.
source from: https://kogs-www.informatik.uni-hamburg.de/~meine/software/vigraqt/qimage2ndarray.py
Parameters: array – Returns:
-
RRtoolbox.lib.image.
qi2np
(qimage, dtype='array')[source]¶ Convert QImage to numpy.ndarray. The dtype defaults to uint8 for QImage.Format_Indexed8 or bgra_dtype (i.e. a record array) for 32bit color images. You can pass a different dtype to use, or ‘array’ to get a 3D uint8 array for color images.
source from: https://kogs-www.informatik.uni-hamburg.de/~meine/software/vigraqt/qimage2ndarray.py
-
RRtoolbox.lib.image.
quadrants
(points)[source]¶ Separate points respect to center of gravity point.
Parameters: points – list of points Returns: [[Top_left],[Top_right],[Bottom_left],[Bottom_right]]
-
RRtoolbox.lib.image.
random_color
(channels=1, min=0, max=256)[source]¶ Random color.
Parameters: - channels – number of channels
- min – min color in any channel
- max – max color in any channel
Returns: random color
-
RRtoolbox.lib.image.
rgb2qi
(rgb)[source]¶ Convert the 3D numpy array rgb into a 32-bit QImage. rgb must have three dimensions with the vertical, horizontal and RGB image axes.
ATTENTION: This QImage carries an attribute ndimage with a reference to the underlying numpy array that holds the data. On Windows, the conversion into a QPixmap does not copy the data, so that you have to take care that the QImage does not get garbage collected (otherwise PyQt will throw away the wrapper, effectively freeing the underlying memory - boom!).
source from: https://kogs-www.informatik.uni-hamburg.de/~meine/software/vigraqt/qimage2ndarray.py
-
RRtoolbox.lib.image.
separe
(values, sep, axis=0)[source]¶ Separate values from separator or threshold.
Parameters: - values – list of values
- sep – peparator value
- axis – axis in each value
Returns: lists of greater values, list of lesser values
-
RRtoolbox.lib.image.
try_loads
(fns, func=<built-in function imread>, paths=None, debug=False, addpath=False)[source]¶ Try to load images from paths.
Parameters: - fns – list of file names
- func – loader function
- paths – paths to try. By default it loads working dir and test path
- debug – True to show debug messages
- addpath – add path as second argument
Returns: image else None
RRtoolbox.lib.inspector module¶
This module is an all purpose intended for debugging, tracking, auto-documenting and self-introspecting the package
Made by Davtoh. Powered partially by pycallgraph. Dependent project: https://github.com/gak/pycallgraph/#python-call-graph
-
class
RRtoolbox.lib.inspector.
GraphTrace
(output=None, config=None)[source]¶ Bases:
pycallgraph.pycallgraph.PyCallGraph
-
source
¶
-
-
class
RRtoolbox.lib.inspector.
GraphTraceOutput
(source=None, saveflag=True, label='', **kwargs)[source]¶ Bases:
pycallgraph.output.graphviz.GraphvizOutput
-
class
RRtoolbox.lib.inspector.
Logger
(**kwargs)[source]¶ Bases:
future.types.newobject.newobject
Logger for decorated functions. Holds important information of an instanced object and can be used with @trace decorator for traceback purposes.
Parameters: - func – object reference.
- funcname – object name.
- inputs – inputs pass to the object.
- outputs – outputs given by the object execution.
- time – initial time of execution.
- exectime – time of execution in seconds.
- writer – writer function where messages are passed.
- eventHandle – event function where object is passed when Logger.broadcast() is called.
- msg_report – message format to use in reports.
- msg_no_executed – massage format to pass to writer when object has not been executed and Logger.report() is called.
- msg_executed – massage format to use when object is executed and Logger.broadcast() is called.
-
Time_
¶ returns formated time (str)
-
Type_
¶ returns type name (str)
-
eventHandle
= None¶
-
file
= <open file '<stdout>', mode 'w'>¶
-
tracer
¶
-
class
RRtoolbox.lib.inspector.
Syncronous
(outputs, config)[source]¶ Bases:
pycallgraph.tracer.SyncronousTracer
RRtoolbox.lib.plotter module¶
This module holds the plotting and data-visualization tools. Motto: don’t know how it is interpreted? i’ll show you!
#Plotim example filename = “t2.jpg” win = “test” img = cv2.resize(cv2.imread(filename), (400, 400)) # (height, width) plot = Plotim(win,img) plot.show()
-
class
RRtoolbox.lib.plotter.
Edger
(img, isSIZE=True, isEQUA=False, isCLAHE=False, isBFILTER=False)[source]¶ Bases:
RRtoolbox.lib.plotter.Plotim
Test visualization for edges
self.edge -> the edges in processed image self.img -> the processed image self.sample -> the rendered precessed image
-
getParameters
(params=('d', 'sigmaColor', 'sigmaSpace', 'clipLimit', 'tileGridSize', 'isSIZE', 'isEQUA', 'isCLAHE', 'isBFILTER', 'th1', 'th2', 'size', 'apertureSize', 'L2gradient'))[source]¶
-
isBFILTER
¶
-
isCLAHE
¶
-
isEQUA
¶
-
isSIZE
¶
-
maxth
¶
-
showgray
¶
-
size
¶
-
th1
¶
-
th2
¶
-
-
class
RRtoolbox.lib.plotter.
Imtester
(img, win='Imtester plot')[source]¶ Bases:
RRtoolbox.lib.plotter.Plotim
Used to test some concepts as thresholds and filters
-
class
RRtoolbox.lib.plotter.
MatchExplorer
(win, img1, img2, kp_pairs=(), status=None, H=None, show=True, block=True, daemon=True)[source]¶ Bases:
RRtoolbox.lib.plotter.Plotim
Draws a set of keypoint pairs obtained on a match method of a descriptor on two images imgf and imgb. (backend: Plotim).
Parameters: - win – window’s name (str)
- img1 – image1 (numpy array)
- img2 – image2 (numpy array)
- kp_pairs – zip(keypoint1, keypoint2)
- status – obtained from cv2.findHomography
- H – obtained from cv2.findHomography (default=None)
- show – if True shows Plotim using block and daemon, else do not show
- block – if True it wait for window close, else it detaches
- daemon – if True window closes if main thread ends, else windows must be closed to main thread to end
Returns: Plotim object with visualization as self.rimg (image with matching result) (default=None)
Note
It supports BGR and gray images.
-
class
RRtoolbox.lib.plotter.
Plotim
(win, im=array([[1]]), bgrcolor=(250, 243, 238))[source]¶ Bases:
future.types.newobject.newobject
Show and image with events, animations, controls, internal commands and highly customizable by code.
Parameters: - win – window name
- im – image of numpy array
- bgrcolor – default color to use for transparent or background color.
Warning
Plotim is deprecated and will be replaced in the future (it was made to test concepts). Originally it was made for windows but some functions were removed to let it be multi-platform.
-
builtincontrol
(control=False)[source]¶ Internal control. use self.usecontrol = True to activate.
Parameters: control – if True, use control key. Returns:
-
builtinplot
(pixel=None, useritems=None, flag=1, xpad=0, ypad=0, bgrcolor=None, alpha=None)[source]¶ Internal plot.
Parameters: - pixel – pixel color where mouse is placed (placed for better control). Color can be from real image, showed image, original image or rendered image, or any color.
- useritems – items to show.
- flag –
flag for position (default=0).
- flag==0 : foreground to left up.
- flag==1 : foreground to left down.
- flag==2 : foreground to right up.
- flag==3 : foreground to right down.
- flag==4 : foreground at center of background.
- flag==5 : XY 0,0 is at center of background.
- flag==6 : XY 0,0 is at center of foreground.
- flag==7 : XY 0,0 is at right down of foreground.
- xpad – padding in x
- ypad – padding in y
- bgrcolor – background color
- alpha – alpha mask or value for transparency
Returns:
-
clean
()[source]¶ Attempt to clean the plotter dictionary for an error in garbage collection. :return:
-
closefunc
()[source]¶ Decoupled close function for Plotim (replace self.closefunc).
Parameters: self – Plotim instance
-
cmdfunc
(execute=False)[source]¶ command function and decoupled cmd solver for Plotim. (repalce self.cmdfunc)
Parameters: - self –
- execute – True, enable execution of commands, False, disable execution.
-
errorbackground
¶
-
formatcmd
(cmd, references=('+', '-', '*', '='), lmissing='self.')[source]¶ Decoupled cmd formatter for cmdfunc and Plotim.
Parameters: - self – Plotim instance
- cmd – command
- references –
- lmissing – assumed missing part in command
Returns:
-
init
()[source]¶ Pseudo __init__. it is used to restart default values without destroying configurations.
-
keyfunc
()[source]¶ Decoupled key function for Plotim (replace self.keyfunc).
Parameters: self – Plotim instance
-
makeoverlay
(items, xpad=0, ypad=0, bgrcolor=None, alpha=None)[source]¶ overlay items over image.
Parameters: - self – instance
- items – list of object to overlay
- xpad – pad in x
- ypad – pad in y
- bgrcolor – background color
- alpha – transparency color
Returns: overlayed
-
mousefunc
()[source]¶ Decoupled mouse function for Plotim (replace self.mousefunc).
Parameters: self – Plotim instance
-
static
onmouse
(event, x, y, flags, self)[source]¶ Mouse event function for Plotim. (replace self.mousefunc)
Parameters: - event – mouse event
- x – x position
- y – y postion
- flags – mouse flag to use in control (it represents clicks)
- self – Plotim object
Returns:
-
plotatpointer
(items, img=None, x=0, y=0, flag=6, xpad=0, ypad=0, bgrcolor=None, alpha=None, pixel=None)[source]¶ Plot message where mouse pointer is.
Parameters: - items – list of items supported by
self.makeoverlay()
- img – image to place in items. If None it uses self.remg
- x – x position
- y – y position
- flag –
flag for position (default=0).
- flag==0 : foreground to left up.
- flag==1 : foreground to left down.
- flag==2 : foreground to right up.
- flag==3 : foreground to right down.
- flag==4 : foreground at center of background.
- flag==5 : XY 0,0 is at center of background.
- flag==6 : XY 0,0 is at center of foreground.
- flag==7 : XY 0,0 is at right down of foreground.
- xpad – padding in x
- ypad – padding in y
- bgrcolor – background color
- alpha – alpha mask or value for transparency
- pixel – color to add as item im items,
Returns: Also see::
convertXY()
,self.makeoverlay()
- items – list of items supported by
-
plotatxy
(items, img=None, x=0, y=0, flag=0, xpad=0, ypad=0, bgrcolor=None, alpha=None)[source]¶ Plot message in xy position.
Parameters: - items – list of items supported by
makeoverlay()
- img – image to place in items. If None it uses self.remg
- x – x position
- y – y position
- flag –
flag for position (default=0).
- flag==0 : foreground to left up.
- flag==1 : foreground to left down.
- flag==2 : foreground to right up.
- flag==3 : foreground to right down.
- flag==4 : foreground at center of background.
- flag==5 : XY 0,0 is at center of background.
- flag==6 : XY 0,0 is at center of foreground.
- flag==7 : XY 0,0 is at right down of foreground.
- xpad – padding in x
- ypad – padding in y
- bgrcolor – background color
- alpha – alpha mask or value for transparency
Returns: - items – list of items supported by
-
plotintime
(items=None, wait=2, img=None, bgrcolor=None)[source]¶ plots messages and events.
Parameters: - items – list of items supported by
makeoverlay()
- wait – time of message.
- img – image to place in items. If None it uses self.remg
- bgrcolor – color of message.
Returns: - items – list of items supported by
-
real2render
(x, y, astype=None)[source]¶ from real coordinates get rendered coordinates.
Parameters: - x – real x
- y – real y
- astype – (np.int32) return as the specified type
Returns: rendered x, rendered y
-
render2real
(rx, ry, astype=<type 'numpy.int32'>)[source]¶ from rendered coordinates get real coordinates.
Parameters: - rx – rendered x
- ry – rendered y
- astype – (np.int32) return as the specified type
Returns: real x, real y
-
rx1
¶
-
rx2
¶
-
ry1
¶
-
ry2
¶
-
save
(strname=None, ext='.png', name='img')[source]¶ Save image (save image if not Qt backend is installed).
Parameters: - strname – name to save, a label with {win} can be used to be replaced with the plot win name
- ext – (”.png”) extension.
- name – (“img”) name of image object from self. default is “img” that is self.img (it allows better control to get custom image)
Returns: True if saved, False if not saved (possibly because folder does not exists)
-
show
(frames=None, block=True, daemon=False, clean=True)[source]¶ Show function. calls buildinwindow, handles key presses and close events.
Parameters: - frames – show number of frames and close.
- block – if True it wait for window close, else it detaches (Experimental)
- daemon – if True window closes if main thread ends, else windows must be closed to main thread to end (Experimental)
Returns:
-
showfunc
(img=None)[source]¶ Decoupled show function for Plotim (replace self.showfunc).
Parameters: - self – Plotim instance
- img – image to show
-
textbackground
¶
-
RRtoolbox.lib.plotter.
background
(color, x=1, y=1, flag=0)[source]¶ Creates background rectangle.
Parameters: - color – main color.
- x – x pixels in axis x.
- y – y pixels in axis y.
- flag – Not implemented.
Returns: image of shape y,x and ndim == color.ndim.
-
RRtoolbox.lib.plotter.
convert2bgr
(src, bgrcolor=None)[source]¶ Tries to convert any image format to BGR.
Parameters: - src – source image.
- bgrcolor – background or transparent color.
Returns: BGR array image.
-
RRtoolbox.lib.plotter.
convert2bgra
(src, bgracolor=None, transparency=None)[source]¶ Tries to convert any image format to BGRA.
Parameters: - src – source image.
- bgracolor – background or transparent color.
- transparency – mask or A channel. (typically source image has not A channel, so user can provide it)
Returns: BGRA array image.
-
RRtoolbox.lib.plotter.
echo
(obj)[source]¶ Printer (used when user wants to print an object from Plotim) :param obj: object
-
RRtoolbox.lib.plotter.
fastplt
(image, cmap=None, title='visualazor', win=None, block=False, daemon=False)[source]¶ Fast plot.
Parameters: - image – image to show
- cmap – “gray” or None
- title – title of subplot
- win – title of window
- block – if True it wait for window close, else it detaches (Experimental)
- daemon – if True window closes if main thread ends, else windows must be closed to main thread to end (Experimental)
Returns: plt
Note
This is a wrapper of the module fastplt.
-
RRtoolbox.lib.plotter.
graph_filter
(filters, levels=None, titles=None, win=None, single=True, legend=True, annotate=True, cols=3, scale=0.07, show=True, lxp=None, lyp=None)[source]¶ Graph filter with standard data to watch response.
Parameters: - filters – list of filters
- levels – numpy array with values. if None tries to fit data or assumes from 0 to 255
- titles – list of titles for each filter in filters. if None creates the titles
- win – window name
- single – True to plot all filters in one plot. else separate each filter in a plot.
- legend – True to add legends.
- annotate – True to add annotations.
- cols – number of columns to create plots
- scale – factor from maximum to draw annotations
- show – to show the figure
Returns: figure
-
RRtoolbox.lib.plotter.
limitaxis
(c, maxc, minc=0)[source]¶ Limit value in axis.
Parameters: - c – value
- maxc – max c value.
- minc – min c value.
Returns: limited c value c E [minc,maxc]
-
RRtoolbox.lib.plotter.
plotPointsContour
(pts, ax=None, lcor='k', pcor=None, deg=None, annotate=True, width=0.004, label='pt{pt}({x}, {y}, {a})', arrowprops=None)[source]¶ Plots points and joining lines in axes.
Parameters: - pts – points. [(x0,y0)...(xN,yN)]
- ax – axes handle to draw points.
- lcor – color of joining lines.
- pcor – color of points. If specified uses lines, else vectors.
- deg – angle of vertex, if True in degrees, if False in radians, if None do not add.
- annotate – (True) True to annotate
- width – adjust width of lines
- label – string to format point labels. add the point with {pt}, x and y coordinates with {x} and {y}, and angle with {a}. By default label is ‘pt{pt}({x}, {y}, {a})’.
- arrowprops – dictionary to modify array properties
Returns: axes
RRtoolbox.lib.root module¶
This module holds core-like methods for library modules but not for the hole package
-
exception
RRtoolbox.lib.root.
ClassNotAllowed
[source]¶ Bases:
exceptions.Exception
Exception to denote that given class is not allowed
-
class
RRtoolbox.lib.root.
Controlstdout
(disable=True, buffer=None)[source]¶ Bases:
future.types.newobject.newobject
Context manager to control output to stdout
Parameters: - disable – if True suppress output.
- buffer – (None) if True creates a buffer to collect all data printed to the stdout which can be retrieved with self.buffered. A file can be given but if it is write-only it cannot retrieve data to self.buffered so “w+” is recommended to be used with self.buffered.
Warning
If a reference to sys.stdout is kept before the Controlstdout instance then output can be printed trough it and cannot be controlled by the Controlstdout context.
-
exception
RRtoolbox.lib.root.
CorruptPersistent
[source]¶ Bases:
exceptions.EOFError
,exceptions.IOError
Used for persistent data read from disk like pickles to denote it has been corrupted
-
class
RRtoolbox.lib.root.
FactorConvert
(factor=None, abbreviate=True)[source]¶ Bases:
future.types.newobject.newobject
Keep track of factor and converts to any available factor.
-
convert
(factor, to=None)[source]¶ Convert from actual factor to another factor.
Parameters: - factor – number
- to – factor to convert
Returns: converted value, units
-
convert2sample
(factor, to=None)[source]¶ Convert to resemble sample.
Parameters: - factor – number
- to – sample factor.
Returns: converted value, units
-
exactFactorIndex
(key)[source]¶ Find the index of a factor that contains a key.
Parameters: key – anything to look in factors (i.e. factor name, factor value, abbreviation). Returns: factor structure, else None.
-
factor
¶
-
factors
¶
-
getFactor
(key)[source]¶ Tries to find factor value in factors.
Parameters: key – anything to look in factors (i.e. factor name, factor value, abbreviation). If key is a factor value it will look for the nearest factor value. Returns: factor structure, else raises error.
-
nearFactorIndex
(factor)[source]¶ Find the index of nearest factor value.
Parameters: factor – factor value. Returns: factor structure near factor value.
-
-
class
RRtoolbox.lib.root.
Magnitude
(value=0, factor=None, unit=None, precision=None, abbreviate=False)[source]¶ Bases:
future.types.newobject.newobject
-
class
RRtoolbox.lib.root.
NameSpace
[source]¶ Bases:
future.types.newobject.newobject
Used to store variables
-
exception
RRtoolbox.lib.root.
NoParserFound
[source]¶ Bases:
exceptions.Exception
Raise when no parser is found to use in a shell i.e to interpret user input
-
exception
RRtoolbox.lib.root.
NotCallable
[source]¶ Bases:
exceptions.Exception
Defines objectGetter error: given object is not callable.
-
exception
RRtoolbox.lib.root.
NotConvertibleToInt
[source]¶ Bases:
exceptions.ValueError
Exception to denote that value cannot be represented as int
-
exception
RRtoolbox.lib.root.
NotCreatable
[source]¶ Bases:
exceptions.Exception
Defines objectGetter error: objectGetter cannot create new object.
-
class
RRtoolbox.lib.root.
Profiler
(msg=None, tag=None)[source]¶ Bases:
future.types.newobject.newobject
profiler for code points.
Parameters: - msg – custom comment for profiling point
- tag – classification tag
- space – (” ”)
- format_line – (“{space}{tag}{msg}{time}”)
- format_structure – (“\n{space}[{tag}{msg}{time}{child}]{side}”)
- points – profile instaces which are divided in “side” or “children” points according if they are side by side or are inside of the profiler.
-
formatter
(level, tag, msg, time)[source]¶ format profiling point arguments.
Parameters: - level –
- tag – classification tag
- msg – custom comment of profiling point
- time – time of profiling
Returns: formatted (spacing, tag, msg, time)
-
lines_formatted
(collapse=None)[source]¶ generate string lines
Parameters: collapse – list for collapsing repeated tags or messages. Returns: list of lines
-
lines_unformatted
(collapse=None)[source]¶ generate structure lines
Parameters: collapse – list for collapsing repeated tags or messages. Returns: generator with outputs (level, tag, msg, time)
-
open_point
(msg=None, tag=None)[source]¶ Open a profiling point to track time.
Parameters: - msg – custom comment for profiling point
- tag – classification tag
Returns:
-
restructure
(structure, collapse)[source]¶ reprocess an already created structure.
Parameters: - structure – structure.
- collapse – list for collapsing repeated tags or messages.
Returns: reprocessed structure
-
string_structured
(collapse=None, structure=None)[source]¶ string with plain structure of profiling
Parameters: - collapse – list for collapsing repeated tags or messages.
- structure – (None) uses and already created structure. If None it creates the structure.
Returns: string
-
structure
(collapse=None)[source]¶ profiling structure.
Parameters: collapse – list for collapsing repeated tags or messages. Returns: structure with format [tag,msg,time,children]
-
time
¶ Returns: overall time of profiling
-
class
RRtoolbox.lib.root.
StdoutLOG
(path, mode='w+', add_stdout=True)[source]¶ Bases:
RRtoolbox.lib.root.StdoutMULTI
Simple logger to save stdout output so anything printed in the console is logged to a file.
Parameters: - path – path to logging file
- mode – mode for opening the file.
- add_stdout – if True closes previous logs and continues with new log
-
class
RRtoolbox.lib.root.
StdoutMULTI
(file_list)[source]¶ Bases:
future.types.newobject.newobject
Enclose several file-like objects.
:param file_list = list of file-like objects
-
class
RRtoolbox.lib.root.
StdoutSIM
(stdout=None, closed=False)[source]¶ Bases:
future.types.newobject.newobject
Simple logger to simulate stdout output adding a closed control
-
class
RRtoolbox.lib.root.
TimeCode
(msg=None, factor=None, precision=None, abv=None, endmsg='{time}n', enableMsg=True, printfunc=None, profiler=None, profile_point=None)[source]¶ Bases:
future.types.newobject.newobject
Context to profile code by printing a prelude and prologue with time.
Parameters: - msg – prelude or description message
- factor – factor supported by FactorConvert class
- precision – number of digits after a float point
- abv – if True prints “s”, if False “seconds” for time
- endmsg – prologue message
- enableMsg – (True) A flag specifying if context should be printed or not.
- printfunc – function to print messages. By default it is sys.stdout.write
-
time
¶
-
time_end
¶
-
exception
RRtoolbox.lib.root.
TimeOutException
[source]¶ Bases:
exceptions.Exception
Raise an exception when a process surpasses the timeout
-
exception
RRtoolbox.lib.root.
TransferExeption
[source]¶ Bases:
exceptions.Exception
Raise an exception when transfered data is corrupt
-
exception
RRtoolbox.lib.root.
VariableNotAvailable
[source]¶ Bases:
exceptions.Exception
Exception for variable that is not available
-
exception
RRtoolbox.lib.root.
VariableNotDeletable
[source]¶ Bases:
exceptions.Exception
Exception for property not deletable
-
exception
RRtoolbox.lib.root.
VariableNotGettable
[source]¶ Bases:
exceptions.Exception
Exception for property not gettable
-
exception
RRtoolbox.lib.root.
VariableNotSettable
[source]¶ Bases:
exceptions.Exception
Exception for property not settable
-
RRtoolbox.lib.root.
addto
(instance, funcname=None)[source]¶ Decorator: Add function as method to instance.
Parameters: - instance – class instance.
- funcname – name to register in instance.
Returns:
-
RRtoolbox.lib.root.
decorateInstanceMethods
(self, decorator, excludeMth='__init__', includeMth=None)[source]¶ Decorate methods in an instance. It should be used in the __init__ method of a class.
Parameters: - self – class instance.
- decorator – decorator function to apply to self.
- excludeMth – list of methods to exclude.
- includeMth – list of methods to include if not in exclude. if excludeMth is None then decorateInstanceMethods checks for includeMth list. if includeMth and excludeMth is None then all methods of self are decorated.
Returns: self
Note
It must be used at instance initialization (i.e. inside __init__ method)
-
RRtoolbox.lib.root.
formatConsume
(format_string, kwargs, formatter=None, handle=None)[source]¶ Format with dictionary and consume keys.
Parameters: - format_string – string to format
- kwargs – dictionary containing the keys and values to format string. The keys must be supported by the string formatter
- formatter – (None) formatter function to format string
Returns: formatted string
-
RRtoolbox.lib.root.
formatOnly
(format_string, **kwargs)[source]¶ Format string only with provided keys
Parameters: - format_string – string to format
- kwargs – format keys
Returns: formatted string
-
RRtoolbox.lib.root.
glob
(path, contents='*', check=<function isfile>)[source]¶ Return a list of paths matching a pathname pattern with valid files.
Parameters: - path – path to process ing glob filter
- contents – If path is a folder then looks for contents using
- check – function to filter contents. it must receive the path and return True to let it pass and False to suppress it.
Returns: return list of files
-
class
RRtoolbox.lib.root.
globFilter
(include=None, exclude=None, case=False)[source]¶ Bases:
future.types.newobject.newobject
glob filter for patterns
-
RRtoolbox.lib.root.
lookinglob
(pattern, path=None, ext=None, forward=None, filelist=None, aslist=False, raiseErr=False)[source]¶ Look for patterns in Path. It looks as {if path}{if pattern}{if forward}{if ext}.
Parameters: - pattern – string to look for pattern.
- path – (None) path to look for pattern
- ext – (None) extension of pattern in path
- forward – (None) look changes after pattern and before ext parameter.
- filelist – (None) simulates the files in path and look patterns in this list.
- aslist – (False) if False it returns the first match case string else the list of matching cases.
- raiseErr – If true raises Exception if patter is not found in path or there are more than one match
Returns: matched case if returnAll is False else the list of matched cases or if no match is found None
RRtoolbox.lib.serverServices module¶
-
class
RRtoolbox.lib.serverServices.
Conection
(conn)[source]¶ Bases:
future.types.newobject.newobject
represent a connection to interchange objects between servers and clients.
-
RRtoolbox.lib.serverServices.
generateServer
(host='localhost', to=63342)[source]¶ generates a simple Server in available address.
Parameters: to – until port. Returns: socket, address
-
RRtoolbox.lib.serverServices.
initClient
(addr, timeout=None)[source]¶ Inits a simple client from address. :param addr: (host, port) :return: socket
-
RRtoolbox.lib.serverServices.
initServer
(addr)[source]¶ Inits a simple server from address.
Parameters: addr – (host, port) Returns: socket
-
RRtoolbox.lib.serverServices.
parseString
(string, timeout=3)[source]¶ Parameters: - string –
- timeout –
Returns:
-
RRtoolbox.lib.serverServices.
ping
(host, port)[source]¶ Ping to.
Parameters: - host – IP address
- port – port address
Returns:
-
RRtoolbox.lib.serverServices.
rcvPickle
(addr=('localhost', 50007), timeout=None)[source]¶ Receive potentially any data using sockets.
Parameters: - addr – socket or address.
- timeout – NotImplemented
Returns: data, else throws error.
-
RRtoolbox.lib.serverServices.
recv_into
(viewable, socket)[source]¶ Receive from socket into viewable object.
Parameters: - viewable – viewable object
- socket – source socket
Returns: None
-
RRtoolbox.lib.serverServices.
scan_ports
(host)[source]¶ Scan opened ports in address.
Parameters: host – host IP to filter opened ports. Returns: generator
-
RRtoolbox.lib.serverServices.
sendPickle
(obj, addr=('localhost', 50007), timeout=None, threaded=False)[source]¶ Send potentially any data using sockets.
Parameters: - obj – packable object.
- addr – socket or address.
- timeout – NotImplemented
Returns: True if sent successfully, else Throw error.
RRtoolbox.lib.session module¶
This module have serializing methods for data persistence so to let the package “save” custom objects
session module made by Davtoh and powered by dill Dependency project: https://github.com/uqfoundation/dill
-
RRtoolbox.lib.session.
checkFromSession
(filepath, varlist)[source]¶ Check that variables exits in session file.
Parameters: - filepath – path to session file.
- varlist – list of variables to checkLoaded.
Returns: list checkLoaded results
-
RRtoolbox.lib.session.
deleteFromSession
(filepath, varlist)[source]¶ Delete variables from session file.
Parameters: - filepath – path to session file.
- varlist – list of variables to delete.
Returns: None
-
RRtoolbox.lib.session.
flushSession
(filepath)[source]¶ Empty session in file.
Parameters: filepath – path to session file. Returns:
-
RRtoolbox.lib.session.
getEnviromentSession
(enviroment=None)[source]¶ Gets the filtered session from the global variables.
Returns: dictionary containing filtered session.
-
RRtoolbox.lib.session.
readSession
(filepath, helper=None)[source]¶ Loads a dictionary session from file.
Parameters: - filepath – path to load session file.
- helper – function to pos-process session file
Returns: session
-
RRtoolbox.lib.session.
saveSession
(filepath, session, helper=None)[source]¶ Saves dictionary session to file.
Parameters: - filepath – path to save session file.
- session – dictionary
- helper – function to pre-process session
Returns: filename of saved session
-
RRtoolbox.lib.session.
updateSession
(filepath, session, replace=True, rdhelper=None, svhelper=None)[source]¶ Updates a dictionary session in file.
Parameters: - filepath – path to session file.
- session – dictionary.
- replace – if True key values are replaced else old key values ar kept.
- rdhelper – read helper.
- svhelper – save helper.
Returns: None
Module contents¶
This module contains core-like, too-much-used and too-much-referenced modules