INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Publish code to PyPI or index of choice.
def publish( c, sdist=True, wheel=False, index=None, sign=False, dry_run=False, directory=None, dual_wheels=False, alt_python=None, check_desc=False, ): """ Publish code to PyPI or index of choice. All parameters save ``dry_run`` and ``directory`` honor config settin...
Upload ( potentially also signing ) all artifacts in directory.
def upload(c, directory, index=None, sign=False, dry_run=False): """ Upload (potentially also signing) all artifacts in ``directory``. :param str index: Custom upload index/repository name. By default, uses whatever the invoked ``pip`` is configured to use. Modify your ``pypirc`` f...
Context - manage a temporary directory.
def tmpdir(skip_cleanup=False, explicit=None): """ Context-manage a temporary directory. Can be given ``skip_cleanup`` to skip cleanup, and ``explicit`` to choose a specific location. (If both are given, this is basically not doing anything, but it allows code that normally requires a secure t...
Generate ransom spatial permutations for inference on LISA vectors.
def permute(self, permutations=99, alternative='two.sided'): """ Generate ransom spatial permutations for inference on LISA vectors. Parameters ---------- permutations : int, optional Number of random permutations of observations. alternative : string, option...
Plot the rose diagram.
def plot(self, attribute=None, ax=None, **kwargs): """ Plot the rose diagram. Parameters ---------- attribute : (n,) ndarray, optional Variable to specify colors of the colorbars. ax : Matplotlib Axes instance, optional If given, the figure will b...
Plot vectors of positional transition of LISA values starting from the same origin.
def plot_origin(self): # TODO add attribute option to color vectors """ Plot vectors of positional transition of LISA values starting from the same origin. """ import matplotlib.cm as cm import matplotlib.pyplot as plt ax = plt.subplot(111) xlim = [self._...
Plot vectors of positional transition of LISA values within quadrant in scatterplot in a polar plot.
def plot_vectors(self, arrows=True): """ Plot vectors of positional transition of LISA values within quadrant in scatterplot in a polar plot. Parameters ---------- ax : Matplotlib Axes instance, optional If given, the figure will be created inside this axis. ...
Nuke docs build target directory so next build is clean.
def _clean(c): """ Nuke docs build target directory so next build is clean. """ if isdir(c.sphinx.target): rmtree(c.sphinx.target)
Open build target s index. html in a browser ( using open ).
def _browse(c): """ Open build target's index.html in a browser (using 'open'). """ index = join(c.sphinx.target, c.sphinx.target_file) c.run("open {0}".format(index))
Build the project s Sphinx docs.
def build( c, clean=False, browse=False, nitpick=False, opts=None, source=None, target=None, ): """ Build the project's Sphinx docs. """ if clean: _clean(c) if opts is None: opts = "" if nitpick: opts += " -n -W -T" cmd = "sphinx-build{0} {...
Display documentation contents with the tree program.
def tree(c): """ Display documentation contents with the 'tree' program. """ ignore = ".git|*.pyc|*.swp|dist|*.egg-info|_static|_build|_templates" c.run('tree -Ca -I "{0}" {1}'.format(ignore, c.sphinx.source))
Build both doc sites w/ maxed nitpicking.
def sites(c): """ Build both doc sites w/ maxed nitpicking. """ # TODO: This is super lolzy but we haven't actually tackled nontrivial # in-Python task calling yet, so we do this to get a copy of 'our' context, # which has been updated with the per-collection config data of the # docs/www su...
Watch both doc trees & rebuild them if files change.
def watch_docs(c): """ Watch both doc trees & rebuild them if files change. This includes e.g. rebuilding the API docs if the source code changes; rebuilding the WWW docs if the README changes; etc. Reuses the configuration values ``packaging.package`` or ``tests.package`` (the former winning ...
Random permutation of rows and columns of a matrix
def shuffle_matrix(X, ids): """ Random permutation of rows and columns of a matrix Parameters ---------- X : array (k, k), array to be permutated. ids : array range (k, ). Returns ------- X : array (k, k) with rows and columns randomly shuffled. ...
Flattens the lower part of an n x n matrix into an n * ( n - 1 )/ 2 x 1 vector.
def get_lower(matrix): """ Flattens the lower part of an n x n matrix into an n*(n-1)/2 x 1 vector. Parameters ---------- matrix : array (n, n) numpy array, a distance matrix. Returns ------- lowvec : array numpy array, the lower half of the distance matri...
r Run black on the current source tree ( all. py files ).
def blacken( c, line_length=79, folders=None, check=False, diff=False, find_opts=None ): r""" Run black on the current source tree (all ``.py`` files). .. warning:: ``black`` only runs on Python 3.6 or above. (However, it can be executed against Python 2 compatible code.) :param in...
Normalize the response value into a 3 - tuple ( rv status headers ): type rv: tuple| *: returns: tuple ( rv status headers ): rtype: tuple ( Response|JsonResponse| * int|None dict|None )
def normalize_response_value(rv): """ Normalize the response value into a 3-tuple (rv, status, headers) :type rv: tuple|* :returns: tuple(rv, status, headers) :rtype: tuple(Response|JsonResponse|*, int|None, dict|None) """ status = headers = None if isinstance(rv, tuple): ...
Make JsonResponse: param rv: Response: the object to encode or tuple ( response status headers ): type rv: tuple| *: rtype: JsonResponse
def make_json_response(rv): """ Make JsonResponse :param rv: Response: the object to encode, or tuple (response, status, headers) :type rv: tuple|* :rtype: JsonResponse """ # Tuple of (response, status, headers) rv, status, headers = normalize_response_value(rv) # JsonResponse if is...
Markov - based mobility index.
def markov_mobility(p, measure="P", ini=None): """ Markov-based mobility index. Parameters ---------- p : array (k, k), Markov transition probability matrix. measure : string If measure= "P", :math:`M_{P} = \\frac{m-\sum_{i=1}^m P_{ii}}{m-1}`; ...
chi - squared test of difference between two transition matrices.
def chi2(T1, T2): """ chi-squared test of difference between two transition matrices. Parameters ---------- T1 : array (k, k), matrix of transitions (counts). T2 : array (k, k), matrix of transitions (counts) to use to form the probabilities under the n...
Kullback information based test of Markov Homogeneity.
def kullback(F): """ Kullback information based test of Markov Homogeneity. Parameters ---------- F : array (s, r, r), values are transitions (not probabilities) for s strata, r initial states, r terminal states. Returns ------- Results : dictionary (key -...
Prais conditional mobility measure.
def prais(pmat): """ Prais conditional mobility measure. Parameters ---------- pmat : matrix (k, k), Markov probability transition matrix. Returns ------- pr : matrix (1, k), conditional mobility measures for each of the k classes. Notes ----- Prais...
Test for homogeneity of Markov transition probabilities across regimes.
def homogeneity(transition_matrices, regime_names=[], class_names=[], title="Markov Homogeneity Test"): """ Test for homogeneity of Markov transition probabilities across regimes. Parameters ---------- transition_matrices : list of transition matrices for r...
Calculate sojourn time based on a given transition probability matrix.
def sojourn_time(p): """ Calculate sojourn time based on a given transition probability matrix. Parameters ---------- p : array (k, k), a Markov transition probability matrix. Returns ------- : array (k, ), sojourn times. Each element is th...
Helper to estimate spatial lag conditioned Markov transition probability matrices based on maximum likelihood techniques.
def _calc(self, y, w): '''Helper to estimate spatial lag conditioned Markov transition probability matrices based on maximum likelihood techniques. ''' if self.discrete: self.lclass_ids = weights.lag_categorical(w, self.class_ids, ...
A summary method to call the Markov homogeneity test to test for temporally lagged spatial dependence.
def summary(self, file_name=None): """ A summary method to call the Markov homogeneity test to test for temporally lagged spatial dependence. To learn more about the properties of the tests, refer to :cite:`Rey2016a` and :cite:`Kang2018`. """ class_names = ["C%d...
Helper method for classifying continuous data.
def _maybe_classify(self, y, k, cutoffs): '''Helper method for classifying continuous data. ''' rows, cols = y.shape if cutoffs is None: if self.fixed: mcyb = mc.Quantiles(y.flatten(), k=k) yb = mcyb.yb.reshape(y.shape) cutoff...
Detect spillover locations for diffusion in LISA Markov.
def spillover(self, quadrant=1, neighbors_on=False): """ Detect spillover locations for diffusion in LISA Markov. Parameters ---------- quadrant : int which quadrant in the scatterplot should form the core of a cluster. n...
Get entity property names
def get_entity_propnames(entity): """ Get entity property names :param entity: Entity :type entity: sqlalchemy.ext.declarative.api.DeclarativeMeta :returns: Set of entity property names :rtype: set """ ins = entity if isinstance(entity, InstanceState) else inspect(entity) ...
Get entity property names that are loaded ( e. g. won t produce new queries )
def get_entity_loaded_propnames(entity): """ Get entity property names that are loaded (e.g. won't produce new queries) :param entity: Entity :type entity: sqlalchemy.ext.declarative.api.DeclarativeMeta :returns: Set of entity property names :rtype: set """ ins = inspect(ent...
Return a Version whose minor number is one greater than self s.
def next_minor(self): """ Return a Version whose minor number is one greater than self's. .. note:: The new Version will always have a zeroed-out bugfix/tertiary version number, because the "next minor release" of e.g. 1.2.1 is 1.3.0, not 1.3.1. """ clone = self.clone() ...
Check that encoding is a valid Python encoding: param name: name under which the encoding is known to the user e. g. default encoding: param encoding_to_check: name of the encoding to check e. g. utf - 8: param source: source where the encoding has been set e. g. option name: raise pygount. common. OptionError if encod...
def _check_encoding(name, encoding_to_check, alternative_encoding, source=None): """ Check that ``encoding`` is a valid Python encoding :param name: name under which the encoding is known to the user, e.g. 'default encoding' :param encoding_to_check: name of the encoding to check, e.g. 'utf-8' :para...
Generator function to yield lines ( delimited with \ n ) stored in text. This is useful when a regular expression should only match on a per line basis in a memory efficient way.
def lines(text): """ Generator function to yield lines (delimited with ``'\n'``) stored in ``text``. This is useful when a regular expression should only match on a per line basis in a memory efficient way. """ assert text is not None assert '\r' not in text previous_newline_index = 0 ...
The first line and its number ( starting with 0 ) in the source code that indicated that the source code is generated.: param source_lines: lines of text to scan: param generated_regexes: regular expressions a line must match to indicate the source code is generated.: param max_line_count: maximum number of lines to sc...
def matching_number_line_and_regex(source_lines, generated_regexes, max_line_count=15): """ The first line and its number (starting with 0) in the source code that indicated that the source code is generated. :param source_lines: lines of text to scan :param generated_regexes: regular expressions a ...
Similar to tokens but converts strings after a colon (: ) to comments.
def _pythonized_comments(tokens): """ Similar to tokens but converts strings after a colon (:) to comments. """ is_after_colon = True for token_type, token_text in tokens: if is_after_colon and (token_type in pygments.token.String): token_type = pygments.token.Comment eli...
The encoding used by the text file stored in source_path.
def encoding_for(source_path, encoding='automatic', fallback_encoding=None): """ The encoding used by the text file stored in ``source_path``. The algorithm used is: * If ``encoding`` is ``'automatic``, attempt the following: 1. Check BOM for UTF-8, UTF-16 and UTF-32. 2. Look for XML prolo...
Initial quick check if there is a lexer for source_path. This removes the need for calling: py: func: pygments. lexers. guess_lexer_for_filename () which fully reads the source file.
def has_lexer(source_path): """ Initial quick check if there is a lexer for ``source_path``. This removes the need for calling :py:func:`pygments.lexers.guess_lexer_for_filename()` which fully reads the source file. """ result = bool(pygments.lexers.find_lexer_class_for_filename(source_path)) ...
Analysis for line counts in source code stored in source_path.
def source_analysis( source_path, group, encoding='automatic', fallback_encoding='cp1252', generated_regexes=pygount.common.regexes_from(DEFAULT_GENERATED_PATTERNS_TEXT), duplicate_pool=None): """ Analysis for line counts in source code stored in ``source_path``. :param source_path:...
replace all masked values calculate flatField from 2d - polynomal fit filling all high gradient areas within averaged fit - image returns flatField average background level fitted image valid indices mask
def polynomial(img, mask, inplace=False, replace_all=False, max_dev=1e-5, max_iter=20, order=2): ''' replace all masked values calculate flatField from 2d-polynomal fit filling all high gradient areas within averaged fit-image returns flatField, average background level, fitte...
TODO
def errorDist(scale, measExpTime, n_events_in_expTime, event_duration, std, points_per_time=100, n_repetitions=300): ''' TODO ''' ntimes = 10 s1 = measExpTime * scale * 10 # exp. time factor 1/16-->16: p2 = np.logspace(-4, 4, 18, base=2) t = np.lin...
std... standard deviation of every signal dur1... dur3 -- > event duration per second n1... n3 -- > number of events per second
def exampleSignals(std=1, dur1=1, dur2=3, dur3=0.2, n1=0.5, n2=0.5, n3=2): ''' std ... standard deviation of every signal dur1...dur3 --> event duration per second n1...n3 --> number of events per second ''' np.random.seed(123) t = np.linspace(0, 10, 100) ...
returns Gaussian shaped signal fluctuations [ events ] t -- > times to calculate event for n -- > numbers of events per sec duration -- > event duration per sec std -- > std of event if averaged over time offs -- > event offset
def _flux(t, n, duration, std, offs=1): ''' returns Gaussian shaped signal fluctuations [events] t --> times to calculate event for n --> numbers of events per sec duration --> event duration per sec std --> std of event if averaged over time offs --> event offset ''' ...
capture signal and return its standard deviation #TODO: more detail
def _capture(f, t, t0, factor): ''' capture signal and return its standard deviation #TODO: more detail ''' n_per_sec = len(t) / t[-1] # len of one split: n = int(t0 * factor * n_per_sec) s = len(f) // n m = s * n f = f[:m] ff = np.split(f, s) m = np.mean(ff...
Return a generic camera matrix [[ fx 0 cx ] [ 0 fy cy ] [ 0 0 1 ]] for a given image shape
def genericCameraMatrix(shape, angularField=60): ''' Return a generic camera matrix [[fx, 0, cx], [ 0, fy, cy], [ 0, 0, 1]] for a given image shape ''' # http://nghiaho.com/?page_id=576 # assume that the optical centre is in the middle: cy = int(shape[0] / 2) cx ...
calculate the spatial resolved standard deviation for a given 2d array ksize - > kernel size blurred ( optional ) - > with same ksize gaussian filtered image setting this parameter reduces processing time
def standardDeviation2d(img, ksize=5, blurred=None): ''' calculate the spatial resolved standard deviation for a given 2d array ksize -> kernel size blurred(optional) -> with same ksize gaussian filtered image setting this parameter reduces processing time ...
fn [ mean median ] fill_mask = True: replaced masked areas with filtered results fill_mask = False: masked areas are ignored
def maskedFilter(arr, mask, ksize=30, fill_mask=True, fn='median'): ''' fn['mean', 'median'] fill_mask=True: replaced masked areas with filtered results fill_mask=False: masked areas are ignored ''' if fill_mask: mask1 = mask out = ar...
Extract vignetting from a set of images containing different devices The devices spatial inhomogeneities are averaged This method is referred as Method C in --- K. Bedrich M. Bokalic et al.: ELECTROLUMINESCENCE IMAGING OF PV DEVICES: ADVANCED FLAT FIELD CALIBRATION 2017 ---
def vignettingFromDifferentObjects(imgs, bg): ''' Extract vignetting from a set of images containing different devices The devices spatial inhomogeneities are averaged This method is referred as 'Method C' in --- K.Bedrich, M.Bokalic et al.: ELECTROLUMINESCENCE IMAGING OF PV D...
Calculate the averaged signal - to - noise ratio SNR50 as defined by IEC NP 60904 - 13 needs 2 reference EL images and one background image
def SNR_IEC(i1, i2, ibg=0, allow_color_images=False): ''' Calculate the averaged signal-to-noise ratio SNR50 as defined by IEC NP 60904-13 needs 2 reference EL images and one background image ''' # ensure images are type float64 (double precision): i1 = np.asfarray(i1) i2 = np....
angle [ DEG ]
def _rotate(img, angle): ''' angle [DEG] ''' s = img.shape if angle == 0: return img else: M = cv2.getRotationMatrix2D((s[1] // 2, s[0] // 2), angle, 1) return cv2.warpAffine(img, M, (s...
return offset ( x y ) which fit best self. _base_img through template matching
def _findOverlap(self, img_rgb, overlap, overlapDeviation, rotation, rotationDeviation): ''' return offset(x,y) which fit best self._base_img through template matching ''' # get gray images if len(img_rgb.shape) != len(img_rgb.shape): ...
estimate the noise level function as stDev over image intensity from a set of 2 image groups images at the same position have to show the identical setup so imgs1 [ i ] - imgs2 [ i ] = noise
def estimateFromImages(imgs1, imgs2=None, mn_mx=None, nbins=100): ''' estimate the noise level function as stDev over image intensity from a set of 2 image groups images at the same position have to show the identical setup, so imgs1[i] - imgs2[i] = noise ''' if imgs2 is None: ...
get the parameters of the needed by function through curve fitting
def _evaluate(x, y, weights): ''' get the parameters of the, needed by 'function' through curve fitting ''' i = _validI(x, y, weights) xx = x[i] y = y[i] try: fitParams = _fit(xx, y) # bound noise fn to min defined y value: minY = function(xx[0], *fit...
limit [ function ] to a minimum y value
def boundedFunction(x, minY, ax, ay): ''' limit [function] to a minimum y value ''' y = function(x, ax, ay) return np.maximum(np.nan_to_num(y), minY)
general square root function
def function(x, ax, ay): ''' general square root function ''' with np.errstate(invalid='ignore'): return ay * (x - ax)**0.5
return indices that have enough data points and are not erroneous
def _validI(x, y, weights): ''' return indices that have enough data points and are not erroneous ''' # density filter: i = np.logical_and(np.isfinite(y), weights > np.median(weights)) # filter outliers: try: grad = np.abs(np.gradient(y[i])) max_gradient = 4 * np.me...
in case the NLF cannot be described by a square root function commit bounded polynomial interpolation
def smooth(x, y, weights): ''' in case the NLF cannot be described by a square root function commit bounded polynomial interpolation ''' # Spline hard to smooth properly, therefore solfed with # bounded polynomal interpolation # ext=3: no extrapolation, but boundary value # ...
Estimate the NLF from one or two images of the same kind
def oneImageNLF(img, img2=None, signal=None): ''' Estimate the NLF from one or two images of the same kind ''' x, y, weights, signal = calcNLF(img, img2, signal) _, fn, _ = _evaluate(x, y, weights) return fn, signal
Get the a range of image intensities that most pixels are in with
def _getMinMax(img): ''' Get the a range of image intensities that most pixels are in with ''' av = np.mean(img) std = np.std(img) # define range for segmentation: mn = av - 3 * std mx = av + 3 * std return max(img.min(), mn, 0), min(img.max(), mx)
Calculate the noise level function ( NLF ) as f ( intensity ) using one or two image. The approach for this work is published in JPV########## img2 - 2nd image taken under same conditions used to estimate noise via image difference signalFromMultipleImages - whether the signal is an average of multiple images and not j...
def calcNLF(img, img2=None, signal=None, mn_mx_nbins=None, x=None, averageFn='AAD', signalFromMultipleImages=False): ''' Calculate the noise level function (NLF) as f(intensity) using one or two image. The approach for this work is published in JPV########## img2 - 2...
fit unstructured data
def polyfit2d(x, y, z, order=3 #bounds=None ): ''' fit unstructured data ''' ncols = (order + 1)**2 G = np.zeros((x.size, ncols)) ij = itertools.product(list(range(order+1)), list(range(order+1))) for k, (i,j) in enumerate(ij): G[:,k] = x**i * y**j m = np...
replace all masked values with polynomial fitted ones
def polyfit2dGrid(arr, mask=None, order=3, replace_all=False, copy=True, outgrid=None): ''' replace all masked values with polynomial fitted ones ''' s0,s1 = arr.shape if mask is None: if outgrid is None: y,x = np.mgrid[:float(s0),:float(s1)] ...
find closest minimum position next to middle line relative: return position relative to middle line f: relative decrease ( 0... 1 ) - setting this value close to one will discriminate positions further away from the center ##order: 2 for cubic refinement
def minimumLineInArray(arr, relative=False, f=0, refinePosition=True, max_pos=100, return_pos_arr=False, # order=2 ): ''' find closest minimum position next to middle line relative: ret...
remove all low frequencies by setting a square in the middle of the Fourier transformation of the size ( 2 * threshold ) ^2 to zero threshold = 0... 1
def highPassFilter(self, threshold): ''' remove all low frequencies by setting a square in the middle of the Fourier transformation of the size (2*threshold)^2 to zero threshold = 0...1 ''' if not threshold: return rows, cols = self.img.shape ...
remove all high frequencies by setting boundary around a quarry in the middle of the size ( 2 * threshold ) ^2 to zero threshold = 0... 1
def lowPassFilter(self, threshold): ''' remove all high frequencies by setting boundary around a quarry in the middle of the size (2*threshold)^2 to zero threshold = 0...1 ''' if not threshold: return rows, cols = self.img.shape tx = i...
do inverse Fourier transform and return result
def reconstructImage(self): ''' do inverse Fourier transform and return result ''' f_ishift = np.fft.ifftshift(self.fshift) return np.real(np.fft.ifft2(f_ishift))
x y v -- > 1d numpy. array grid -- > 2d numpy. array fast if number of given values is small relative to grid resolution
def interpolate2dUnstructuredIDW(x, y, v, grid, power=2): ''' x,y,v --> 1d numpy.array grid --> 2d numpy.array fast if number of given values is small relative to grid resolution ''' n = len(v) gx = grid.shape[0] gy = grid.shape[1] for i in range(gx): for j in ran...
returns the Histogram of Oriented Gradients: param ksize: convolution kernel size as ( y x ) - needs to be odd: param orientations: number of orientations in between rad = 0 and rad = pi similar to http:// scikit - image. org/ docs/ dev/ auto_examples/ plot_hog. html but faster and with less options
def hog(image, orientations=8, ksize=(5, 5)): ''' returns the Histogram of Oriented Gradients :param ksize: convolution kernel size as (y,x) - needs to be odd :param orientations: number of orientations in between rad=0 and rad=pi similar to http://scikit-image.org/docs/dev/auto_examples/pl...
visualize HOG as polynomial around cell center for [ grid ] * cells
def visualize(hog, grid=(10, 10), radCircle=None): ''' visualize HOG as polynomial around cell center for [grid] * cells ''' s0, s1, nang = hog.shape angles = np.linspace(0, np.pi, nang + 1)[:-1] # center of each sub array: cx, cy = s0 // (2 * grid[0]), s1 // (2 * grid[1]) ...
Post process measured flat field [ arr ]. Depending on the measurement different post processing [ method ] s are beneficial. The available methods are presented in --- K. Bedrich M. Bokalic et al.: ELECTROLUMINESCENCE IMAGING OF PV DEVICES: ADVANCED FLAT FIELD CALIBRATION 2017 --- methods: POLY replace -- > replace [ ...
def postProcessing(arr, method='KW replace + Gauss', mask=None): ''' Post process measured flat field [arr]. Depending on the measurement, different post processing [method]s are beneficial. The available methods are presented in --- K.Bedrich, M.Bokalic et al.: ...
border [ None ] if images are corrected and device ends at image border [ one number ] ( like 50 ) if there is an equally spaced border around the device [ two tuples ] like (( 50 60 ) ( 1500 900 )) means (( Xfrom Yfrom ) ( Xto Yto )) [ four tuples ] like (( x0 y0 ) ( x1 y1 )... ( x3 y3 ))
def rmBorder(img, border=None): ''' border [None], if images are corrected and device ends at image border [one number] (like 50), if there is an equally spaced border aroun...
######### mask -- optional
def addImage(self, image, mask=None): ''' ######### mask -- optional ''' self._last_diff = diff = image - self.noSTE ste = diff > self.threshold removeSinglePixels(ste) self.mask_clean = clean = ~ste if mask is not None: ...
return STE area - relative to image area
def relativeAreaSTE(self): ''' return STE area - relative to image area ''' s = self.noSTE.shape return np.sum(self.mask_STE) / (s[0] * s[1])
return distribution of STE intensity
def intensityDistributionSTE(self, bins=10, range=None): ''' return distribution of STE intensity ''' v = np.abs(self._last_diff[self.mask_STE]) return np.histogram(v, bins, range)
transform a float to an unsigned integer array of a fitting dtype adds an offset to get rid of negative values range = ( min max ) - scale values between given range cutNegative - all values <0 will be set to 0 cutHigh - set to False to rather scale values to fit
def toUIntArray(img, dtype=None, cutNegative=True, cutHigh=True, range=None, copy=True): ''' transform a float to an unsigned integer array of a fitting dtype adds an offset, to get rid of negative values range = (min, max) - scale values between given range cutNegative - a...
transform an unsigned integer array into a float array of the right size
def toFloatArray(img): ''' transform an unsigned integer array into a float array of the right size ''' _D = {1: np.float32, # uint8 2: np.float32, # uint16 4: np.float64, # uint32 8: np.float64} # uint64 return img.astype(_D[img.itemsize])
cast array to the next higher integer array if dtype = unsigned integer
def toNoUintArray(arr): ''' cast array to the next higher integer array if dtype=unsigned integer ''' d = arr.dtype if d.kind == 'u': arr = arr.astype({1: np.int16, 2: np.int32, 4: np.int64}[d.itemsize]) return arr
weights see https:// en. wikipedia. org/ wiki/ Grayscale#Colorimetric_. 28luminance - prese http:// docs. opencv. org/ 2. 4/ modules/ imgproc/ doc/ miscellaneous_transformations. html#cvtcolor
def toGray(img): ''' weights see https://en.wikipedia.org/wiki/Grayscale#Colorimetric_.28luminance-prese http://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html#cvtcolor ''' return np.average(img, axis=-1, weights=(0.299, # red ...
returns the normalized RGB space ( RGB/ intensity ) see https:// en. wikipedia. org/ wiki/ Rg_chromaticity
def rgChromaticity(img): ''' returns the normalized RGB space (RGB/intensity) see https://en.wikipedia.org/wiki/Rg_chromaticity ''' out = _calc(img) if img.dtype == np.uint8: out = (255 * out).astype(np.uint8) return out
TODO##########
def monochromaticWavelength(img): ''' TODO########## ''' # peak wave lengths: https://en.wikipedia.org/wiki/RGB_color_model out = _calc(img) peakWavelengths = (570, 540, 440) # (r,g,b) # s = sum(peakWavelengths) for n, p in enumerate(peakWavelengths): out[..., n] *= p...
rotate one or multiple grayscale or color images 90 degrees
def rot90(img): ''' rotate one or multiple grayscale or color images 90 degrees ''' s = img.shape if len(s) == 3: if s[2] in (3, 4): # color image out = np.empty((s[1], s[0], s[2]), dtype=img.dtype) for i in range(s[2]): out[:, :, i] = np.rot...
like cv2. applyColorMap ( im_gray cv2. COLORMAP_ * ) but with different color maps
def applyColorMap(gray, cmap='flame'): ''' like cv2.applyColorMap(im_gray, cv2.COLORMAP_*) but with different color maps ''' # TODO:implement more cmaps if cmap != 'flame': raise NotImplemented # TODO: make better mx = 256 # if gray.dtype==np.uint8 else 65535 lut = np.e...
returns the index to insert the given date in a list where each items first value is a date
def _insertDateIndex(date, l): ''' returns the index to insert the given date in a list where each items first value is a date ''' return next((i for i, n in enumerate(l) if n[0] < date), len(l))
returns the index of given or best fitting date
def _getFromDate(l, date): ''' returns the index of given or best fitting date ''' try: date = _toDate(date) i = _insertDateIndex(date, l) - 1 if i == -1: return l[0] return l[i] except (ValueError, TypeError): # ValueError: date invalid...
Args: typ: type of calibration to look for. See. coeffs. keys () for all types available light ( Optional [ str ] ): restrict to calibrations done given light source Returns: list: All calibration dates available for given typ
def dates(self, typ, light=None): ''' Args: typ: type of calibration to look for. See .coeffs.keys() for all types available light (Optional[str]): restrict to calibrations, done given light source Returns: list: All calibration dates available for giv...
Args: typ: type of calibration to look for. See. coeffs. keys () for all types available date ( Optional [ str ] ): date of calibration Returns: list: all infos available for given typ
def infos(self, typ, light=None, date=None): ''' Args: typ: type of calibration to look for. See .coeffs.keys() for all types available date (Optional[str]): date of calibration Returns: list: all infos available for given typ ''' d =...
Returns: str: an overview covering all calibrations infos and shapes
def overview(self): ''' Returns: str: an overview covering all calibrations infos and shapes ''' c = self.coeffs out = 'camera name: %s' % c['name'] out += '\nmax value: %s' % c['depth'] out += '\nlight spectra: %s' % c['light spe...
Args: camera_name ( str ): Name of the camera bit_depth ( int ): depth ( bit ) of the camera sensor
def setCamera(self, camera_name, bit_depth=16): ''' Args: camera_name (str): Name of the camera bit_depth (int): depth (bit) of the camera sensor ''' self.coeffs['name'] = camera_name self.coeffs['depth'] = bit_depth
Args: slope ( np. array ) intercept ( np. array ) error ( numpy. array ) slope ( float ): dPx/ dExposureTime [ sec ] error ( float ): absolute date ( str ): DD Mon YY e. g. 30 Nov 16
def addDarkCurrent(self, slope, intercept=None, date=None, info='', error=None): ''' Args: slope (np.array) intercept (np.array) error (numpy.array) slope (float): dPx/dExposureTime[sec] error (float): absolute date (str): "...
Args: nlf_coeff ( list ) error ( float ): absolute info ( str ): additional information date ( str ): DD Mon YY e. g. 30 Nov 16
def addNoise(self, nlf_coeff, date=None, info='', error=None): ''' Args: nlf_coeff (list) error (float): absolute info (str): additional information date (str): "DD Mon YY" e.g. "30 Nov 16" ''' date = _toDate(date) d = self...
add a new point spread function
def addPSF(self, psf, date=None, info='', light_spectrum='visible'): ''' add a new point spread function ''' self._registerLight(light_spectrum) date = _toDate(date) f = self.coeffs['psf'] if light_spectrum not in f: f[light_spectrum] = [] ...
light_spectrum = light IR...
def addFlatField(self, arr, date=None, info='', error=None, light_spectrum='visible'): ''' light_spectrum = light, IR ... ''' self._registerLight(light_spectrum) self._checkShape(arr) date = _toDate(date) f = self.coeffs['flat field'] ...
lens - > instance of LensDistortion or saved file
def addLens(self, lens, date=None, info='', light_spectrum='visible'): ''' lens -> instance of LensDistortion or saved file ''' self._registerLight(light_spectrum) date = _toDate(date) if not isinstance(lens, LensDistortion): l = LensDistortion() ...
if not only a specific date than remove all except of the youngest calibration
def clearOldCalibrations(self, date=None): ''' if not only a specific date than remove all except of the youngest calibration ''' self.coeffs['dark current'] = [self.coeffs['dark current'][-1]] self.coeffs['noise'] = [self.coeffs['noise'][-1]] for light in self.co...
transpose all calibration arrays in case different array shape orders were used ( x y ) vs. ( y x )
def transpose(self): ''' transpose all calibration arrays in case different array shape orders were used (x,y) vs. (y,x) ''' def _t(item): if type(item) == list: for n, it in enumerate(item): if type(it) == tuple: ...
exposure_time [ s ] date - > string e. g. 30. Nov 15 to get a calibration on from date - > { dark current: 30. Nov 15 flat field: 15. Nov 15 lens: 14. Nov 15 noise: 01. Nov 15 }
def correct(self, images, bgImages=None, exposure_time=None, light_spectrum=None, threshold=0.1, keep_size=True, date=None, deblur=False, denoise=False): ''' exposure...
denoise using non - local - means with guessing best parameters
def _correctNoise(self, image): ''' denoise using non-local-means with guessing best parameters ''' from skimage.restoration import denoise_nl_means # save startup time image[np.isnan(image)] = 0 # otherwise result =nan out = denoise_nl_means(image, ...
open OR calculate a background image: f ( t ) = m * t + n
def _correctDarkCurrent(self, image, exposuretime, bgImages, date): ''' open OR calculate a background image: f(t)=m*t+n ''' # either exposureTime or bgImages has to be given # if exposuretime is not None or bgImages is not None: print('... remove dark current') ...
Apply a thresholded median replacing high gradients and values beyond the boundaries
def _correctArtefacts(self, image, threshold): ''' Apply a thresholded median replacing high gradients and values beyond the boundaries ''' image = np.nan_to_num(image) medianThreshold(image, threshold, copy=False) return image
try to get calibration for right light source but use another if they is none existent
def getCoeff(self, name, light=None, date=None): ''' try to get calibration for right light source, but use another if they is none existent ''' d = self.coeffs[name] try: c = d[light] except KeyError: try: k, i ...
important: first image should shown most iof the device because it is used as reference
def vignettingFromRandomSteps(imgs, bg, inPlane_scale_factor=None, debugFolder=None, **kwargs): ''' important: first image should shown most iof the device because it is used as reference ''' # TODO: inPlane_scale_factor if debugFolder: debugFolder =...