sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
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...
return indices that have enough data points and are not erroneous
entailment
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 # ...
in case the NLF cannot be described by a square root function commit bounded polynomial interpolation
entailment
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
Estimate the NLF from one or two images of the same kind
entailment
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)
Get the a range of image intensities that most pixels are in with
entailment
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...
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 avera...
entailment
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...
fit unstructured data
entailment
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)] ...
replace all masked values with polynomial fitted ones
entailment
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...
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
entailment
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 low frequencies by setting a square in the middle of the Fourier transformation of the size (2*threshold)^2 to zero threshold = 0...1
entailment
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...
remove all high frequencies by setting boundary around a quarry in the middle of the size (2*threshold)^2 to zero threshold = 0...1
entailment
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))
do inverse Fourier transform and return result
entailment
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...
x,y,v --> 1d numpy.array grid --> 2d numpy.array fast if number of given values is small relative to grid resolution
entailment
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...
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
entailment
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]) ...
visualize HOG as polynomial around cell center for [grid] * cells
entailment
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.: ...
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 CALI...
entailment
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...
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 tu...
entailment
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: ...
######### mask -- optional
entailment
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 STE area - relative to image area
entailment
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)
return distribution of STE intensity
entailment
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 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
entailment
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])
transform an unsigned integer array into a float array of the right size
entailment
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
cast array to the next higher integer array if dtype=unsigned integer
entailment
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 ...
weights see https://en.wikipedia.org/wiki/Grayscale#Colorimetric_.28luminance-prese http://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html#cvtcolor
entailment
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
returns the normalized RGB space (RGB/intensity) see https://en.wikipedia.org/wiki/Rg_chromaticity
entailment
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...
TODO##########
entailment
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...
rotate one or multiple grayscale or color images 90 degrees
entailment
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...
like cv2.applyColorMap(im_gray, cv2.COLORMAP_*) but with different color maps
entailment
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 to insert the given date in a list where each items first value is a date
entailment
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...
returns the index of given or best fitting date
entailment
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 light (Optional[str]): restrict to calibrations, done given light source Returns: list: All calibration dates available for given typ
entailment
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 =...
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
entailment
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...
Returns: str: an overview covering all calibrations infos and shapes
entailment
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: camera_name (str): Name of the camera bit_depth (int): depth (bit) of the camera sensor
entailment
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: 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"
entailment
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...
Args: nlf_coeff (list) error (float): absolute info (str): additional information date (str): "DD Mon YY" e.g. "30 Nov 16"
entailment
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] = [] ...
add a new point spread function
entailment
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'] ...
light_spectrum = light, IR ...
entailment
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() ...
lens -> instance of LensDistortion or saved file
entailment
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...
if not only a specific date than remove all except of the youngest calibration
entailment
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: ...
transpose all calibration arrays in case different array shape orders were used (x,y) vs. (y,x)
entailment
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...
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'}
entailment
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, ...
denoise using non-local-means with guessing best parameters
entailment
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') ...
open OR calculate a background image: f(t)=m*t+n
entailment
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
Apply a thresholded median replacing high gradients and values beyond the boundaries
entailment
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 ...
try to get calibration for right light source, but use another if they is none existent
entailment
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 =...
important: first image should shown most iof the device because it is used as reference
entailment
def addImg(self, img, maxShear=0.015, maxRot=100, minMatches=12, borderWidth=3): # borderWidth=100 """ Args: img (path or array): image containing the same object as in the reference image Kwargs: maxShear (float): In order to define a good fit, refe...
Args: img (path or array): image containing the same object as in the reference image Kwargs: maxShear (float): In order to define a good fit, refect higher shear values between this and the reference image maxRot (float): Same for rotation ...
entailment
def error(self, nCells=15): ''' calculate the standard deviation of all fitted images, averaged to a grid ''' s0, s1 = self.fits[0].shape aR = s0 / s1 if aR > 1: ss0 = int(nCells) ss1 = int(ss0 / aR) else: ss...
calculate the standard deviation of all fitted images, averaged to a grid
entailment
def _fitImg(self, img): ''' fit perspective and size of the input image to the reference image ''' img = imread(img, 'gray') if self.bg is not None: img = cv2.subtract(img, self.bg) if self.lens is not None: img = self.lens.correct(img, k...
fit perspective and size of the input image to the reference image
entailment
def _findObject(self, img): ''' Create a bounding box around the object within an image ''' from imgProcessor.imgSignal import signalMinimum # img is scaled already i = img > signalMinimum(img) # img.max()/2.5 # filter noise, single-time-effects etc. from ...
Create a bounding box around the object within an image
entailment
def filterVerticalLines(arr, min_line_length=4): """ Remove vertical lines in boolean array if linelength >=min_line_length """ gy = arr.shape[0] gx = arr.shape[1] mn = min_line_length-1 for i in range(gy): for j in range(gx): if arr[i,j]: for d ...
Remove vertical lines in boolean array if linelength >=min_line_length
entailment
def vignetting(xy, f=100, alpha=0, rot=0, tilt=0, cx=50, cy=50): ''' Vignetting equation using the KANG-WEISS-MODEL see http://research.microsoft.com/en-us/um/people/sbkang/publications/eccv00.pdf f - focal length alpha - coefficient in the geometric vignetting factor tilt - tilt angl...
Vignetting equation using the KANG-WEISS-MODEL see http://research.microsoft.com/en-us/um/people/sbkang/publications/eccv00.pdf f - focal length alpha - coefficient in the geometric vignetting factor tilt - tilt angle of a planar scene rot - rotation angle of a planar scene cx - image...
entailment
def tiltFactor(xy, f, tilt, rot, center=None): ''' this function is extra to only cover vignetting through perspective distortion f - focal length [px] tau - tilt angle of a planar scene [radian] rot - rotation angle of a planar scene [radian] ''' x, y = xy arr = np.cos(tilt) *...
this function is extra to only cover vignetting through perspective distortion f - focal length [px] tau - tilt angle of a planar scene [radian] rot - rotation angle of a planar scene [radian]
entailment
def imgAverage(images, copy=True): ''' returns an image average works on many, also unloaded images minimises RAM usage ''' i0 = images[0] out = imread(i0, dtype='float') if copy and id(i0) == id(out): out = out.copy() for i in images[1:]: out += imread...
returns an image average works on many, also unloaded images minimises RAM usage
entailment
def offsetMeshgrid(offset, grid, shape): ''' Imagine you have cell averages [grid] on an image. the top-left position of [grid] within the image can be variable [offset] offset(x,y) e.g.(0,0) if no offset grid(nx,ny) resolution of smaller grid shape(x,y) -> output sha...
Imagine you have cell averages [grid] on an image. the top-left position of [grid] within the image can be variable [offset] offset(x,y) e.g.(0,0) if no offset grid(nx,ny) resolution of smaller grid shape(x,y) -> output shape returns meshgrid to be used to upscale [...
entailment
def poisson(x, a, b, c, d=0): ''' Poisson function a -> height of the curve's peak b -> position of the center of the peak c -> standard deviation d -> offset ''' from scipy.misc import factorial #save startup time lamb = 1 X = (x/(2*c)).astype(int) return a * ((...
Poisson function a -> height of the curve's peak b -> position of the center of the peak c -> standard deviation d -> offset
entailment
def rotate(image, angle, interpolation=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REFLECT, borderValue=0): ''' angle [deg] ''' s0, s1 = image.shape image_center = (s0 - 1) / 2., (s1 - 1) / 2. rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0) result = cv2.warpAffine(i...
angle [deg]
entailment
def adjustUncertToExposureTime(facExpTime, uncertMap, evtLenMap): ''' Adjust image uncertainty (measured at exposure time t0) to new exposure time facExpTime --> new exp.time / reference exp.time =(t/t0) uncertMap --> 2d array mapping image uncertainty evtLen --> 2d array mappi...
Adjust image uncertainty (measured at exposure time t0) to new exposure time facExpTime --> new exp.time / reference exp.time =(t/t0) uncertMap --> 2d array mapping image uncertainty evtLen --> 2d array mapping event duration within image [sec] event duration is relative...
entailment
def gaussian(x, a, b, c, d=0): ''' a -> height of the curve's peak b -> position of the center of the peak c -> standard deviation or Gaussian RMS width d -> offset ''' return a * np.exp( -(((x-b)**2 )/ (2*(c**2))) ) + d
a -> height of the curve's peak b -> position of the center of the peak c -> standard deviation or Gaussian RMS width d -> offset
entailment
def videoWrite(path, imgs, levels=None, shape=None, frames=15, annotate_names=None, lut=None, updateFn=None): ''' TODO ''' frames = int(frames) if annotate_names is not None: assert len(annotate_names) == len(imgs) if levels is None: if i...
TODO
entailment
def imread(img, color=None, dtype=None): ''' dtype = 'noUint', uint8, float, 'float', ... ''' COLOR2CV = {'gray': cv2.IMREAD_GRAYSCALE, 'all': cv2.IMREAD_COLOR, None: cv2.IMREAD_ANYCOLOR } c = COLOR2CV[color] if callable(img): img...
dtype = 'noUint', uint8, float, 'float', ...
entailment
def addImg(self, img, roi=None): ''' img - background, flat field, ste corrected image roi - [(x1,y1),...,(x4,y4)] - boundaries where points are ''' self.img = imread(img, 'gray') s0, s1 = self.img.shape if roi is None: roi = ((0, 0), (s0, 0...
img - background, flat field, ste corrected image roi - [(x1,y1),...,(x4,y4)] - boundaries where points are
entailment
def interpolate2dStructuredFastIDW(grid, mask, kernel=15, power=2, minnvals=5): ''' FASTER IMPLEMENTATION OF interpolate2dStructuredIDW replace all values in [grid] indicated by [mask] with the inverse distance weighted interpolation of all values within px...
FASTER IMPLEMENTATION OF interpolate2dStructuredIDW replace all values in [grid] indicated by [mask] with the inverse distance weighted interpolation of all values within px+-kernel [power] -> distance weighting factor: 1/distance**[power] [minvals] -> minimum number of neighbour values to ...
entailment
def linearBlend(img1, img2, overlap, backgroundColor=None): ''' Stitch 2 images vertically together. Smooth the overlap area of both images with a linear fade from img1 to img2 @param img1: numpy.2dArray @param img2: numpy.2dArray of the same shape[1,2] as img1 @param overlap: number of ...
Stitch 2 images vertically together. Smooth the overlap area of both images with a linear fade from img1 to img2 @param img1: numpy.2dArray @param img2: numpy.2dArray of the same shape[1,2] as img1 @param overlap: number of pixels both images overlap @returns: stitched-image
entailment
def interpolate2dStructuredPointSpreadIDW(grid, mask, kernel=15, power=2, maxIter=1e5, copy=True): ''' same as interpolate2dStructuredIDW but using the point spread method this is faster if there are bigger connected masked areas and the border length is sm...
same as interpolate2dStructuredIDW but using the point spread method this is faster if there are bigger connected masked areas and the border length is smaller replace all values in [grid] indicated by [mask] with the inverse distance weighted interpolation of all values within px+-kernel ...
entailment
def SNRaverage(snr, method='average', excludeBackground=True, checkBackground=True, backgroundLevel=None): ''' average a signal-to-noise map :param method: ['average','X75', 'RMS', 'median'] - X75: this SNR will be exceeded by 75% of the signal :type method: str ...
average a signal-to-noise map :param method: ['average','X75', 'RMS', 'median'] - X75: this SNR will be exceeded by 75% of the signal :type method: str :param checkBackground: check whether there is actually a background level to exclude :type checkBackground: bool :returns: averaged SNR as ...
entailment
def maskedConvolve(arr, kernel, mask, mode='reflect'): ''' same as scipy.ndimage.convolve but is only executed on mask==True ... which should speed up everything ''' arr2 = extendArrayForConvolution(arr, kernel.shape, modex=mode, modey=mode) print(arr2.shape) out = np.zeros_like(arr) ...
same as scipy.ndimage.convolve but is only executed on mask==True ... which should speed up everything
entailment
def SNR(img1, img2=None, bg=None, noise_level_function=None, constant_noise_level=False, imgs_to_be_averaged=False): ''' Returns a signal-to-noise-map uses algorithm as described in BEDRICH 2016 JPV (not jet published) :param constant_noise_level: True, to assume noise t...
Returns a signal-to-noise-map uses algorithm as described in BEDRICH 2016 JPV (not jet published) :param constant_noise_level: True, to assume noise to be constant :param imgs_to_be_averaged: True, if SNR is for average(img1, img2)
entailment
def sortCorners(corners): ''' sort the corners of a given quadrilateral of the type corners : [ [xi,yi],... ] to an anti-clockwise order starting with the bottom left corner or (if plotted as image where y increases to the bottom): clockwise, starting top left ''' corners = n...
sort the corners of a given quadrilateral of the type corners : [ [xi,yi],... ] to an anti-clockwise order starting with the bottom left corner or (if plotted as image where y increases to the bottom): clockwise, starting top left
entailment
def closestDirectDistance(arr, ksize=30, dtype=np.uint16): ''' return an array with contains the closest distance to the next positive value given in arr within a given kernel size ''' out = np.zeros_like(arr, dtype=dtype) _calc(out, arr, ksize) return out
return an array with contains the closest distance to the next positive value given in arr within a given kernel size
entailment
def closestConnectedDistance(target, walls=None, max_len_border_line=500, max_n_path=100, concentrate_every_n_pixel=1): ''' returns an array with contains the closest distance from every pixel the next position wher...
returns an array with contains the closest distance from every pixel the next position where target == 1 [walls] binary 2darray - e.g. walls in a labyrinth that have to be surrounded in order to get to the target [target] binary 2darray - positions given by 1 [concentrate_every_n_pixel] often ...
entailment
def _grow(growth, walls, target, i, j, steps, new_steps, res): ''' fills [res] with [distance to next position where target == 1, x coord., y coord. of that position in target] using region growth i,j -> pixel position growth -> a work array, ne...
fills [res] with [distance to next position where target == 1, x coord., y coord. of that position in target] using region growth i,j -> pixel position growth -> a work array, needed to measure the distance steps, new_steps -> current and last posit...
entailment
def polylinesFromBinImage(img, minimum_cluster_size=6, remove_small_obj_size=3, reconnect_size=3, max_n_contours=None, max_len_contour=None, copy=True): ''' return a list of arrays of un-branching conto...
return a list of arrays of un-branching contours img -> (boolean) array optional: --------- minimum_cluster_size -> minimum number of pixels connected together to build a contour ##search_kernel_size -> TODO ##min_search_kernel_moment -> TODO numeric: ------------- ...
entailment
def cdf(arr, pos=None): ''' Return the cumulative density function of a given array or its intensity at a given position (0-1) ''' r = (arr.min(), arr.max()) hist, bin_edges = np.histogram(arr, bins=2 * int(r[1] - r[0]), range=r) hist = np.asfarray(hist) / hist.sum() cdf = np.c...
Return the cumulative density function of a given array or its intensity at a given position (0-1)
entailment
def subCell2DGenerator(arr, shape, d01=None, p01=None): '''Generator to access evenly sized sub-cells in a 2d array Args: shape (tuple): number of sub-cells in y,x e.g. (10,15) d01 (tuple, optional): cell size in y and x p01 (tuple, optional): position of top left edge Returns...
Generator to access evenly sized sub-cells in a 2d array Args: shape (tuple): number of sub-cells in y,x e.g. (10,15) d01 (tuple, optional): cell size in y and x p01 (tuple, optional): position of top left edge Returns: int: 1st index int: 2nd index array...
entailment
def subCell2DSlices(arr, shape, d01=None, p01=None): '''Generator to access evenly sized sub-cells in a 2d array Args: shape (tuple): number of sub-cells in y,x e.g. (10,15) d01 (tuple, optional): cell size in y and x p01 (tuple, optional): position of top left edge Returns: ...
Generator to access evenly sized sub-cells in a 2d array Args: shape (tuple): number of sub-cells in y,x e.g. (10,15) d01 (tuple, optional): cell size in y and x p01 (tuple, optional): position of top left edge Returns: int: 1st index int: 2nd index slice...
entailment
def subCell2DCoords(*args, **kwargs): '''Same as subCell2DSlices but returning coordinates Example: g = subCell2DCoords(arr, shape) for x, y in g: plt.plot(x, y) ''' for _, _, s0, s1 in subCell2DSlices(*args, **kwargs): yield ((s1.start, s1.start, s1.sto...
Same as subCell2DSlices but returning coordinates Example: g = subCell2DCoords(arr, shape) for x, y in g: plt.plot(x, y)
entailment
def subCell2DFnArray(arr, fn, shape, dtype=None, **kwargs): ''' Return array where every cell is the output of a given cell function Args: fn (function): ...to be executed on all sub-arrays Returns: array: value of every cell equals result of fn(sub-array) Example: ...
Return array where every cell is the output of a given cell function Args: fn (function): ...to be executed on all sub-arrays Returns: array: value of every cell equals result of fn(sub-array) Example: mx = subCell2DFnArray(myArray, np.max, (10,6) ) - -> here ...
entailment
def defocusThroughDepth(u, uf, f, fn, k=2.355): ''' return the defocus (mm std) through DOF u -> scene point (depth value) uf -> in-focus position (the distance at which the scene point should be placed in order to be focused) f -> focal length k -> camera dependent constant (transfe...
return the defocus (mm std) through DOF u -> scene point (depth value) uf -> in-focus position (the distance at which the scene point should be placed in order to be focused) f -> focal length k -> camera dependent constant (transferring blur circle to PSF), 2.335 would be FHWD of 2dgaussian ...
entailment
def extendArrayForConvolution(arr, kernelXY, modex='reflect', modey='reflect'): ''' extends a given array right right border handling for convolution -->in opposite to skimage and skipy this function allows to chose different mode = ('ref...
extends a given array right right border handling for convolution -->in opposite to skimage and skipy this function allows to chose different mode = ('reflect', 'wrap') in x and y direction only supports 'warp' and 'reflect' at the moment
entailment
def calibrate(self, board_size=(8, 6), method='Chessboard', images=[], max_images=100, sensorSize_mm=None, detect_sensible=True): ''' sensorSize_mm - (width, height) [mm] Physical size of the sensor ''' self._coeffs = {} self.opts = {'fo...
sensorSize_mm - (width, height) [mm] Physical size of the sensor
entailment
def addPoints(self, points, board_size=None): ''' add corner points directly instead of extracting them from image points = ( (0,1), (...),... ) [x,y] ''' self.opts['foundPattern'].append(True) self.findCount += 1 if board_size is not None: ...
add corner points directly instead of extracting them from image points = ( (0,1), (...),... ) [x,y]
entailment
def setImgShape(self, shape): ''' image shape must be known for calculating camera matrix if method==Manual and addPoints is used instead of addImg this method must be called before .coeffs are obtained ''' self.img = type('Dummy', (object,), {}) # if imgPr...
image shape must be known for calculating camera matrix if method==Manual and addPoints is used instead of addImg this method must be called before .coeffs are obtained
entailment
def addImgStream(self, img): ''' add images using a continous stream - stop when max number of images is reached ''' if self.findCount > self.max_images: raise EnoughImages('have enough images') return self.addImg(img)
add images using a continous stream - stop when max number of images is reached
entailment
def addImg(self, img): ''' add one chessboard image for detection lens distortion ''' # self.opts['imgs'].append(img) self.img = imread(img, 'gray', 'uint8') didFindCorners, corners = self.method() self.opts['foundPattern'].append(didFindCorners) ...
add one chessboard image for detection lens distortion
entailment
def getCoeffStr(self): ''' get the distortion coeffs in a formated string ''' txt = '' for key, val in self.coeffs.items(): txt += '%s = %s\n' % (key, val) return txt
get the distortion coeffs in a formated string
entailment
def drawChessboard(self, img=None): ''' draw a grid fitting to the last added image on this one or an extra image img == None ==False -> draw chessbord on empty image ==img ''' assert self.findCount > 0, 'cannot draw chessboard if nothing f...
draw a grid fitting to the last added image on this one or an extra image img == None ==False -> draw chessbord on empty image ==img
entailment
def writeToFile(self, filename, saveOpts=False): ''' write the distortion coeffs to file saveOpts --> Whether so save calibration options (and not just results) ''' try: if not filename.endswith('.%s' % self.ftype): filename += '.%s' % self.ftyp...
write the distortion coeffs to file saveOpts --> Whether so save calibration options (and not just results)
entailment
def readFromFile(self, filename): ''' read the distortion coeffs from file ''' s = dict(np.load(filename)) try: self.coeffs = s['coeffs'][()] except KeyError: #LEGENCY - remove self.coeffs = s try: self.op...
read the distortion coeffs from file
entailment
def undistortPoints(self, points, keepSize=False): ''' points --> list of (x,y) coordinates ''' s = self.img.shape cam = self.coeffs['cameraMatrix'] d = self.coeffs['distortionCoeffs'] pts = np.asarray(points, dtype=np.float32) if pts.ndim == 2: ...
points --> list of (x,y) coordinates
entailment
def correct(self, image, keepSize=False, borderValue=0): ''' remove lens distortion from given image ''' image = imread(image) (h, w) = image.shape[:2] mapx, mapy = self.getUndistortRectifyMap(w, h) self.img = cv2.remap(image, mapx, mapy, cv2.INTER_LINEAR, ...
remove lens distortion from given image
entailment
def distortImage(self, image): ''' opposite of 'correct' ''' image = imread(image) (imgHeight, imgWidth) = image.shape[:2] mapx, mapy = self.getDistortRectifyMap(imgWidth, imgHeight) return cv2.remap(image, mapx, mapy, cv2.INTER_LINEAR, ...
opposite of 'correct'
entailment
def getCameraParams(self): ''' value positions based on http://docs.opencv.org/modules/imgproc/doc/geometric_transformations.html#cv.InitUndistortRectifyMap ''' c = self.coeffs['cameraMatrix'] fx = c[0][0] fy = c[1][1] cx = c[0][2] cy = c...
value positions based on http://docs.opencv.org/modules/imgproc/doc/geometric_transformations.html#cv.InitUndistortRectifyMap
entailment
def standardUncertainties(self, sharpness=0.5): ''' sharpness -> image sharpness // std of Gaussian PSF [px] returns a list of standard uncertainties for the x and y component: (1x,2x), (1y, 2y), (intensity:None) 1. px-size-changes(due to deflection) 2. reprojecti...
sharpness -> image sharpness // std of Gaussian PSF [px] returns a list of standard uncertainties for the x and y component: (1x,2x), (1y, 2y), (intensity:None) 1. px-size-changes(due to deflection) 2. reprojection error
entailment
def edgesFromBoolImg(arr, dtype=None): ''' takes a binary image (usually a mask) and returns the edges of the object inside ''' out = np.zeros_like(arr, dtype=dtype) _calc(arr, out) _calc(arr.T, out.T) return out
takes a binary image (usually a mask) and returns the edges of the object inside
entailment
def draw_matches(img1, kp1, img2, kp2, matches, color=None, thickness=2, r=15): """Draws lines between matching keypoints of two images. Keypoints not in a matching pair are not drawn. Places the images side by side in a new image and draws circles around each keypoint, with line segments connect...
Draws lines between matching keypoints of two images. Keypoints not in a matching pair are not drawn. Places the images side by side in a new image and draws circles around each keypoint, with line segments connecting matching pairs. You can tweak the r, thickness, and figsize values as needed. ...
entailment
def _scaleTo8bit(self, img): ''' The pattern comparator need images to be 8 bit -> find the range of the signal and scale the image ''' r = scaleSignalCutParams(img, 0.02) # , nSigma=3) self.signal_ranges.append(r) return toUIntArray(img, dtype=np.uint8, r...
The pattern comparator need images to be 8 bit -> find the range of the signal and scale the image
entailment
def findHomography(self, img, drawMatches=False): ''' Find homography of the image through pattern comparison with the base image ''' print("\t Finding points...") # Find points in the next frame img = self._prepareImage(img) features, descs = self...
Find homography of the image through pattern comparison with the base image
entailment
def patCircles(s0): '''make circle array''' arr = np.zeros((s0,s0), dtype=np.uint8) col = 255 for rad in np.linspace(s0,s0/7.,10): cv2.circle(arr, (0,0), int(round(rad)), color=col, thickness=-1, lineType=cv2.LINE_AA ) if col: col = 0 else...
make circle array
entailment
def patCrossLines(s0): '''make line pattern''' arr = np.zeros((s0,s0), dtype=np.uint8) col = 255 t = int(s0/100.) for pos in np.logspace(0.01,1,10): pos = int(round((pos-0.5)*s0/10.)) cv2.line(arr, (0,pos), (s0,pos), color=col, thickness=t, lineType=cv2.LI...
make line pattern
entailment