INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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 minMatches ( int ): Minimum of mating points found in both this and the re...
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...
calculate the standard deviation of all fitted images averaged to a grid
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...
fit perspective and size of the input image to the reference image
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...
Create a bounding box around the object within an image
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 ...
Remove vertical lines in boolean array if linelength > = min_line_length
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 ...
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 center x cy - imag...
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...
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 ]
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) *...
returns an image average works on many also unloaded images minimises RAM usage
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...
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 [ grid ] to [ shape ] resolution
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...
Poisson function a - > height of the curve s peak b - > position of the center of the peak c - > standard deviation d - > offset
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 * ((...
angle [ deg ]
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...
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 to exposure time e. g. duration = 2 ...
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...
a - > height of the curve s peak b - > position of the center of the peak c - > standard deviation or Gaussian RMS width d - > offset
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
TODO
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...
dtype = noUint uint8 float float...
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...
img - background flat field ste corrected image roi - [ ( x1 y1 )... ( x4 y4 ) ] - boundaries where points are
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...
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 find until ...
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...
Stitch 2 images vertically together. Smooth the overlap area of both images with a linear fade from img1 to img2
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 ...
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 [ power ] - > distance ...
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...
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 float
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 ...
same as scipy. ndimage. convolve but is only executed on mask == True... which should speed up everything
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) ...
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 )
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...
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
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...
return an array with contains the closest distance to the next positive value given in arr within a given kernel size
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
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 the distance of nei...
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...
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 positions of the region growth steps using this instead of looking for th...
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...
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: ------------- max_n_contours - > maximum number of possible ...
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 the cumulative density function of a given array or its intensity at a given position ( 0 - 1 )
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...
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: sub array Example: >>> a = np. array ( [[[ 0 1 ] [ 1...
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 slice: first dimension slice: 1st dimension
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: ...
Same as subCell2DSlices but returning coordinates Example: g = subCell2DCoords ( arr shape ) for x y in g: plt. plot ( x y )
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...
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 mx is a 2d array containing all cell maxima
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 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 fn -- > f - n...
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...
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
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...
sensorSize_mm - ( width height ) [ mm ] Physical size of the sensor
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...
add corner points directly instead of extracting them from image points = ( ( 0 1 ) (... )... ) [ x y ]
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: ...
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
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...
add images using a continous stream - stop when max number of images is reached
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 one chessboard image for detection lens distortion
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) ...
get the distortion coeffs in a formated string
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
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
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...
write the distortion coeffs to file saveOpts -- > Whether so save calibration options ( and not just results )
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...
read the distortion coeffs from file
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...
points -- > list of ( x y ) coordinates
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: ...
remove lens distortion from given image
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, ...
opposite of correct
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, ...
value positions based on http:// docs. opencv. org/ modules/ imgproc/ doc/ geometric_transformations. html#cv. InitUndistortRectifyMap
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...
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
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...
takes a binary image ( usually a mask ) and returns the edges of the object inside
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
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. Args: img1: An openCV image...
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...
The pattern comparator need images to be 8 bit - > find the range of the signal and scale the image
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...
Find homography of the image through pattern comparison with the base image
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...
make circle array
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 line pattern
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
def patStarLines(s0): '''make line pattern''' arr = np.zeros((s0,s0), dtype=np.uint8) col = 255 t = int(s0/100.) for pos in np.linspace(0,np.pi/2,15): p0 = int(round(np.sin(pos)*s0*2)) p1 = int(round(np.cos(pos)*s0*2)) cv2.line(arr,(0,0),(p0,p1), co...
make line pattern
def patSiemensStar(s0, n=72, vhigh=255, vlow=0, antiasing=False): '''make line pattern''' arr = np.full((s0,s0),vlow, dtype=np.uint8) c = int(round(s0/2.)) s = 2*np.pi/(2*n) step = 0 for i in range(2*n): p0 = round(c+np.sin(step)*2*s0) p1 = round(c+np.cos(step)*2*s0) ...
make text pattern
def patText(s0): '''make text pattern''' arr = np.zeros((s0,s0), dtype=np.uint8) s = int(round(s0/100.)) p1 = 0 pp1 = int(round(s0/10.)) for pos0 in np.linspace(0,s0,10): cv2.putText(arr, 'helloworld', (p1,int(round(pos0))), cv2.FONT_HERSHEY_COMPLEX_SMALL, fo...
img - boolean array remove all pixels that have no neighbour
def removeSinglePixels(img): ''' img - boolean array remove all pixels that have no neighbour ''' gx = img.shape[0] gy = img.shape[1] for i in range(gx): for j in range(gy): if img[i, j]: found_neighbour = False for ii in...
same as interpolate2dStructuredIDW but calculation distance to neighbour using polar coordinates fr fphi -- > weight factors for radian and radius differences cx cy - > polar center of the array e. g. middle - > ( sx// 2 + 1 sy// 2 + 1 )
def interpolateCircular2dStructuredIDW(grid, mask, kernel=15, power=2, fr=1, fphi=1, cx=0, cy=0): ''' same as interpolate2dStructuredIDW but calculation distance to neighbour using polar coordinates fr, fphi --> weight factors for radian and radius differences c...
####### usefull if large empty areas need to be filled
def interpolate2dStructuredCrossAvg(grid, mask, kernel=15, power=2): ''' ####### usefull if large empty areas need to be filled ''' vals = np.empty(shape=4, dtype=grid.dtype) dist = np.empty(shape=4, dtype=np.uint16) weights = np.empty(shape=4, dtype=np.float32) valid = np.em...
return all positions around central point ( 0 0 ) for a given kernel size positions grow from smallest to biggest distances returns [ positions ] and [ distances ] from central cell
def growPositions(ksize): ''' return all positions around central point (0,0) for a given kernel size positions grow from smallest to biggest distances returns [positions] and [distances] from central cell ''' i = ksize*2+1 kk = np.ones( (i, i), dtype=bool) x,y...
Convert QImage to numpy. ndarray. The dtype defaults to uint8 for QImage. Format_Indexed8 or bgra_dtype ( i. e. a record array ) for 32bit color images. You can pass a different dtype to use or array to get a 3D uint8 array for color images.
def qImageToArray(qimage, dtype = 'array'): """Convert QImage to numpy.ndarray. The dtype defaults to uint8 for QImage.Format_Indexed8 or `bgra_dtype` (i.e. a record array) for 32bit color images. You can pass a different dtype to use, or 'array' to get a 3D uint8 array for color images.""" ...
applies gaussian_filter on input array but allowing variable ksize in y stdyrange ( int ) - > maximum ksize - ksizes will increase from 0 to given value stdyrange ( tuple list ) - > minimum and maximum size as ( mn mx ) stdyrange ( np. array ) - > all different ksizes in y
def varYSizeGaussianFilter(arr, stdyrange, stdx=0, modex='wrap', modey='reflect'): ''' applies gaussian_filter on input array but allowing variable ksize in y stdyrange(int) -> maximum ksize - ksizes will increase from 0 to given value stdyrange(tuple,list) -> ...
2d Gaussian to be used in numba code
def numbaGaussian2d(psf, sy, sx): ''' 2d Gaussian to be used in numba code ''' ps0, ps1 = psf.shape c0,c1 = ps0//2, ps1//2 ssx = 2*sx**2 ssy = 2*sy**2 for i in range(ps0): for j in range(ps1): psf[i,j]=exp( -( (i-c0)**2/ssy +(j-c...
estimate background level through finding the most homogeneous area and take its average min_size - relative size of the examined area
def estimateBackgroundLevel(img, image_is_artefact_free=False, min_rel_size=0.05, max_abs_size=11): ''' estimate background level through finding the most homogeneous area and take its average min_size - relative size of the examined area ''' s0,s1 = i...
returns angular dependent EL emissivity of a PV module calculated of nanmedian ( persp - corrected EL module/ reference module ) published in K. Bedrich: Quantitative Electroluminescence Measurement on PV devices PhD Thesis 2017
def EL_Si_module(): ''' returns angular dependent EL emissivity of a PV module calculated of nanmedian(persp-corrected EL module/reference module) published in K. Bedrich: Quantitative Electroluminescence Measurement on PV devices PhD Thesis, 2017 ''' arr = np...
reflected temperature for 250DEG Glass published in IEC 62446 - 3 TS: Photovoltaic ( PV ) systems - Requirements for testing documentation and maintenance - Part 3: Outdoor infrared thermography of photovoltaic modules and plants p Page 12
def TG_glass(): ''' reflected temperature for 250DEG Glass published in IEC 62446-3 TS: Photovoltaic (PV) systems - Requirements for testing, documentation and maintenance - Part 3: Outdoor infrared thermography of photovoltaic modules and plants p Page 12 ''' vals = np.arra...
Extract pixel sensitivity from a set of homogeneously illuminated images This method is detailed in Section 5 of: --- K. Bedrich M. Bokalic et al.: ELECTROLUMINESCENCE IMAGING OF PV DEVICES: ADVANCED FLAT FIELD CALIBRATION 2017 ---
def sensitivity(imgs, bg=None): ''' Extract pixel sensitivity from a set of homogeneously illuminated images This method is detailed in Section 5 of: --- K.Bedrich, M.Bokalic et al.: ELECTROLUMINESCENCE IMAGING OF PV DEVICES: ADVANCED FLAT FIELD CALIBRATION,2017 --- ''' ...
solves the Navier - Stokes equation for incompressible flow one a regular 2d grid u v p -- > initial velocity ( u v ) and pressure ( p ) maps dt -- > time step nt -- > number of time steps to caluclate rho nu -- > material constants nit -- > number of iteration to solve the pressure field
def navierStokes2d(u, v, p, dt, nt, rho, nu, boundaryConditionUV, boundardConditionP, nit=100): ''' solves the Navier-Stokes equation for incompressible flow one a regular 2d grid u,v,p --> initial velocity(u,v) and pressure(p) maps dt --> time s...
remap an image using velocity field
def shiftImage(u, v, t, img, interpolation=cv2.INTER_LANCZOS4): ''' remap an image using velocity field ''' ny,nx = u.shape sy, sx = np.mgrid[:float(ny):1,:float(nx):1] sx += u*t sy += v*t return cv2.remap(img.astype(np.float32), (sx).astype(np.float32), ...
adds Gaussian ( thermal ) and shot noise to [ img ] [ img ] is assumed to be noise free [ rShot ] - shot noise ratio relative to all noise
def addNoise(img, snr=25, rShot=0.5): ''' adds Gaussian (thermal) and shot noise to [img] [img] is assumed to be noise free [rShot] - shot noise ratio relative to all noise ''' s0, s1 = img.shape[:2] m = img.mean() if np.isnan(m): m = np.nanmean(img) assert m...
return an array of [ shape ] where every cell equals the localised maximum of the given array [ arr ] at the same ( scalled ) position
def coarseMaximum(arr, shape): ''' return an array of [shape] where every cell equals the localised maximum of the given array [arr] at the same (scalled) position ''' ss0, ss1 = shape s0, s1 = arr.shape pos0 = linspace2(0, s0, ss0, dtype=int) pos1 = linspace2(0, s1, ss1, ...
Another vignetting equation from: M. Koentges M. Siebert and D. Hinken Quantitative analysis of PV - modules by electroluminescence images for quality control 2009 f -- > Focal length D -- > Diameter of the aperture BOTH D AND f NEED TO HAVE SAME UNIT [ PX mm... ] a -- > Angular aperture center - > optical center [ y x...
def angleOfView(XY, shape=None, a=None, f=None, D=None, center=None): ''' Another vignetting equation from: M. Koentges, M. Siebert, and D. Hinken, "Quantitative analysis of PV-modules by electroluminescence images for quality control" 2009 f --> Focal length D --> Diameter of the aper...
Corrected AngleOfView equation by Koentges ( via mail from 14/ 02/ 2017 ) b -- > distance between the camera and the module in m x0 -- > viewable with in the module plane of the camera in m y0 -- > viewable height in the module plane of the camera in m x y -- > pixel position [ m ] from top left
def angleOfView2(x,y, b, x0=None,y0=None): ''' Corrected AngleOfView equation by Koentges (via mail from 14/02/2017) b --> distance between the camera and the module in m x0 --> viewable with in the module plane of the camera in m y0 --> viewable height in the module plane of the camera in m ...
###TODO REDO TXT OPTIONAL: subgrid = ( [ x ] [ y ] ) -- > relative positions e. g. subgrid = ( ( 0. 3 0. 7 ) () ) -- > two subgrid lines in x - nothing in y Returns: horiz vert - > arrays of ( x y ) poly - lines if subgrid ! = None Returns: horiz vert subhoriz subvert ####### creates a regular 2d grid from given edge p...
def gridLinesFromVertices(edges, nCells, subgrid=None, dtype=float): """ ###TODO REDO TXT OPTIONAL: subgrid = ([x],[y]) --> relative positions e.g. subgrid = ( (0.3,0.7), () ) --> two subgrid lines in x - nothing in y Returns: horiz,vert -> arrays of (x,y) ...
return object resolution as [ line pairs/ mm ] where MTF = 50% see http:// www. imatest. com/ docs/ sharpness/
def MTF50(self, MTFx,MTFy): ''' return object resolution as [line pairs/mm] where MTF=50% see http://www.imatest.com/docs/sharpness/ ''' if self.mtf_x is None: self.MTF() f = UnivariateSpline(self.mtf_x, self.mtf_y-0.5) r...
px_per_mm = cam_resolution/ image_size
def MTF(self, px_per_mm): ''' px_per_mm = cam_resolution / image_size ''' res = 100 #numeric resolution r = 4 #range +-r*std #size of 1 px: px_size = 1 / px_per_mm #standard deviation of the point-spread-function (PSF) as normal...
return the intensity based uncertainty due to the unsharpness of the image as standard deviation method = [ convolve unsupervised_wiener ] latter one also returns the reconstructed image ( deconvolution )
def uncertaintyMap(self, psf, method='convolve', fitParams=None): ''' return the intensity based uncertainty due to the unsharpness of the image as standard deviation method = ['convolve' , 'unsupervised_wiener'] latter one also returns the reconstructe...
get the standard deviation from the PSF is evaluated as 2d Gaussian
def stdDev(self): ''' get the standard deviation from the PSF is evaluated as 2d Gaussian ''' if self._corrPsf is None: self.psf() p = self._corrPsf.copy() mn = p.min() p[p<0.05*p.max()] = mn p-=mn p/=p.sum() ...
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 ]
def interpolate2dStructuredIDW(grid, mask, kernel=15, power=2, fx=1, fy=1): ''' 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] ''' weights = ...
( Electroluminescence ) signal is not stable over time especially next to cracks. This function takes a set of images and returns parameters needed to transform uncertainty to other exposure times using [ adjustUncertToExposureTime ] return [ signal uncertainty ] obtained from linear fit to [ imgs ] [ average event len...
def temporalSignalStability(imgs, times, down_scale_factor=1): ''' (Electroluminescence) signal is not stable over time especially next to cracks. This function takes a set of images and returns parameters, needed to transform uncertainty to other exposure times using [adjustUncer...
[ images ] -- > list of images containing small bright spots generated by the same device images at different positions within image plane depending on the calibrated waveband the device can be a LCD display or PV 1 - cell mini module This method is referred as Method B in --- K. Bedrich M. Bokalic et al.: ELECTROLUMIN...
def vignettingFromSpotAverage( images, bgImages=None, averageSpot=True, thresh=None): ''' [images] --> list of images containing small bright spots generated by the same device images at different positions within image plane depending on the calibrat...
Simulates a lens calibration using synthetic images * images are rendered under the given HEIGHT resolution * noise and smoothing is applied * perspective and position errors are applied * images are deformed using the given CAMERA_PARAM * the detected camera parameters are used to calculate the error to the given ones...
def simulateSytematicError(N_SAMPLES=5, N_IMAGES=10, SHOW_DETECTED_PATTERN=True, # GRAYSCALE=False, HEIGHT=500, PLOT_RESULTS=True, PLOT_ERROR_ARRAY=True, CAMERA_PARAM=None, PERSPECTIVE=True, ROTATION=True, R...
creates plots showing both found GAUSSIAN peaks the histogram a smoothed histogram from all images within [ imgDir ] posExTime - position range of the exposure time in the image name e. g.: img_30s. jpg - > ( 4 5 ) outDir - dirname to save the output images show_legend - True/ False show_plots - display the result on s...
def plotSet(imgDir, posExTime, outDir, show_legend, show_plots, save_to_file, ftype): ''' creates plots showing both found GAUSSIAN peaks, the histogram, a smoothed histogram from all images within [imgDir] posExTime - position range of the exposure time in the image name e.g.: img_30...
Average multiple images of a homogeneous device imaged directly in front the camera lens. if [ bg_imgs ] are not given background level is extracted from 1% of the cumulative intensity distribution of the averaged [ imgs ] This measurement method is referred as Method A in --- K. Bedrich M. Bokalic et al.: ELECTROLUMIN...
def flatFieldFromCloseDistance(imgs, bg_imgs=None): ''' Average multiple images of a homogeneous device imaged directly in front the camera lens. if [bg_imgs] are not given, background level is extracted from 1% of the cumulative intensity distribution of the averaged [imgs] ...
Same as [ flatFieldFromCloseDistance ]. Differences are:... single - time - effect removal included... returns the standard deviation of the image average [ calcStd = True ] Optional: ----------- calcStd - > set to True to also return the standard deviation nlf - > noise level function ( callable ) nstd - > artefact ne...
def flatFieldFromCloseDistance2(images, bgImages=None, calcStd=False, nlf=None, nstd=6): ''' Same as [flatFieldFromCloseDistance]. Differences are: ... single-time-effect removal included ... returns the standard deviation of the image average [calcStd=True] O...
signal - to - noise ratio ( SNR ) as mean ( images )/ std ( images ) as defined in Hinken et. al. 2011 ( DOI: 10. 1063/ 1. 3541766 ) works on unloaded images no memory overload if too many images are given
def SNR_hinken(imgs, bg=0, roi=None): ''' signal-to-noise ratio (SNR) as mean(images) / std(images) as defined in Hinken et.al. 2011 (DOI: 10.1063/1.3541766) works on unloaded images no memory overload if too many images are given ''' mean = None M = len(imgs) if bg is...
Transform at maximum 8 bool layers -- > 2d arrays dtype = ( bool int ) to one 8bit image
def boolMasksToImage(masks): ''' Transform at maximum 8 bool layers --> 2d arrays, dtype=(bool,int) to one 8bit image ''' assert len(masks) <= 8, 'can only transform up to 8 masks into image' masks = np.asarray(masks, dtype=np.uint8) assert masks.ndim == 3, 'layers need to be stack of...
inverse of [ boolMasksToImage ]
def imageToBoolMasks(arr): '''inverse of [boolMasksToImage]''' assert arr.dtype == np.uint8, 'image needs to be dtype=uint8' masks = np.unpackbits(arr).reshape(*arr.shape, 8) return np.swapaxes(masks, 2, 0)
simple and better alg. than below in_plane - > whether object has no tilt but only rotation and translation
def calcAspectRatioFromCorners(corners, in_plane=False): ''' simple and better alg. than below in_plane -> whether object has no tilt, but only rotation and translation ''' q = corners l0 = [q[0, 0], q[0, 1], q[1, 0], q[1, 1]] l1 = [q[0, 0], q[0, 1], q[-1, 0], q[-1, 1]] l2 = ...
Extends cv2. putText with [ alpha ] argument
def putTextAlpha(img, text, alpha, org, fontFace, fontScale, color, thickness): # , lineType=None ''' Extends cv2.putText with [alpha] argument ''' x, y = cv2.getTextSize(text, fontFace, fontScale, thickness)[0] ox, oy = org imgcut = img...
for bigger ksizes it if often faster to resize an image rather than blur it...
def fastMean(img, f=10, inplace=False): ''' for bigger ksizes it if often faster to resize an image rather than blur it... ''' s0,s1 = img.shape[:2] ss0 = int(round(s0/f)) ss1 = int(round(s1/f)) small = cv2.resize(img,(ss1,ss0), interpolation=cv2.INTER_AREA) #bigger ...
Build a file path from * paths * and return the contents.
def read(*paths): """Build a file path from *paths* and return the contents.""" try: f_name = os.path.join(*paths) with open(f_name, 'r') as f: return f.read() except IOError: print('%s not existing ... skipping' % f_name) return ''
average background images with same exposure time
def averageSameExpTimes(imgs_path): ''' average background images with same exposure time ''' firsts = imgs_path[:2] imgs = imgs_path[2:] for n, i in enumerate(firsts): firsts[n] = np.asfarray(imread(i)) d = DarkCurrentMap(firsts) for i in imgs: i = imread(i) ...
returns offset ascent of image ( expTime ) = offset + ascent * expTime
def getLinearityFunction(expTimes, imgs, mxIntensity=65535, min_ascent=0.001, ): ''' returns offset, ascent of image(expTime) = offset + ascent*expTime ''' # TODO: calculate [min_ascent] from noise function # instead of having it as variable ascent, offset...
return image paths sorted for same exposure time
def sortForSameExpTime(expTimes, img_paths): # , excludeSingleImg=True): ''' return image paths sorted for same exposure time ''' d = {} for e, i in zip(expTimes, img_paths): if e not in d: d[e] = [] d[e].append(i) # for key in list(d.keys()): # if ...
return exposure times image averages for each exposure time
def getDarkCurrentAverages(exposuretimes, imgs): ''' return exposure times, image averages for each exposure time ''' x, imgs_p = sortForSameExpTime(exposuretimes, imgs) s0, s1 = imgs[0].shape imgs = np.empty(shape=(len(x), s0, s1), dtype=imgs[0].dtype) for i, i...
get dark current function from given images and exposure times
def getDarkCurrentFunction(exposuretimes, imgs, **kwargs): ''' get dark current function from given images and exposure times ''' exposuretimes, imgs = getDarkCurrentAverages(exposuretimes, imgs) offs, ascent, rmse = getLinearityFunction(exposuretimes, imgs, **kwargs) return offs, ascent, ...
return a sub image aligned along given line
def alignImageAlongLine(img, line, height=15, length=None, zoom=1, fast=False, borderValue=0): ''' return a sub image aligned along given line @param img - numpy.2darray input image to get subimage from @param line - list of 2 points [x0,y0,x1,y1]) @param height - he...
calculates the estimated standard deviation map from the changes of neighbouring pixels from a center pixel within a point spread function defined by a std. dev. in x and y taken from the ( sx sy ) maps sx sy - > either 2d array of same shape as [ image ] of single values
def positionToIntensityUncertainty(image, sx, sy, kernelSize=None): ''' calculates the estimated standard deviation map from the changes of neighbouring pixels from a center pixel within a point spread function defined by a std.dev. in x and y taken from the (sx, sy) maps sx,sy -> either 2d ...