output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
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...
Implement a Python 3 function for reading the distortion coeffs from file
As a Python code composer, you craft elegant and concise scripts.
Returns a list of undistorted points.
Can you generate a brief explanation for the following Python 3 code def undistortPoints(self, points, keepSize=False): ''' points --> list of (x,y) coordinates ''' s = self.img.shape cam = self.coeffs['cameraMatrix'] d = self.coeffs['distortionCoeffs'] p...
As a Python code composer, you craft elegant and concise scripts.
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, ...
Write a Python 3 script for removing lens distortion from given image keepSize = True keepSize = False borderValue = 0
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a tuple of the two elements of the camera matrix and the two elements of the camera matrix.
Can you generate a brief explanation for the following Python 3 code def getCameraParams(self): ''' value positions based on http://docs.opencv.org/modules/imgproc/doc/geometric_transformations.html#cv.InitUndistortRectifyMap ''' c = self.coeffs['cameraMatrix'] fx ...
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Create a Python 3 function for returning a list of standard uncertainties for the image and the image sharpness.
As a python code expert, you are capable of creating scripts from specifications.
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
Can you create a Python 3 function that takes a binary image and returns the edges of the object inside .
As a Python code analyst, you investigate and solve complex coding mysteries
Draws lines between two matching keypoints.
Given the following Python 3 function, write the documentation def draw_matches(img1, kp1, img2, kp2, matches, color=None, thickness=2, r=15): # We're drawing them side by side. Get dimensions accordingly. # Handle both color and grayscale images. if len(img1.shape) == 3: new_shape = (max(img1....
You are a Python code architect, reviewing and designing scalable and efficient code
Find homography of the image through pattern
Given the following Python 3 function, write the documentation 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 ...
As a Python code analyst, you investigate and solve complex coding mysteries
make a circle array
Here you have a function in Python 3, explain what it does 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.LI...
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Implement a function in Python 3 to make line pattern for the given number of times
As a Python code composer, you craft elegant and concise scripts.
remove all pixels that have no neighbour
Here you have a function in Python 3, explain what it does 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]: ...
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Create a Python 3 function for interpolating a 2D array into a 2D array with a cross average.
You are a Python code generator, capable of creating scripts from specifications.
grows all positions around central point
Explain what the following Python 3 code does 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 ...
You are a Python code generator, capable of creating scripts from specifications.
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.""" ...
Create a Python 3 function for converting a QImage to a numpy array.
As a Python code analyst, you investigate and solve complex coding mysteries
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) -> ...
Write a Python 3 function that can create a new array with variable ksize in y
You are a Python code generator, capable of creating scripts from specifications.
Returns a 2d Gaussian that is used in numba code
Given the following Python 3 function, write the documentation 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): ps...
As a Python code analyst, you investigate and solve complex coding mysteries
estimate background level through finding the most homogeneous area and take its average
Given the following Python 3 function, write the documentation 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...
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Write a Python 3 script for returning the angular dependent EL emissivity of a PV module
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Write a Python 3 function that can reflect 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
As a Python code translator, you convert algorithms and pseudocode into Python.
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 --- ''' ...
How would you implement a function in Python 3 that returns the sensitivity of the homogeneously illuminated images.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a new 2d grid with the same initial velocity and pressure.
How would you explain what the following Python 3 function does 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 --> ini...
As a python code expert, you are capable of creating scripts from specifications.
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...
Implement a function in Python 3 to add noise to the image and return the new image
As a Python code composer, you craft elegant and concise scripts.
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, ...
Create a Python 3 function for returning an array of the given shape coarse - maximum of the given array.
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Can you implement a function in Python 3 that returns the angle of view of the aperture given the specified parameters
As a Python code analyst, you investigate and solve complex coding mysteries
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 ...
Create a Python 3 function to return the angle of view between two camera modules.
As a Python code translator, you convert algorithms and pseudocode into Python.
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) ...
Can you implement a function in Python 3 that returns a 2d grid of nCells lines from a list of edges.
As a python code expert, you are capable of creating scripts from specifications.
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...
Write a Python 3 script for returning the most recent object resolution as [ line pairs / mm ] where MTF = 50% of the given time frame.
As a python code expert, you are capable of creating scripts from specifications.
Returns the MTF and the MTF_y values for the most recent image.
How would you explain what the following Python 3 function does 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 ...
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Implement a function in Python 3 to return the intensity based uncertainty due to the unsharpness of the image as standard deviation
You are a Python code generator, capable of creating scripts from specifications.
get the standard deviation of the current time - domain entry from the PSF is evaluated as 2d Gaussian self. _corrPsf is None
Can you generate the documentation for the following Python 3 function 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() ...
As a Python code translator, you convert algorithms and pseudocode into Python.
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 = ...
Can you write a function in Python 3 where it interpolates all values in a 2D structured IDW grid with inverse distance weighted interpolation of all values in a 2D structured IDW grid
As a Python code analyst, you investigate and solve complex coding mysteries
This function takes a set of images and returns a set of time - dependent Electrouminescence signal parameters needed to transform the uncertainty of each image to other exposure times using adjustUncertToExposureTime.
Make a summary of the following Python 3 code 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 ...
As a python code expert, you are capable of creating scripts from specifications.
Returns a new image mask containing the small bright spots generated by the same AttributeNames image mask containing valid positions and background images that are at different positions within the same AttributeNames image mask containing valid positions.
Can you generate a brief explanation for the following Python 3 code def vignettingFromSpotAverage( images, bgImages=None, averageSpot=True, thresh=None): ''' [images] --> list of images containing small bright spots generated by the same device images at differen...
As a python code expert, you are capable of creating scripts from specifications.
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...
Write a Python 3 script for simulating a synthetic image using the given parameters and returns a new list of synthetic images.
As a python code expert, you are capable of creating scripts from specifications.
Plots a set of GAUSSIAN peaks and a smoothed histogram of all images within the image dir.
How would you explain what the following Python 3 function does 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 - po...
You are a Python code generator, capable of creating scripts from specifications.
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] ...
How would you implement a function in Python 3 that averages 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 ...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the flat field from close distance images.
Explain what the following Python 3 code does def flatFieldFromCloseDistance2(images, bgImages=None, calcStd=False, nlf=None, nstd=6): ''' Same as [flatFieldFromCloseDistance]. Differences are: ... single-time-effect removal included ... returns the standard deviatio...
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Can you write a function in Python 3 where it calculates the signal - to - noise ratio of the given images.
You are a Python code generator, capable of creating scripts from specifications.
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...
Implement a Python 3 function for transforming at maximum 8 bool layers --> 2d arrays dtype = bool int array
You are a Python code architect, reviewing and designing scalable and efficient code
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)
How would you code a function in Python 3 to inverse of [ boolMasksToImage ]
As a python code expert, you are capable of creating scripts from specifications.
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 = ...
Create a Python 3 function to calculate the aspect ratio of a new object from a list of corners.
You are a Python code generator, capable of creating scripts from specifications.
Adds text to image with alpha color.
How would you explain what the following Python 3 function does def putTextAlpha(img, text, alpha, org, fontFace, fontScale, color, thickness): # , lineType=None ''' Extends cv2.putText with [alpha] argument ''' x, y = cv2.getTextSize(text, fontFace, ...
As a Python code translator, you convert algorithms and pseudocode into Python.
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 ''
Can you write a function in Python 3 where it builds a file path from the given list of paths and return the contents.
As a Python code translator, you convert algorithms and pseudocode into Python.
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) ...
How would you code a function in Python 3 to return a DarkCurrentMap that has the average background images with same exposure time.
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Can you create a Python 3 function that returns the linear interpolation function for the given set of images.
As a python code expert, you are capable of creating scripts from specifications.
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 ...
Write a Python 3 script to sort image paths for same exposure time
As a python code expert, you are capable of creating scripts from specifications.
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...
Can you create a Python 3 function that returns the exposure times and image averages for each exposure time returns exposure times and image averages for each exposure time returns exposure times imgs averages for each exposure time imgs_p returns imgs_p
As a Python code analyst, you investigate and solve complex coding mysteries
get dark current function from given images and exposure times
Here you have a function in Python 3, explain what it does def getDarkCurrentFunction(exposuretimes, imgs, **kwargs): ''' get dark current function from given images and exposure times ''' exposuretimes, imgs = getDarkCurrentAverages(exposuretimes, imgs) offs, ascent, rmse = getLinearityFunctio...
As a Python code composer, you craft elegant and concise scripts.
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...
Implement a Python 3 function for returning a subimage aligned along given line.
You are a Python code generator, capable of creating scripts from specifications.
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 ...
Can you write a function in Python 3 where it returns the estimated standard deviation map from the changes of neighbouring pixels from a center pixel within a point spread function within a center pixel within a point spread function within a center pixel within a point spread function within a center pixel within a p...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a new image with the given number of coarsening components.
Explain what the following Python 3 code does def _coarsenImage(image, f): ''' seems to be a more precise (but slower) way to down-scale an image ''' from skimage.morphology import square from skimage.filters import rank from skimage.transform._warps import rescale selem = square...
You are a Python code analyst, evaluating scripts for potential improvements.
Like positionToIntensityUncertainty but calculated average uncertainty for an area [ y0 x0 x1
Given the following Python 3 function, write the documentation def positionToIntensityUncertaintyForPxGroup(image, std, y0, y1, x0, x1): ''' like positionToIntensityUncertainty but calculated average uncertainty for an area [y0:y1,x0:x1] ''' fy, fx = y1 - y0, x1 - x0 if fy != fx: ...
You are a Python code architect, reviewing and designing scalable and efficient code
same as scipy. filters. maximum_filter but working excluding nan
How would you explain what the following Python 3 function does def nan_maximum_filter(arr, ksize): ''' same as scipy.filters.maximum_filter but working excluding nans ''' out = np.empty_like(arr) _calc(arr, out, ksize//2) return out
You are a Python code analyst, evaluating scripts for potential improvements.
fast filter for large kernel sizes
Make a summary of the following Python 3 code def fastFilter(arr, ksize=30, every=None, resize=True, fn='median', interpolation=cv2.INTER_LANCZOS4, smoothksize=0, borderMode=cv2.BORDER_REFLECT): ''' fn['nanmean', 'mean', 'nanmedian', 'median'] ...
As a Python code analyst, you investigate and solve complex coding mysteries
Reads the EL images created by the RELTRON EL Software and returns a list of tuples each containing the current time and the number of times in the image.
Here you have a function in Python 3, explain what it does def elbin(filename): ''' Read EL images (*.elbin) created by the RELTRON EL Software http://www.reltron.com/Products/Solar.html ''' # arrs = [] labels = [] # These are all exposure times [s] to be selectable: TIMES = (0...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the 2D gaussian distribution of a vector x y
Given the following Python 3 function, write the documentation def gaussian2d(xy, sx, sy, mx=0, my=0, rho=0, amp=1, offs=0): ''' see http://en.wikipedia.org/wiki/Multivariate_normal_distribution # probability density function of a vector [x,y] sx,sy -> sigma (standard deviation) mx,my: mue (mea...
You are a Python code generator, capable of creating scripts from specifications.
fit perspective and size of the input image to the base image
Given the following Python 3 function, write the documentation def fitImg(self, img_rgb): ''' fit perspective and size of the input image to the base image ''' H = self.pattern.findHomography(img_rgb)[0] H_inv = self.pattern.invertHomography(H) s = self.img_orig.sha...
You are a Python code generator, capable of creating scripts from specifications.
scale the img cutting x percent of top and bottom part of histogram
Make a summary of the following Python 3 code def scaleSignalCut(img, ratio, nbins=100): ''' scaling img cutting x percent of top and bottom part of histogram ''' start, stop = scaleSignalCutParams(img, ratio, nbins) img = img - start img /= (stop - start) return img
You are a Python code analyst, evaluating scripts for potential improvements.
scale the image between... and 1 - 3std
Given the following Python 3 function, write the documentation def scaleSignal(img, fitParams=None, backgroundToZero=False, reference=None): ''' scale the image between... backgroundToZero=True -> 0 (average background) and 1 (maximum signal) backgroundToZero=False -> signal+-3std...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the minimum average maximum of the background peak peak
Make a summary of the following Python 3 code def getBackgroundRange(fitParams): ''' return minimum, average, maximum of the background peak ''' smn, _, _ = getSignalParameters(fitParams) bg = fitParams[0] _, avg, std = bg bgmn = max(0, avg - 3 * std) if avg + 4 * std < smn: ...
As a python code expert, you are capable of creating scripts from specifications.
def hasBackground(fitParams): ''' compare the height of putative bg and signal peak if ratio if too height assume there is no background ''' signal = getSignalPeak(fitParams) bg = getBackgroundPeak(fitParams) if signal == bg: return False r = signal[0] / bg[0] if r ...
Can you write a function in Python 3 where it checks if there is background
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the minimum position between signal and background peak.
Given the following Python 3 function, write the documentation def signalMinimum2(img, bins=None): ''' minimum position between signal and background peak ''' f = FitHistogramPeaks(img, bins=bins) i = signalPeakIndex(f.fitParams) spos = f.fitParams[i][1] # spos = getSignalPeak(f.fitPa...
As a python code expert, you are capable of creating scripts from specifications.
get minimum signal peak
Can you generate the documentation for the following Python 3 function def signalMinimum(img, fitParams=None, n_std=3): ''' intersection between signal and background peak ''' if fitParams is None: fitParams = FitHistogramPeaks(img).fitParams assert len(fitParams) > 1, 'need 2 peaks so...
You are a Python code generator, capable of creating scripts from specifications.
def getSignalParameters(fitParams, n_std=3): ''' return minimum, average, maximum of the signal peak ''' signal = getSignalPeak(fitParams) mx = signal[1] + n_std * signal[2] mn = signal[1] - n_std * signal[2] if mn < fitParams[0][1]: mn = fitParams[0][1] # set to bg ret...
Write a Python 3 function for returning the minimum average maximum of the signal peak and the signal peak peak.
As a Python code translator, you convert algorithms and pseudocode into Python.
Equalize the histogram of an image
Given the following Python 3 function, write the documentation def equalizeImage(img, save_path=None, name_additive='_eqHist'): ''' Equalize the histogram (contrast) of an image works with RGB/multi-channel images and flat-arrays @param img - image_path or np.array @param save_path if g...
As a Python code composer, you craft elegant and concise scripts.
Returns the localized maximum of a given 2d array
Here you have a function in Python 3, explain what it does def localizedMaximum(img, thresh=0, min_increase=0, max_length=0, dtype=bool): ''' Returns the local maximum of a given 2d array thresh -> if given, ignore all values below that value max_length -> limit length between value has to var...
As a Python code composer, you craft elegant and concise scripts.
def setReference(self, ref): ''' ref ... either quad, grid, homography or reference image quad --> list of four image points(x,y) marking the edges of the quad to correct homography --> h. matrix to correct perspective distortion referenceImage --> image o...
How would you code a function in Python 3 to set the reference of the object
As a python code expert, you are capable of creating scripts from specifications.
def distort(self, img, rotX=0, rotY=0, quad=None): ''' Apply perspective distortion ion self.img angles are in DEG and need to be positive to fit into image ''' self.img = imread(img) # fit old image to self.quad: corr = self.correct(self.img) ...
Create a Python 3 function to apply perspective distortion ion to image and return a new image.
You are a Python code generator, capable of creating scripts from specifications.
Returns a new image with the new image and the new border.
Given the following Python 3 function, write the documentation def correctGrid(self, img, grid): ''' grid -> array of polylines=((p0x,p0y),(p1x,p1y),,,) ''' self.img = imread(img) h = self.homography # TODO: cleanup only needed to get newBorder attr. if self.op...
You are a Python code generator, capable of creating scripts from specifications.
def correct(self, img): ''' ...from perspective distortion: --> perspective transformation --> apply tilt factor (view factor) correction ''' print("CORRECT PERSPECTIVE ...") self.img = imread(img) if not self._homography_is_fixed: ...
Write a Python 3 script to correct the image using the perspective distortion transformation and tilt factor.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the camera position in world coordinates using self. rvec and self. tvec
Explain what the following Python 3 code does def camera_position(self, pose=None): ''' returns camera position in world coordinates using self.rvec and self.tvec from http://stackoverflow.com/questions/14515200/python-opencv-solvepnp-yields-wrong-translation-vector ''' if p...
You are a Python code architect, reviewing and designing scalable and efficient code
calculate view factor between one small and one finite surface
Can you generate a brief explanation for the following Python 3 code def viewAngle(self, **kwargs): ''' calculate view factor between one small and one finite surface vf =1/pi * integral(cos(beta1)*cos(beta2)/s**2) * dA according to VDI heatatlas 2010 p961 ''' v0 = ...
As a Python code composer, you craft elegant and concise scripts.
def foreground(self, quad=None): '''return foreground (quad) mask''' fg = np.zeros(shape=self._newBorders[::-1], dtype=np.uint8) if quad is None: quad = self.quad else: quad = quad.astype(np.int32) cv2.fillConvexPoly(fg, quad, 1) return fg....
Write a Python 3 function that can return foreground (quad) mask
As a Python code composer, you craft elegant and concise scripts.
get tilt factor from inverse distance law
Explain what the following Python 3 code does def tiltFactor(self, midpointdepth=None, printAvAngle=False): ''' get tilt factor from inverse distance law https://en.wikipedia.org/wiki/Inverse-square_law ''' # TODO: can also be only def. with FOV, rot, til...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a new image with the standard uncertainty.
Make a summary of the following Python 3 code def standardUncertainties(self, focal_Length_mm, f_number, midpointdepth=1000, focusAtYX=None, # sigma_best_focus=0, # quad_pos_err=0, shape=None, ...
You are a Python code architect, reviewing and designing scalable and efficient code
def _poseFromQuad(self, quad=None): ''' estimate the pose of the object plane using quad setting: self.rvec -> rotation vector self.tvec -> translation vector ''' if quad is None: quad = self.quad if quad.ndim == 3: qu...
Write a Python 3 function for estimating the pose of the object plane using quad
As a python code expert, you are capable of creating scripts from specifications.
def drawQuad(self, img=None, quad=None, thickness=30): ''' Draw the quad into given img ''' if img is None: img = self.img if quad is None: quad = self.quad q = np.int32(quad) c = int(img.max()) cv2.line(img, tuple(q[0]),...
Write a Python 3 script to draw the quad into given img
You are a Python code architect, reviewing and designing scalable and efficient code
def draw3dCoordAxis(self, img=None, thickness=8): ''' draw the 3d coordinate axes into given image if image == False: create an empty image ''' if img is None: img = self.img elif img is False: img = np.zeros(shape=self.img.sha...
How would you implement a function in Python 3 that draws the 3d coordinate axes into a given image
You are a Python code analyst, evaluating scripts for potential improvements.
def _calcQuadSize(corners, aspectRatio): ''' return the size of a rectangle in perspective distortion in [px] DEBUG: PUT THAT BACK IN??:: if aspectRatio is not given is will be determined ''' if aspectRatio > 1: # x is bigger -> reduce y x_length =...
Write a Python 3 function that can calculate the size of a rectangle in perspective distortion in [ px ].
You are a Python code generator, capable of creating scripts from specifications.
Returns a 2d array of polar coordinates using opencv. remap
Given the following Python 3 function, write the documentation def linearToPolar(img, center=None, final_radius=None, initial_radius=None, phase_width=None, interpolation=cv2.INTER_AREA, maps=None, borderValue=0, borderMode=c...
As a python code expert, you are capable of creating scripts from specifications.
Returns a 2d array of polar coordinates with a linear interpolation
How would you explain what the following Python 3 function does def polarToLinear(img, shape=None, center=None, maps=None, interpolation=cv2.INTER_AREA, borderValue=0, borderMode=cv2.BORDER_REFLECT, **opts): ''' map a 2d polar (r, phi) polar array to a Cartesian (x,y) ar...
You are a Python code analyst, evaluating scripts for potential improvements.
Calculates the variance of Laplacian.
Make a summary of the following Python 3 code def varianceOfLaplacian(img): ''''LAPV' algorithm (Pech2000)''' lap = cv2.Laplacian(img, ddepth=-1)#cv2.cv.CV_64F) stdev = cv2.meanStdDev(lap)[1] s = stdev[0]**2 return s[0]
As a Python code analyst, you investigate and solve complex coding mysteries
def normalizedGraylevelVariance(img): ''''GLVN' algorithm (Santos97)''' mean, stdev = cv2.meanStdDev(img) s = stdev[0]**2 / mean[0] return s[0]
Can you write a function in Python 3 where it returns the normalized graylevel variance of the image.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a line plot of the image along a given line defined by [ x0 y0 x1 y1.
Can you generate a brief explanation for the following Python 3 code def linePlot(img, x0, y0, x1, y1, resolution=None, order=3): ''' returns [img] intensity values along line defined by [x0, y0, x1, y1] resolution ... number or data points to evaluate order ... interpolation precision ...
You are a Python code generator, capable of creating scripts from specifications.
calculate flatField from fitting vignetting function to averaged fit - image returns flatField average background level fitted image valid indices mask
Explain what the following Python 3 code does def flatFieldFromFunction(self): ''' calculate flatField from fitting vignetting function to averaged fit-image returns flatField, average background level, fitted image, valid indices mask ''' fitimg, mask = self._prepare() ...
You are a Python code generator, capable of creating scripts from specifications.
def flatFieldFromFit(self): ''' 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 ''' fitimg, mask = self._prepare() out = fi...
Implement a Python 3 function for calculating flatField from 2d - polaral fit filling all high gradient areas within averaged fit - image returns flatField average background level fitted image valid indices mask
You are a Python code analyst, evaluating scripts for potential improvements.
Parse a named VHDL file
How would you explain what the following Python 3 function does def parse_vhdl_file(fname): '''Parse a named VHDL file Args: fname(str): Name of file to parse Returns: Parsed objects. ''' with open(fname, 'rt') as fh: text = fh.read() return parse_vhdl(text)
You are a Python code analyst, evaluating scripts for potential improvements.
Parse a text buffer of VHDL code into a list of Parsed objects.
Make a summary of the following Python 3 code def parse_vhdl(text): '''Parse a text buffer of VHDL code Args: text(str): Source code to parse Returns: Parsed objects. ''' lex = VhdlLexer name = None kind = None saved_type = None end_param_group = False cur_package = None metacomments ...
You are a Python code architect, reviewing and designing scalable and efficient code
Generate a canonical prototype string for a sequence of subprogram objects.
Can you tell what is the following Python 3 function doing def subprogram_prototype(vo): '''Generate a canonical prototype string Args: vo (VhdlFunction, VhdlProcedure): Subprogram object Returns: Prototype string. ''' plist = '; '.join(str(p) for p in vo.parameters) if isinstance(vo, VhdlFunct...
You are a Python code generator, capable of creating scripts from specifications.
def subprogram_signature(vo, fullname=None): '''Generate a signature string Args: vo (VhdlFunction, VhdlProcedure): Subprogram object Returns: Signature string. ''' if fullname is None: fullname = vo.name if isinstance(vo, VhdlFunction): plist = ','.join(p.data_type for p in vo.paramete...
Can you implement a function in Python 3 that generates a signature string for a sequence of subprogram objects.
You are a Python code generator, capable of creating scripts from specifications.
def extract_objects_from_source(self, text, type_filter=None): '''Extract object declarations from a text buffer Args: text (str): Source code to parse type_filter (class, optional): Object class to filter results Returns: List of parsed objects. ''' objects = parse_vhdl(text) ...
Can you implement a function in Python 3 that extracts object declarations from a text buffer containing a single object.
As a Python code translator, you convert algorithms and pseudocode into Python.
Check if a type is a known array type.
How would you explain what the following Python 3 function does def is_array(self, data_type): '''Check if a type is a known array type Args: data_type (str): Name of type to check Returns: True if ``data_type`` is a known array type. ''' # Split off any brackets data_type = da...
As a Python code analyst, you investigate and solve complex coding mysteries
def load_array_types(self, fname): '''Load file of previously extracted data types Args: fname (str): Name of file to load array database from ''' type_defs = '' with open(fname, 'rt') as fh: type_defs = fh.read() try: type_defs = ast.literal_eval(type_defs) except Sy...
Can you write a function in Python 3 where it loads file of previously extracted data types
You are a Python code analyst, evaluating scripts for potential improvements.
def save_array_types(self, fname): '''Save array type registry to a file Args: fname (str): Name of file to save array database to ''' type_defs = {'arrays': sorted(list(self.array_types))} with open(fname, 'wt') as fh: pprint(type_defs, stream=fh)
Create a Python 3 function for saving array type registry to a file
As a Python code translator, you convert algorithms and pseudocode into Python.
Add array type definitions to internal registry
Here you have a function in Python 3, explain what it does def _register_array_types(self, objects): '''Add array type definitions to internal registry Args: objects (list of VhdlType or VhdlSubtype): Array types to track ''' # Add all array types directly types = [o for o in objects if i...
As a Python code analyst, you investigate and solve complex coding mysteries
def register_array_types_from_sources(self, source_files): '''Add array type definitions from a file list to internal registry Args: source_files (list of str): Files to parse for array definitions ''' for fname in source_files: if is_vhdl(fname): self._register_array_types(self.ext...
Write a Python 3 script to add array type definitions from a list of source files to internal registry
You are a Python code architect, reviewing and designing scalable and efficient code
def run(self, text): '''Run lexer rules against a source text Args: text (str): Text to apply lexer to Yields: A sequence of lexer matches. ''' stack = ['root'] pos = 0 patterns = self.tokens[stack[-1]] while True: for pat, action, new_state in patterns: m ...
Create a Python 3 function to run lexer rules against a source text.
You are a Python code analyst, evaluating scripts for potential improvements.
Scan the script for the version string
Can you generate a brief explanation for the following Python 3 code def get_package_version(verfile): '''Scan the script for the version string''' version = None with open(verfile) as fh: try: version = [line.split('=')[1].strip().strip("'") for line in fh if \ line.startswith('__ve...
You are a Python code analyst, evaluating scripts for potential improvements.
def parse_verilog_file(fname): '''Parse a named Verilog file Args: fname (str): File to parse. Returns: List of parsed objects. ''' with open(fname, 'rt') as fh: text = fh.read() return parse_verilog(text)
Write a Python 3 function that can parse a named Verilog file
You are a Python code analyst, evaluating scripts for potential improvements.
def parse_verilog(text): '''Parse a text buffer of Verilog code Args: text (str): Source code to parse Returns: List of parsed objects. ''' lex = VerilogLexer name = None kind = None saved_type = None mode = 'input' ptype = 'wire' metacomments = [] parameters = [] param_items = [] ...
Create a Python 3 function for parsing a text buffer of Verilog code into a list of objects.
As a Python code translator, you convert algorithms and pseudocode into Python.