RRtoolbox.lib.arrayops package

Submodules

RRtoolbox.lib.arrayops.basic module

This module contains simple array operation methods

RRtoolbox.lib.arrayops.basic.angle(v1, v2, deg=False)[source]

Angle between two N dimmensional vectors.

Parameters:
  • v1 – vector 1.
  • v2 – vector 2.
  • deg – if True angle is in Degrees, else radians.
Returns:

angle in radians.

Example:

>>> angle_between((1, 0, 0), (0, 1, 0))
1.5707963267948966
>>> angle_between((1, 0, 0), (1, 0, 0))
0.0
>>> angle_between((1, 0, 0), (-1, 0, 0))
3.141592653589793
RRtoolbox.lib.arrayops.basic.angle2D(v1, v2, deg=False, absolute=None)[source]

Angle between two 2 dimensional vectors.

Parameters:
  • v1 – vector 1.
  • v2 – vector 2.
  • deg – if True angle is in Degrees, else radians.
  • absolute – if None returns the angle (0 yo 180(pi)) between v1 and v2. if True returns the absolute angle (0 to 360(2pi)) from v1 as axis to v2. if False returns the angle (0 to 180 or 0 to -180) from v1 as axis to v2, where v2 angle relative to v1 is positive or negative if counter-clock or clock wise.
Returns:

angle in radians.

RRtoolbox.lib.arrayops.basic.angleXY(coorX, coorY, angle)[source]

Rotate coordinate.

Parameters:
  • coorX – x coordinate.
  • coorY – y coordinate.
  • angle – radian angle.
Returns:

rotated x,y

RRtoolbox.lib.arrayops.basic.anorm(a)[source]

norm in array.

Parameters:a
Returns:
RRtoolbox.lib.arrayops.basic.anorm2(a)[source]

Summation of squares (helper function for anorm())

Parameters:a
Returns:
RRtoolbox.lib.arrayops.basic.axesIntercept(coorSM, maxS, maxM)[source]

Intercept static axis (S) and mobile axis (M) with a coordinate connecting both axes from minS to minM.

S1 S2

S0 |<---------------------|———–> maxS

coorSM <———| |
M1 M2

M0 <———|--------------------->| maxM

Parameters:
  • coorSM – coordinate of vector from S=0 to M=0.
  • maxS – value representing end of estatic axis.
  • maxM – value representing end of mobile axis.
Returns:

S1,S2,M1,M2.

RRtoolbox.lib.arrayops.basic.boxPads(bx, points)[source]

Get box pads to fit all.

Parameters:
  • bx – box coordinates or previous boxPads [left_top, right_bottom]
  • points – array of points
Returns:

[(left,top),(right,bottom)] where bx and points fit.

RRtoolbox.lib.arrayops.basic.centerM(coor, maxM)[source]

Center vector coor in M axis.

Parameters:
  • coor – coordinate of vector from S=0 to M center
  • maxM – value representing end of mobile axis
Returns:

M centered coordinate

RRtoolbox.lib.arrayops.basic.centerS(coor, maxS)[source]

Center vector coor in S axis.

Parameters:
  • coor – coordinate of vector from S center to M=0
  • maxS – value representing end of estatic axis
Returns:

S centered coordinate

RRtoolbox.lib.arrayops.basic.centerSM(coorSM, maxS, maxM)[source]

Center vector coorSM in both S and M axes.

Parameters:
  • coorSM – coordinate of vector from S to M centers.
  • maxS – value representing end of estatic axis.
  • maxM – value representing end of mobile axis.
Returns:

SM centered coordinate.

RRtoolbox.lib.arrayops.basic.contours2mask(contours, shape=None, astype=<type 'bool'>)[source]

Creates an array with filled polygons formed by contours.

Parameters:
  • contours – list of contour or points forming objects
  • shape – (None) shape of array. If None it creates an array fitted to contours.
  • astype – (“bool”) numpy type
Returns:

RRtoolbox.lib.arrayops.basic.contoursArea(contours)[source]

Accumulates areas from list of contours.

Parameters:contours – list of contours or binary array.
Returns:area.
RRtoolbox.lib.arrayops.basic.convertXY(x, y, backshape, foreshape, flag=0, quartile=0, angle=None)[source]

Convert absolute XY 0,0 coordinates to new system WZ.

Parameters:
  • x – x coordinate.
  • y – y coordinate.
  • backshape – shape of background image.

:param foreshape:shape of foreground image. :param 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.
Parameters:
  • quartile – place Mobile image at quartile 1,2,3,4. if left quartile=0 image won’t be moved.
  • angle – angle in radians (defalut=None). if None it does not apply.
Returns:

W,Z

RRtoolbox.lib.arrayops.basic.convexityRatio(cnt, hull=None)[source]

Ratio to test if contours are irregular

Parameters:cnt – contour

:param hull:(None) convex hull :return: ratio

RRtoolbox.lib.arrayops.basic.entroyTest(arr)[source]

Entropy test of intensity arrays. (Helper function for entropy())

Parameters:arr – array MxN of dim 2.
Returns:entropy.
RRtoolbox.lib.arrayops.basic.findContours(*args, **kwargs)[source]

Compatibility wrapper around cv2.findContour to support both openCV 2 and openCV 3.

findContours(image, mode, method[, contours[, hierarchy[, offset]]]) -> image, contours, hierarchy

RRtoolbox.lib.arrayops.basic.find_near(m, thresh=None, side=None)[source]

helper function for findminima and findmaxima :param m: minima or maxima points :param thresh: guess or seed point :param side: left or right :return: value

RRtoolbox.lib.arrayops.basic.findmaxima(hist, thresh=None, side=None)[source]

Get nearest peak value to a thresh point from a histogram.

Parameters:
  • hist – histogram
  • thresh – initial seed
  • side – find valley from left or right of thresh
Returns:

RRtoolbox.lib.arrayops.basic.findminima(hist, thresh=None, side=None)[source]

Get nearest valley value to a thresh point from a histogram.

Parameters:
  • hist – histogram
  • thresh – initial seed
  • side – find valley from left or right of thresh
Returns:

RRtoolbox.lib.arrayops.basic.getOtsuThresh(hist)[source]

From histogram calculate Otsu threshold value.

Parameters:hist – histogram
Returns:otsu threshold value
RRtoolbox.lib.arrayops.basic.getTransformedCorners(shape, H)[source]

from shape gets transformed corners of array.

Parameters:
  • shape – H,W array shape
  • H – transformation matrix
Returns:

upper_left, upper_right, lower_right, lower_lef transformed corners.

RRtoolbox.lib.arrayops.basic.getTransparency(array)[source]

Convert foreground to background.

Parameters:array – image array.
Returns:alfa (int or array)
RRtoolbox.lib.arrayops.basic.get_x_space(funcs, step=10, xleft=-300, xright=300)[source]

get X axis space by brute force. This can be used to find the x points where the points in the y axis of any number of functions become stable.

Parameters:
  • funcs – list of functions
  • step
    1. step to close guess to maximum
  • xleft – maximum left limit
  • xright – maximum right limit
Returns:

linspace

RRtoolbox.lib.arrayops.basic.getdataVH(array, ypad=0, xpad=0, bgrcolor=None, alfa=None)[source]

Get data from array according to padding (Helper function for padVH()).

Parameters:
  • array – list of arrays to get data
  • ypad – how much to pad in y axis
  • xpad – how much to pad in x axis
Returns:

matrix_shapes, grid_div, row_grid, row_gridpad, globalgrid

RRtoolbox.lib.arrayops.basic.histogram(img)[source]

Get image histogram.

Parameters:img – gray or image with any bands
Returns:histogram of every band
RRtoolbox.lib.arrayops.basic.im2imFormat(src, dst)[source]

Tries to convert source image to destine image format.

Parameters:
  • src – source image.
  • dst – destine image.
Returns:

reshaped source image.

RRtoolbox.lib.arrayops.basic.im2shapeFormat(im, shape)[source]

Tries to convert image to intuited format from shape.

Parameters:
  • im – image.
  • shape

    shape to get format.

    shapes: * (None, None): converts to gray * (None, None, 2): converts to GR555 * (None, None, 3): converts to BGR * (None, None, 4): converts to BGRA

Returns:

reshaped image.

RRtoolbox.lib.arrayops.basic.instability_bf(funcs, step=10, maximum=300, guess=0, tolerance=0.01)[source]

Find the instability of function approaching value by brute force,

Parameters:
  • funcs – list of functions
  • step
    1. step to close guess to maximum
  • maximum
    1. maximum value, if guess surpass this value then calculations are stopped.
  • guess
    1. initial guess
  • tolerance – (0.01) tolerance with last step to check instability.
Returns:

(state, updated guess). state is True if successful, else False.

RRtoolbox.lib.arrayops.basic.invertM(coorSM, maxM)[source]

Invert M axis.

Parameters:
  • coorSM – coordinate of vector for M inverted axes.
  • maxS – value representing end of estatic axis.
  • maxM – value representing end of mobile axis.
Returns:

SM coordinate on S axis and inverted M axis.

RRtoolbox.lib.arrayops.basic.invertSM(coorSM, maxS, maxM)[source]

Invert S and M axes.

Parameters:
  • coorSM – coordinate of vector for SM inverted axes.
  • maxS – value representing end of estatic axis.
  • maxM – value representing end of mobile axis.
Returns:

SM coordinate on inverted SM axes.

RRtoolbox.lib.arrayops.basic.isnumpy(arr)[source]

Test whether an object is a numpy array.

Parameters:arr
Returns:True if numpy array, else false.
RRtoolbox.lib.arrayops.basic.makeVis(globalgrid, bgrcolor=None)[source]

Make visualization (Helper function for padVH())

Parameters:
  • globalgrid – shape
  • bgrcolor – color of visualization
Returns:

array of shape globalgrid

RRtoolbox.lib.arrayops.basic.matrixIntercept(x, y, staticm, *mobilem)[source]

Intercepts planes x and y of a static matrix (staticm) with N mobile matrices (mobilem) translated from the origin to x,y coordinates.

Parameters:
  • x – x coordinate.
  • y – y coordinate.
  • staticm – static matrix.
  • mobilem – mobile matrices.
Returns:

ROI of intercepted matrices [staticm,*mobilem].

RRtoolbox.lib.arrayops.basic.multiple_superpose(base, fore, H, foremask=None)[source]

Superpose multiple foreground images to a single base image.

Parameters:
  • base – backgraound, base or dipest level image (level -1)
  • fore – foreground image list (in order of level i = 0, … , N)
  • H – transformation matrix of fore in level i to overlay in base
  • foremask – foreground alfa mask in level i
Returns:

generator of each overlay

RRtoolbox.lib.arrayops.basic.noisy(arr, mode)[source]

Add noise to arrays

Parameters:
  • arr – Input ndarray data (it will be converted to float).
  • mode

    noise method:

    • ’gauss’ - Gaussian-distributed additive noise.
    • ’poisson’ - Poisson-distributed noise generated from the data.
    • ’s&p’ - Replaces random pixels with 0 or 1.
    • ’speckle’ - Multiplicative noise using out = arr + n*arr,where
      n is uniform noise with specified mean & variance.

:return noisy arr

RRtoolbox.lib.arrayops.basic.normalize(arr)[source]

Normalize array to ensure range [0,1]

RRtoolbox.lib.arrayops.basic.normalize2(arr)[source]

Normalize with factor of absolute maximum value.

RRtoolbox.lib.arrayops.basic.normalizeCustom(arr, by=<function amax>, axis=None)[source]

Normalize array with custom operations.

Parameters:
  • arr – array (it does not correct negative values, use preferable NxM).
  • by – np,max, np.sum or any function that gets an array to obtain factor.
  • axis – if None it normalizes in all axes else in the selected axis.
Returns:

normalized to with factor.

RRtoolbox.lib.arrayops.basic.overlay(back, fore, alpha=None, alfainverted=False, under=False, flag=0)[source]

Try to Overlay any dimension array.

Parameters:
  • back – BGRA background image.
  • fore – BGRA foreground image.
  • alpha – transparency channel.
  • alfainverted – if True inverts alpha transparency.
  • under – if True, place back as fore and fore as back.
  • flag

    (experimental)

    1. Normally replace inverted transparency of alpha in back (N);
      superpose alpha in back (V).
    2. Bloat and replace inverted transparency of alpha in back;
      superpose bgr in back (V).
    3. Superpose inverted transparent COLOR of alpha in back.
    4. Superpose inverted transparent COLOR of alpha in back.
    5. Superpose transparent of alpha in back;
      superpose transparent COLOR of alpha in back.
    6. Superpose transparent of alpha in back;
      superpose transparent COLOR of alpha in back.
Returns:

overlayed array

See also

overlay2()

RRtoolbox.lib.arrayops.basic.overlay2(back, fore)[source]

Overlay foreground to x,y coordinates in background image.

Parameters:
  • back – background image (numpy array dim 3).
  • fore – foreground image (numpy array dim 4). the fourth dimension is used for transparency.
Returns:

back (with overlay).

#Example:

import cv2
import numpy as np
import time
a= time.time()
back = cv2.imread("t1.jpg")
temp = back.shape
bgr = np.zeros((temp[0],temp[1],4), np.uint8)
points = [(86, 162), (1219, 1112), (2219, 2112), (1277,3000),(86, 162)]
col_in = (0, 0, 0,255)
thickness = 10
for i in range(len(points)-1):
    pt1 = (points[i][0], points[i][1])
    pt2 = (points[i+1][0], points[i+1][1])
    cv2.line(bgr, pt1, pt2, col_in, thickness)

overlay(back,bgr)

win = "overlay"
cv2.namedWindow(win,cv2.WINDOW_NORMAL)
cv2.imshow(win, back)
print time.time()-a
cv2.waitKey()
cv2.destroyAllWindows()

See also

overlay()

RRtoolbox.lib.arrayops.basic.overlayXY(x, y, back, fore, alfa=None, alfainverted=False, under=False, flag=0)[source]

Overlay foreground image to x,y coordinates in background image. This function support images of different sizes with formats: BGR background and BGRA foreground of Opencv or numpy images.

Parameters:
  • x – x position in background.
  • y – y position in background.
  • back – background image (numpy array dim 3).
  • fore – foreground image (numpy array dim 4). the fourth dimension is used for transparency.
Returns:

back (with overlay)

Example:

import cv2
back = cv2.imread("t1.jpg")
bgr = cv2.imread("mustache.png",-1)
x,y=convertXY(0,0,back.shape,bgr.shape,flag=1)
overlayXY(x,y,back,bgr)
win = "overlay"
cv2.namedWindow(win,cv2.WINDOW_NORMAL)
cv2.imshow(win, back)
cv2.waitKey()
cv2.destroyAllWindows()
RRtoolbox.lib.arrayops.basic.overlaypng(back, fore, alpha=None, alfainverted=False, under=False, flag=0)[source]

Overlay only BGRA.

Parameters:
  • back – BGRA background image.
  • fore – BGRA foreground image.
  • alpha – transparency channel.
  • alfainverted – if True inverts alpha transparency.
  • under – if True, place back as fore and fore as back.
  • flag

    (experimental)

    1. Normally replace inverted transparency of alpha in back (N);
      superpose alpha in back (V).
    2. Bloat and replace inverted transparency of alpha in back;
      superpose bgr in back (V).
    3. Superpose inverted transparent COLOR of alpha in back.
    4. Superpose inverted transparent COLOR of alpha in back.
    5. Superpose transparent of alpha in back;
      superpose transparent COLOR of alpha in back.
    6. Superpose transparent of alpha in back;
      superpose transparent COLOR of alpha in back.
Returns:

overlayed array

See also

overlay(), overlay2()

RRtoolbox.lib.arrayops.basic.padVH(imgs, ypad=0, xpad=0, bgrcolor=None, alfa=None)[source]

Pad Vertically and Horizontally image or group of images into an array.

Parameters:
  • imgs – image to pad or list of horizontal images (i.e. piled up horizontally as [V1,..,VN] where each can be a list of vertical piling VN = [H1,..,HM]. It can be successive like horizontals, verticals, horizontals, etc.
  • ypad – padding in axis y
  • xpad – padding in axis x
  • bgrcolor – color of spaces
  • alfa – transparency of imgs over background of bgrcolor color.
Returns:

visualization of paded and piled images in imgs.

RRtoolbox.lib.arrayops.basic.pad_to_fit_H(shape1, shape2, H)[source]

get boxPads to fit transformed shape1 in shape2.

Parameters:
  • shape1 – shape of array 1
  • shape2 – shape of array 2
  • H – transformation matrix to use in shape1
Returns:

[(left,top),(right,bottom)]

RRtoolbox.lib.arrayops.basic.points2mask(pts, shape=None, astype=<type 'bool'>)[source]

Creates an array with the filled polygon formed by points.

Parameters:
  • pts – points.
  • shape – (None) shape of array. If None it creates an array fitted to points.
  • astype – (“bool”) numpy type
Returns:

array.

Example:

pts = random_points([(-100, 100), (-100, 100)])
img = points2mask(pts)
Plotim("filled",img).show()
RRtoolbox.lib.arrayops.basic.points_generator(shape=(10, 10), nopoints=None, convex=False, erratic=False, complete=False)[source]

generate points.

Parameters:
  • shape – enclosed frame (width, height)
  • nopoints – number of points
  • convex – if True make points convex, else points follow a circular pattern.
Returns:

RRtoolbox.lib.arrayops.basic.polygonArea(pts)

Area of points calculating polygon Area.

Parameters:pts – points.
Returns:area value.
..note::
RRtoolbox.lib.arrayops.basic.polygonArea_calcule(pts)[source]

Area of points calculating polygon Area.

Parameters:pts – points.
Returns:area value.
..note::
RRtoolbox.lib.arrayops.basic.polygonArea_contour(pts)[source]

Area of points using contours.

Parameters:pts – points.
Returns:area value.

..note:: if polygon is incomplete (last is not first point) it completes the array.

RRtoolbox.lib.arrayops.basic.polygonArea_fill(pts)[source]

Area of points using filled polygon and pixel count.

Parameters:pts – points.
Returns:area value.

..note:: if polygon is incomplete (last is not first point) it completes the array.

RRtoolbox.lib.arrayops.basic.process_as_blocks(arr, func, block_shape=(3, 3), mask=None, asWindows=False)[source]

process with function over an array using blocks (using re-striding).

Parameters:
  • arr – array to process
  • func – function to feed blocks
  • block_shape – (3,3) shape of blocks
  • mask – (None) mask to process arr
  • asWindows – (False) if True all blocks overlap each other to give a result for each position of arr, if False the results are given in blocks equivalent for each processed blocks of arr (faster).
Returns:

processed array.

RRtoolbox.lib.arrayops.basic.quadrant(coorX, coorY, maxX, maxY, quadrant=0)[source]

Moves a point to a quadrant

Parameters:
  • coorX – point in x coordinate
  • coorY – point in y coordinate
  • maxX – max value in x axis
  • maxY – max value in y axis
  • quadrant – Cartesian quadrant, if 0 or False it leaves coorX and coorY unprocessed.
Returns:

RRtoolbox.lib.arrayops.basic.random_points(axes_range=((-50, 50), ), nopoints=4, complete=False)[source]

Get random points.

Parameters:
  • axes_range – [x_points_range, y_points_range] where points_range is (min,max) range in axis.
  • nopoints – number of points.
  • complete – last point is the first point (adds an additional point i.e. nopoints+1).
Returns:

numpy array.

RRtoolbox.lib.arrayops.basic.recursiveMap(function, sequence)[source]

Iterate recursively over a structure using a function.

Parameters:
  • function – function to apply
  • sequence – iterator
Returns:

RRtoolbox.lib.arrayops.basic.relativeQuadrants(points)[source]

Get quadrants of relative vectors obtained from points.

Parameters:points – array of points.
Returns:quadrants.
RRtoolbox.lib.arrayops.basic.relativeVectors(pts, all=True)[source]

Form vectors from points.

Parameters:
  • pts – array of points [p0, … ,(x,y)].
  • all – (True) if True adds last vector from last and first point.
Returns:

array of vectors [V0, … , (V[n] = x[n+1]-x[n],y[n+1]-y[n])].

RRtoolbox.lib.arrayops.basic.rescale(arr, max=1, min=0)[source]

Rescales array values to range [min,max].

Parameters:
  • arr – array.
  • max – maximum value in range.
  • min – minimum value in range.
Returns:

rescaled array.

RRtoolbox.lib.arrayops.basic.separePointsByAxis(pts, ptaxis=(1, 0), origin=(0, 0))[source]

Separate scattered points with respect to axis (splitting line).

Parameters:
  • pts – points to separate.
  • ptaxis – point to form axis from origin
  • origin – origin
Returns:

left, right points from axis.

RRtoolbox.lib.arrayops.basic.splitPoints(pts, aslist=None)[source]

from points get x,y columns

Parameters:
  • pts – array of points
  • aslist – True to return lists instead of arrays
Returns:

x, y columns

example:

splitPoints((1,2))
>>> ([1], [2])
splitPoints([[[[(1,2),(1,2),(2,3)]]]])
>>> ([1, 1, 2], [2, 2, 3])
splitPoints(np.array([[[[(1,2),(1,2),(2,3)]]]]))
>>> (array([1, 1, 2]), array([2, 2, 3]))
splitPoints(np.array([[[[(1,2),(1,2),(2,3)]]]]), True)
>>> ([1, 1, 2], [2, 2, 3])
splitPoints([(1,2,3,4,5),(1,2,3,4,5)]) # it is processed anyways
>>> ([1, 2, 3, 4, 5], [1, 2, 3, 4, 5])
RRtoolbox.lib.arrayops.basic.standarizePoints(pts, aslist=False)[source]

converts points to a standard form :param pts: list or array of points :param aslist: True to return list instead of array :return: standard points

example:

standarizePoints((1,2))
>>> array([[1, 2]])
standarizePoints([[[[(1,2)]]]])
>>> array([[1, 2]])
standarizePoints([[[[(1,2),(1,2),(2,3)]]]],True)
>>> [(1, 2), (1, 2), (2, 3)]
standarizePoints([[[[(1,2,3),(1,2,3)]]]],True)
>>> [(1, 2), (1, 2), (2, 3)]
standarizePoints([(1,2,3,4,5),(1,2,3,4,5)],True)
>>> [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]
RRtoolbox.lib.arrayops.basic.superpose(back, fore, H, foreMask=None, grow=True)[source]

Superpose foreground image to background image.

Parameters:
  • back – background image
  • fore – foreground image
  • H – transformation matrix of fore to overlay in back
  • foreMask – (None) foreground alpha mask, None or function. foreMask values are from 1 for solid to 0 for transparency. If a function is provided the new back,fore parameters are provided to produce the foreMask. If None is provided as foreMask then it is equivalent to a foreMask with all values to 1 where fore is True.
  • grow – If True, im can be bigger than back and is calculated according to how fore is superposed in back; if False im is of the same shape as back.
Returns:

im, H_back, H_fore

RRtoolbox.lib.arrayops.basic.transformPoint(p, H)[source]

Transform individual x,y point with Transformation Matrix.

Parameters:
  • p – x,y point
  • H – transformation matrix
Returns:

transformed x,y point

RRtoolbox.lib.arrayops.basic.transformPoints(p, H)[source]

Transform x,y points in array with Transformation Matrix.

Parameters:
  • p – array of points
  • H – transformation matrix
Returns:

transformed array of x,y point

RRtoolbox.lib.arrayops.basic.unit_vector(vector)[source]

Returns the unit vector of the vector.

RRtoolbox.lib.arrayops.basic.vectorsAngles(pts, ptaxis=(1, 0), origin=(0, 0), dtype=None, deg=False, absolute=None)[source]

Angle of formed vectors in Cartesian plane with respect to formed axis vector.

i.e. angle between vector “Vn” (formed by point “Pn” and the “origin”)
and vector “Vaxis” formed by “ptaxis” and the “origin”.

where pts-origin = (P0-origin … Pn-origin) = V0 … Vn

Parameters:
  • pts – points to form vectors from origin
  • ptaxis – point to form axis from origin
  • origin – origin
  • dtype – return array of type supported by numpy.
  • deg – if True angle is in Degrees, else radians.
  • absolute – if None returns angles (0 yo 180(pi)) between pts-origin (V0 .. Vn) and Vaxis. if True returns any Vn absolute angle (0 to 360(2pi)) from Vaxis as axis to Vn. if False returns any Vn angle (0 to 180 or 0 to -180) from Vaxis as axis to Vn, where any Vn angle is positive or negative if counter-clock or clock wise from Vaxis.
Returns:

RRtoolbox.lib.arrayops.basic.vectorsQuadrants(vecs)[source]

Get quadrants of vectors.

Parameters:vecs – array of vectors.
Returns:quadrants.
RRtoolbox.lib.arrayops.basic.vertexesAngles(pts, dtype=None, deg=False)[source]

Relative angle of vectors formed by vertexes (where vectors cross).

i.e. angle between vectors “v01” formed by points “p0-p1” and “v12”
formed by points “p1-p2” where “p1” is seen as a vertex (where vectors cross).
Parameters:
  • pts – points seen as vertexes (vectors are recreated from point to point).
  • dtype – return array of type supported by numpy.
  • deg – if True angle is in Degrees, else radians.
Returns:

angles.

RRtoolbox.lib.arrayops.basic.view_as_blocks(arr_in, block_shape=(3, 3))[source]

Provide a 2D block_shape view to 2D array. No error checking made. Therefore meaningful (as implemented) only for blocks strictly compatible with the shape of arr_in.

Parameters:
  • arr_in
  • block_shape
Returns:

RRtoolbox.lib.arrayops.basic.view_as_windows(arr_in, window_shape, step=1)[source]

Provide a 2D block_shape rolling view to 2D array. No error checking made. Therefore meaningful (as implemented) only for blocks strictly compatible with the shape of arr_in.

Parameters:
  • arr_in
  • window_shape
  • step
Returns:

RRtoolbox.lib.arrayops.convert module

This module unlike common and basic array operations classifies just the from-to-conversions methods

class RRtoolbox.lib.arrayops.convert.SimKeyPoint(*args)[source]

Bases: future.types.newobject.newobject

Simulates opencv keypoint (it allows manipulation, conversion and serialization of keypoints).

Note

Used for conversions and data persistence.

RRtoolbox.lib.arrayops.convert.apply2kp_pairs(kp_pairs, kp1_rel, kp2_rel, func=None)[source]

Apply to kp_pairs.

Parameters:
  • kp_pairs – list of (kp1,kp2) pairs
  • kp1_rel – x,y relation or function to apply to kp1
  • kp2_rel – x,y relation or function to apply to kp2
  • func – function to build new copy of keypoint
Returns:

transformed kp_pairs

RRtoolbox.lib.arrayops.convert.cnt2pts(contours)

Convert contours to points. (cnt2pts)

Parameters:contours – array of contours (cnt) ([[x,y]] only for openCV)
Returns:

Example:

contours = np.array([[[0, 0]], [[1, 0]]]) # contours
points = contour2points(contours)
print points # np.array([[0, 0], [1, 0]])
RRtoolbox.lib.arrayops.convert.contour2points(contours)[source]

Convert contours to points. (cnt2pts)

Parameters:contours – array of contours (cnt) ([[x,y]] only for openCV)
Returns:

Example:

contours = np.array([[[0, 0]], [[1, 0]]]) # contours
points = contour2points(contours)
print points # np.array([[0, 0], [1, 0]])
RRtoolbox.lib.arrayops.convert.conv3H4H(M)[source]

Convert a 3D transformation matrix (TM) to 4D TM.

Parameters:M – Matrix
Returns:4D Matrix
RRtoolbox.lib.arrayops.convert.dict2keyPoint(d, func=<type 'cv2.KeyPoint'>)[source]

KeyPoint([x, y, _size[, _angle[, _response[, _octave[, _class_id]]]]]) -> <KeyPoint object>

RRtoolbox.lib.arrayops.convert.getSOpointRelation(source_shape, destine_shape, asMatrix=False)[source]

Return parameters to change scaled point to original point.

# destine_domain = relation*source_domain
Parameters:
  • source_shape – image shape for source domain
  • destine_shape – image shape for destine domain
  • asMatrix – if true returns a Transformation Matrix H
Returns:

x, y coordinate relations or H if asMatrix is True

Note

Used to get relations to convert scaled points to original points of an Image.

RRtoolbox.lib.arrayops.convert.invertH(H)[source]

Invert Transformation Matrix.

Parameters:H
Returns:
RRtoolbox.lib.arrayops.convert.keyPoint2tuple(keypoint)[source]

obj.angle, obj.class_id, obj.octave, obj.pt, obj.response, obj.size

RRtoolbox.lib.arrayops.convert.points2contour(points)[source]

Convert points to contours. (pts2cnt)

Parameters:points – array of points ([x,y] for openCV, [y,x] for numpy)
Returns:

Example:

points = np.array([[0, 0], [1, 0]]) # points
contours = points2contour(points)
print contours # np.array([[[0, 0]], [[1, 0]]])
RRtoolbox.lib.arrayops.convert.points2vectos(pts, origin=None)[source]

Convert points to vectors with respect to origin.

Parameters:
  • pts – array of points.
  • origin – point of origin.
Returns:

vectors.

RRtoolbox.lib.arrayops.convert.pts2cnt(points)

Convert points to contours. (pts2cnt)

Parameters:points – array of points ([x,y] for openCV, [y,x] for numpy)
Returns:

Example:

points = np.array([[0, 0], [1, 0]]) # points
contours = points2contour(points)
print contours # np.array([[[0, 0]], [[1, 0]]])
RRtoolbox.lib.arrayops.convert.sh2oh(sH, osrc_sh, sscr_sh, odst_sh, sdst_sh)[source]

Convert scaled transformation matrix (sH) to original (oH).

Parameters:
  • sH – scaled transformation matrix
  • osrc_sh – original source’s shape
  • sscr_sh – scaled source’s shape
  • odst_sh – original destine’s shape
  • sdst_sh – scaled destine’s shape
Returns:

RRtoolbox.lib.arrayops.convert.spairs2opairs(kp_pairs, osrc_sh, sscr_sh, odst_sh, sdst_sh, func=None)[source]

Convert scaled kp_pairs to original kp_pairs.

Parameters:
  • kp_pairs – list of kp_pairs
  • osrc_sh – original source’s shape
  • sscr_sh – scaled source’s shape
  • odst_sh – original destine’s shape
  • sdst_sh – scaled destine’s shape
  • func – function to build new copy of keypoint
Returns:

RRtoolbox.lib.arrayops.convert.spoint2opointfunc(source_shape, destine_shape)[source]

Return function with parameters to change scaled point to original point.

Parameters:
  • source_shape
  • destine_shape – shape of
Returns:

Example:

forefunc = scaled2realfunc(imgf.shape,bgr.shape)
backfunc = scaled2realfunc(imgb.shape,back.shape)
p1fore = np.array([forefunc(i) for i in p1])
p2back = np.array([backfunc(i) for i in p2])
RRtoolbox.lib.arrayops.convert.toTupple(obj)[source]

Converts recursively to tuple

Parameters:obj – numpy array, list structure, iterators, etc.
Returns:tuple representation obj.
RRtoolbox.lib.arrayops.convert.translateQuadrants(quadrants, quadrantmap={(-1, -1): 'left-down', (-1, 0): 'left', (-1, 1): 'left-up', (0, -1): 'down', (0, 0): 'origin', (0, 1): 'up', (1, -1): 'right-down', (1, 0): 'right', (1, 1): 'right-up'})[source]

Convert quadrants into human readable data.

Parameters:
  • quadrants – array of quadrants.
  • quadrantmap

    dictionary map to translate quadrants. it is of the form:

    {(0,0):"origin",(1,0):"right",(1,1):"top-right",(0,1):"top",(-1,1):"top-left",
    
    (-1,0):”left”,(-1,-1):”bottom-left”,(0,-1):”bottom”,(1,-1):”bottom-right”}
Returns:

list of translated quadrants.

RRtoolbox.lib.arrayops.convert.tuple2keyPoint(points, func=<type 'cv2.KeyPoint'>)[source]

KeyPoint([x, y, _size[, _angle[, _response[, _octave[, _class_id]]]]]) -> <KeyPoint object>

RRtoolbox.lib.arrayops.convert.vectos2points(vecs, origin=None)[source]

Convert points to vectors with respect to origin.

Parameters:
  • vecs – array of vectors.
  • origin – point of origin.
Returns:

points.

RRtoolbox.lib.arrayops.filters module

This module contains custom 1D adn 2D-array filters and pre-processing (as in filtering phase) methods

class RRtoolbox.lib.arrayops.filters.Bandpass(alpha, beta1, beta2)[source]

Bases: RRtoolbox.lib.arrayops.filters.FilterBase

Bandpass filter (recommended to use float types)

class RRtoolbox.lib.arrayops.filters.Bandstop(alpha, beta1, beta2)[source]

Bases: RRtoolbox.lib.arrayops.filters.FilterBase

Bandstop filter (recommended to use float types)

class RRtoolbox.lib.arrayops.filters.BilateraParameter(scale, shift=33, name=None, alpha=100, beta1=-400, beta2=200)[source]

Bases: RRtoolbox.lib.arrayops.filters.Bandstop

bilateral parameter

class RRtoolbox.lib.arrayops.filters.BilateralParameters(d=None, sigmaColor=None, sigmaSpace=None)[source]

Bases: future.types.newobject.newobject

create instance to calculate bilateral parameters from image shape.

d -> inf then:
  • computation is slower
  • filtering is better to eliminate noise
  • images look more cartoon-like
Parameters:
  • d – distance
  • sigmaColor – sigma in color
  • sigmaSpace – sigma in space
d = <RRtoolbox.lib.arrayops.filters.BilateraParameter object>
filters

list of filters

sigmaColor = <RRtoolbox.lib.arrayops.filters.BilateraParameter object>
sigmaSpace = <RRtoolbox.lib.arrayops.filters.BilateraParameter object>
class RRtoolbox.lib.arrayops.filters.FilterBase(alpha=None, beta1=None, beta2=None)[source]

Bases: future.types.newobject.newobject

base filter to create custom filters

alpha
beta1
beta2
class RRtoolbox.lib.arrayops.filters.Highpass(alpha, beta1)[source]

Bases: RRtoolbox.lib.arrayops.filters.FilterBase

Highpass filter (recommended to use float types)

class RRtoolbox.lib.arrayops.filters.InvertedBandpass(alpha, beta1, beta2)[source]

Bases: RRtoolbox.lib.arrayops.filters.Bandpass

inverted Bandpass filter (recommended to use float types)

class RRtoolbox.lib.arrayops.filters.InvertedBandstop(alpha, beta1, beta2)[source]

Bases: RRtoolbox.lib.arrayops.filters.Bandstop

inverted Bandstop filter (recommended to use float types)

class RRtoolbox.lib.arrayops.filters.Lowpass(alpha, beta1)[source]

Bases: RRtoolbox.lib.arrayops.filters.FilterBase

Lowpass filter (recommended to use float types)

RRtoolbox.lib.arrayops.filters.bilateralFilter(im, d, sigmaColor, sigmaSpace)[source]

Apply bilateral Filter.

Parameters:
  • im
  • d
  • sigmaColor
  • sigmaSpace
Returns:

filtered image

RRtoolbox.lib.arrayops.filters.filterFactory(alpha, beta1, beta2=None)[source]

Make filter.

Parameters:
  • alpha – steepness of filter
  • beta1 – first shift from origin
  • beta2

    second shift from origin:

    alpha must be != 0 if beta2 = None:

    if alpha > 0: high-pass filter, if alpha < 0: low-pass filter
    else:
    if beta2 > beta1:
    if alpha > 0: band-pass filter, if alpha < 0: band-stop filter
    else:
    if alpha > 0: inverted-band-pass filter, if alpha < 0: inverted-band-stop filter
Returns:

filter funtion with intup levels

Example:

alpha,beta1,beta2 = 10,20,100
myfilter = filter(alpha,beta1,beta2)
print myfilter,type(myfilter)
print myfilter.alpha,myfilter.beta1,myfilter.beta2
RRtoolbox.lib.arrayops.filters.getBilateralParameters(shape=None, mode=None)[source]

Calculate from shape bilateral parameters.

Parameters:
  • shape – image shape. if None it returns the instace to use with shapes.
  • mode – “mild”, “heavy” or “normal” to process noise
Returns:

instance or parameters

RRtoolbox.lib.arrayops.filters.normsigmoid(x, alpha, beta)[source]

Apply normalized sigmoid filter.

Parameters:
  • x – data to apply filter
  • alpha – if alpha > 0: pass high filter, if alpha < 0: pass low filter, alpha must be != 0
  • beta – shift from origin
Returns:

filtered values normalized to range [-1 if x<0, 1 if x>=0]

RRtoolbox.lib.arrayops.filters.sigmoid(x, alpha, beta, max=255, min=0)[source]

Apply sigmoid filter.

Parameters:
  • x – data to apply filter
  • alpha – if alpha > 0: pass high filter, if alpha < 0: pass low filter, alpha must be != 0
  • beta – shift from origin
  • max – maximum output value
  • min – minimum output value
Returns:

filtered values ranging as [min,max]

RRtoolbox.lib.arrayops.filters.smooth(x, window_len=11, window='hanning', correct=False)[source]

Smooth the data using a window with requested size.

This method is based on the convolution of a scaled window with the signal. The signal is prepared by introducing reflected copies of the signal (with the window size) in both ends so that transient parts are minimized in the beginning and end part of the output signal.

input:

x: the input signal window_len: the dimension of the smoothing window; should be an odd integer window: the type of window from ‘flat’, ‘hanning’, ‘hamming’, ‘bartlett’, ‘blackman’

flat window will produce a moving average smoothing.
output:
the smoothed signal

Example:

t=linspace(-2,2,0.1)
x=sin(t)+randn(len(t))*0.1
y=smooth(x)

See also

numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve, scipy.signal.lfilter

Note

length(output) != length(input), to correct this: return y[(window_len/2-1):-(window_len/2)] instead of just y.

RRtoolbox.lib.arrayops.mask module

This module contains all basic masking and pre-processing (as in segmenting phase) methods

RRtoolbox.lib.arrayops.mask.background(gray, mask=None, iterations=3)[source]

get the background mask of a gray image. (this it the inverted of foreground())

Parameters:
  • gray – gray image
  • mask – (None) input mask to process gray
  • iterations – (3) number of iterations to detect background with otsu threshold.
Returns:

output mask

RRtoolbox.lib.arrayops.mask.biggestCnt(contours)[source]

Filters contours to get biggest contour.

Parameters:contours
Returns:cnt
RRtoolbox.lib.arrayops.mask.biggestCntData(contours)[source]

Gets index and area of biggest contour.

Parameters:contours
Returns:index, area
RRtoolbox.lib.arrayops.mask.brightness(img)[source]

get brightness from an image :param img: BGR or gray image :return:

RRtoolbox.lib.arrayops.mask.cnt_hist(gray)[source]

Mask of a ellipse enclosing retina using histogram threshold.

Parameters:
  • gray – gray image
  • invert – invert mask
Returns:

mask

RRtoolbox.lib.arrayops.mask.foreground(gray, mask=None, iterations=3)[source]

get the foreground mask of a gray image. (this it the inverted of background())

Parameters:
  • gray – gray image
  • mask – (None) input mask to process gray
  • iterations – (3) number of iterations to detect foreground with otsu threshold.
Returns:

output mask

RRtoolbox.lib.arrayops.mask.gethull(contours)[source]

Get convex hull.

Parameters:contours – contours or mask array
Returns:cnt
RRtoolbox.lib.arrayops.mask.hist_cdf(img, window_len=0, window='hanning')[source]

Get image histogram and the normalized cumulative distribution function.

Parameters:
  • img – imaeg
  • window_len
  • window
Returns:

histogram (int), normalized cdf (float)

RRtoolbox.lib.arrayops.mask.mask_watershed(BGR, GRAY=None)[source]

Get retinal mask with watershed method.

Parameters:
  • BGR
  • GRAY
Returns:

mask

RRtoolbox.lib.arrayops.mask.multiple_otsu(gray, mask=None, flag=0, iterations=1)[source]

get the mask of a gray image applying Otsu threshold.

Parameters:
  • gray – gray image
  • mask – (None) input mask to process gray
  • iterations
    1. number of iterations to detect Otsu threshold.
Returns:

thresh, mask

RRtoolbox.lib.arrayops.mask.thresh_biggestCnt(thresh)[source]

From threshold obtain biggest contour.

Parameters:thresh – binary image
Returns:cnt
RRtoolbox.lib.arrayops.mask.thresh_hist(gray)[source]

Get best possible thresh to threshold object from the gray image.

Parameters:gray – gray image.
Returns:thresh value.
RRtoolbox.lib.arrayops.mask.threshold_opening(src, thresh, maxval, type)[source]

Eliminate small objects from threshold.

Parameters:
  • src
  • thresh
  • maxval
  • type
Returns:

Module contents