output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Generator function to yield lines stored in a .
How would you explain what the following Python 3 function does def lines(text): assert text is not None assert '\r' not in text previous_newline_index = 0 newline_index = text.find('\n') while newline_index != -1: yield text[previous_newline_index:newline_index] previous_newline_ind...
As a python code expert, you are capable of creating scripts from specifications.
Returns the first line and its regex that matches the source code.
How would you explain what the following Python 3 function does def matching_number_line_and_regex(source_lines, generated_regexes, max_line_count=15): initial_numbers_and_lines = enumerate(itertools.islice(source_lines, max_line_count)) matching_number_line_and_regexps = ( (number, line, matching_regex...
As a Python code analyst, you investigate and solve complex coding mysteries
Yields the pythonized comments for the given list of tokens.
Can you generate a brief explanation for the following Python 3 code def _pythonized_comments(tokens): is_after_colon = True for token_type, token_text in tokens: if is_after_colon and (token_type in pygments.token.String): token_type = pygments.token.Comment elif token_text == ':': ...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the encoding used by the text file stored in source_path.
Here you have a function in Python 3, explain what it does def encoding_for(source_path, encoding='automatic', fallback_encoding=None): assert encoding is not None if encoding == 'automatic': with open(source_path, 'rb') as source_file: heading = source_file.read(128) result = None ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns True if there is a lexer for source_path.
Given the following Python 3 function, write the documentation def has_lexer(source_path): result = bool(pygments.lexers.find_lexer_class_for_filename(source_path)) if not result: suffix = os.path.splitext(os.path.basename(source_path))[1].lstrip('.') result = suffix in _SUFFIX_TO_FALLBACK_LEXER...
As a Python code composer, you craft elegant and concise scripts.
def source_analysis( source_path, group, encoding='automatic', fallback_encoding='cp1252', generated_regexes=pygount.common.regexes_from(DEFAULT_GENERATED_PATTERNS_TEXT), duplicate_pool=None): """ Analysis for line counts in source code stored in ``source_path``. :param source_path:...
Can you write a function in Python 3 where it analyzes the source code in the specified source file.
You are a Python code architect, reviewing and designing scalable and efficient code
polyfit2dGrid - 2d polynomial fit
Can you generate a brief explanation for the following Python 3 code def polynomial(img, mask, inplace=False, replace_all=False, max_dev=1e-5, max_iter=20, order=2): ''' replace all masked values calculate flatField from 2d-polynomal fit filling all high gradient areas within average...
You are a Python code generator, capable of creating scripts from specifications.
def errorDist(scale, measExpTime, n_events_in_expTime, event_duration, std, points_per_time=100, n_repetitions=300): ''' TODO ''' ntimes = 10 s1 = measExpTime * scale * 10 # exp. time factor 1/16-->16: p2 = np.logspace(-4, 4, 18, base=2) t = np.lin...
Can you create a Python 3 function that returns the error distribution of a single event in a single time series.
You are a Python code architect, reviewing and designing scalable and efficient code
std ... standard deviation of every signal dur1...dur3 --> event duration per second n1...n3 --> number of events per second
Make a summary of the following Python 3 code def exampleSignals(std=1, dur1=1, dur2=3, dur3=0.2, n1=0.5, n2=0.5, n3=2): ''' std ... standard deviation of every signal dur1...dur3 --> event duration per second n1...n3 --> number of events per second ''' np.random...
As a python code expert, you are capable of creating scripts from specifications.
def _flux(t, n, duration, std, offs=1): ''' returns Gaussian shaped signal fluctuations [events] t --> times to calculate event for n --> numbers of events per sec duration --> event duration per sec std --> std of event if averaged over time offs --> event offset ''' ...
Write a Python 3 function for returning a new array of the same size as the original array.
You are a Python code generator, capable of creating scripts from specifications.
capture signal and return its standard deviation
Can you generate the documentation for the following Python 3 function def _capture(f, t, t0, factor): ''' capture signal and return its standard deviation #TODO: more detail ''' n_per_sec = len(t) / t[-1] # len of one split: n = int(t0 * factor * n_per_sec) s = len(f) // n ...
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a generic camera matrix for a given image shape
Given the following Python 3 function, write the documentation def genericCameraMatrix(shape, angularField=60): ''' Return a generic camera matrix [[fx, 0, cx], [ 0, fy, cy], [ 0, 0, 1]] for a given image shape ''' # http://nghiaho.com/?page_id=576 # assume that the optica...
You are a Python code architect, reviewing and designing scalable and efficient code
calculate the spatial resolved standard deviation of a given 2d array
Make a summary of the following Python 3 code def standardDeviation2d(img, ksize=5, blurred=None): ''' calculate the spatial resolved standard deviation for a given 2d array ksize -> kernel size blurred(optional) -> with same ksize gaussian filtered image s...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a new array with masked areas replaced with filtered results
Can you generate a brief explanation for the following Python 3 code def maskedFilter(arr, mask, ksize=30, fill_mask=True, fn='median'): ''' fn['mean', 'median'] fill_mask=True: replaced masked areas with filtered results fill_mask=False: masked areas are ignored ...
As a Python code analyst, you investigate and solve complex coding mysteries
Extract vignetting from a set of images containing different devices
Can you generate a brief explanation for the following Python 3 code def vignettingFromDifferentObjects(imgs, bg): ''' Extract vignetting from a set of images containing different devices The devices spatial inhomogeneities are averaged This method is referred as 'Method C' in --- ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Calculate the average signal - to - noise ratio of two images.
Can you generate a brief explanation for the following Python 3 code def SNR_IEC(i1, i2, ibg=0, allow_color_images=False): ''' Calculate the averaged signal-to-noise ratio SNR50 as defined by IEC NP 60904-13 needs 2 reference EL images and one background image ''' # ensure images are typ...
You are a Python code generator, capable of creating scripts from specifications.
def _rotate(img, angle): ''' angle [DEG] ''' s = img.shape if angle == 0: return img else: M = cv2.getRotationMatrix2D((s[1] // 2, s[0] // 2), angle, 1) return cv2.warpAffine(img, M, (s...
Create a Python 3 function to rotate the image by the given angle
As a python code expert, you are capable of creating scripts from specifications.
find the best image that fits best self. _base_img
Can you generate the documentation for the following Python 3 function def _findOverlap(self, img_rgb, overlap, overlapDeviation, rotation, rotationDeviation): ''' return offset(x,y) which fit best self._base_img through template matching ''' # get gray...
You are a Python code analyst, evaluating scripts for potential improvements.
def estimateFromImages(imgs1, imgs2=None, mn_mx=None, nbins=100): ''' estimate the noise level function as stDev over image intensity from a set of 2 image groups images at the same position have to show the identical setup, so imgs1[i] - imgs2[i] = noise ''' if imgs2 is None: ...
Write a Python 3 script for estimating the noise level function over images at the same position
You are a Python code analyst, evaluating scripts for potential improvements.
def _evaluate(x, y, weights): ''' get the parameters of the, needed by 'function' through curve fitting ''' i = _validI(x, y, weights) xx = x[i] y = y[i] try: fitParams = _fit(xx, y) # bound noise fn to min defined y value: minY = function(xx[0], *fit...
How would you code a function in Python 3 to evaluate the parameters of the necessary by function through curve fitting
You are a Python code architect, reviewing and designing scalable and efficient code
def boundedFunction(x, minY, ax, ay): ''' limit [function] to a minimum y value ''' y = function(x, ax, ay) return np.maximum(np.nan_to_num(y), minY)
Create a Python 3 function to limit [ function ] to a minimum y value
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Can you create a Python 3 function that returns indices that have enough data points and are not erroneous
You are a Python code architect, reviewing and designing scalable and efficient code
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 # ...
Can you implement a function in Python 3 that smooths the NLF with respect to the given weights
As a Python code analyst, you investigate and solve complex coding mysteries
Estimate the NLF from one or two images of the same kind
Can you generate a brief explanation for the following Python 3 code 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
As a python code expert, you are capable of creating scripts from specifications.
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)
Create a Python 3 function to get the a range of image intensities that most pixels are in with
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Create a Python 3 function for calculating the noise level function for a single image and a signal.
As a Python code translator, you convert algorithms and pseudocode into Python.
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)] ...
Can you implement a function in Python 3 that returns a new array with the polynomial fitted values in the order specified by the mask and order specified.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the minimum position in an array.
Here you have a function in Python 3, explain what it does def minimumLineInArray(arr, relative=False, f=0, refinePosition=True, max_pos=100, return_pos_arr=False, # order=2 ): ''' find clos...
You are a Python code architect, reviewing and designing scalable and efficient code
Remove all low frequencies by setting a square in the middle of the Fourier transformation of the size ( 2 * threshold^2 to zero
Can you generate the documentation for the following Python 3 function 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 no...
As a Python code analyst, you investigate and solve complex coding mysteries
reconstruct the image from the Fourier transform and return the real image
Here you have a function in Python 3, explain what it does 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))
You are a Python code analyst, evaluating scripts for potential improvements.
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...
Create a Python 3 function for returning the histogram of Oriented Gradients
As a python code expert, you are capable of creating scripts from specifications.
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]) ...
Can you create a Python 3 function that visualizes HOG as polynomial around cell center and radius of each sub array.
As a Python code analyst, you investigate and solve complex coding mysteries
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.: ...
Can you create a Python 3 function that returns a new array with the same shape as the array arr.
You are a Python code generator, capable of creating scripts from specifications.
Remove the border of an image.
Explain what the following Python 3 code does 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 space...
You are a Python code analyst, evaluating scripts for potential improvements.
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: ...
Implement a Python 3 function for adding an image to the list of entries in the cache.
As a python code expert, you are capable of creating scripts from specifications.
Returns the STE area relative to image area
Here you have a function in Python 3, explain what it does def relativeAreaSTE(self): ''' return STE area - relative to image area ''' s = self.noSTE.shape return np.sum(self.mask_STE) / (s[0] * s[1])
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the STE intensity distribution of the last set of STE
Can you tell what is the following Python 3 function doing 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)
As a Python code composer, you craft elegant and concise scripts.
transform a float to an unsigned integer array of a fitting dtype cutNegative cutHigh - all values < 0 will be set to False to get rid of negative values from fit range - all values from fit range - all values from fit range - all values from fit range - all values from fit range - all values from fit range...
Make a summary of the following Python 3 code 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 val...
As a Python code analyst, you investigate and solve complex coding mysteries
transform an unsigned integer array into a float array of the right size
Make a summary of the following Python 3 code 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 re...
You are a Python code architect, reviewing and designing scalable and efficient code
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
Can you create a Python 3 function that casts array to the next higher integer array if dtype = unsigned integer
You are a Python code analyst, evaluating scripts for potential improvements.
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 ...
How would you code a function in Python 3 to convert a single image to grayscale.
As a Python code translator, you convert algorithms and pseudocode into Python.
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
Write a Python 3 script for returning the normalized RGB space RGB / intensity
As a python code expert, you are capable of creating scripts from specifications.
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...
Can you create a Python 3 function that returns the monochromatic wavelength of the given image.
As a python code expert, you are capable of creating scripts from specifications.
rotate one or multiple grayscale or color images 90 degrees Insights
How would you explain what the following Python 3 function does 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) ...
As a Python code composer, you craft elegant and concise scripts.
Like cv2. applyColorMap but with different color maps
Explain what the following Python 3 code does 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 g...
As a python code expert, you are capable of creating scripts from specifications.
Returns the index to insert the given date in a list where each item is a date
Make a summary of the following Python 3 code 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))
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Implement a function in Python 3 to return the index of given or best fitting date in list l
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a list of dates available for the given type
Make a summary of the following Python 3 code 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: ...
As a python code expert, you are capable of creating scripts from specifications.
Returns a list of infos available for a given type and light.
Given the following Python 3 function, write the documentation 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: li...
You are a Python code architect, reviewing and designing scalable and efficient code
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...
How would you code a function in Python 3 to return an overview of all calibrations of all calibrations of all the calendars in the calendar.
You are a Python code generator, capable of creating scripts from specifications.
Sets the name and depth of the camera sensor with the name camera_name and bit_depth.
How would you explain what the following Python 3 function does 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 s...
As a python code expert, you are capable of creating scripts from specifications.
Adds a dark current to the calendar.
Can you generate a brief explanation for the following Python 3 code 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...
As a Python code composer, you craft elegant and concise scripts.
Adds noise to the entry in the dictionary.
Explain what the following Python 3 code does 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" ''' ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Add a flat field to the log.
Can you tell what is the following Python 3 function doing def addFlatField(self, arr, date=None, info='', error=None, light_spectrum='visible'): ''' light_spectrum = light, IR ... ''' self._registerLight(light_spectrum) self._checkShape(arr) d...
As a Python code analyst, you investigate and solve complex coding mysteries
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() ...
Create a Python 3 function to add lens to the list of available lights
As a Python code composer, you craft elegant and concise scripts.
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...
Implement a function in Python 3 to remove all old calibration entries except the youngest one.
As a Python code composer, you craft elegant and concise scripts.
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: ...
Write a Python 3 script for transposing all calibration arrays in case different array shape orders were used
As a python code expert, you are capable of creating scripts from specifications.
Corrects the image using non - local - means with guessing best parameters
Can you generate the documentation for the following Python 3 function 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)] = ...
You are a Python code generator, capable of creating scripts from specifications.
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') ...
Create a Python 3 function to correct dark current image
As a Python code composer, you craft elegant and concise scripts.
Apply a thresholded median replacing high gradients and values beyond the boundaries
How would you explain what the following Python 3 function does 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...
You are a Python code architect, reviewing and designing scalable and efficient code
get the most recent calibration for a given name light and date
Can you tell what is the following Python 3 function doing 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] ...
As a Python code composer, you craft elegant and concise scripts.
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 =...
Write a Python 3 function that can return a tuple of the smoothed and mask of the objects in the objectVignettingSeparation objects.
As a Python code composer, you craft elegant and concise scripts.
Add an image to the list of related objects.
Make a summary of the following Python 3 code 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: maxShea...
You are a Python code architect, reviewing and designing scalable and efficient code
calculate the standard deviation of all fitted images averaged to a grid
How would you explain what the following Python 3 function does 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)...
You are a Python code architect, reviewing and designing scalable and efficient code
fit the image to the reference image
Can you generate a brief explanation for the following Python 3 code 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) ...
As a python code expert, you are capable of creating scripts from specifications.
Find the object within an image
Can you tell what is the following Python 3 function doing 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()/...
As a Python code translator, you convert algorithms and pseudocode into Python.
Remove vertical lines in boolean array if linelength < min_line_length
Can you generate the documentation for the following Python 3 function def filterVerticalLines(arr, min_line_length=4): 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 in range(min_line_lengt...
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Implement a Python 3 function for returning the vignetting of a single image
You are a Python code analyst, evaluating scripts for potential improvements.
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) *...
Can you write a function in Python 3 where it returns the tilt factor of a single image
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns an image average of the images in the order they appear.
Can you tell what is the following Python 3 function doing 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 = ou...
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Implement a Python 3 function for returning a meshgrid that is offset within the image
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the maximal Poisson distance of a peak with respect to a center of the peak b and c.
Here you have a function in Python 3, explain what it does 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 ...
You are a Python code analyst, evaluating scripts for potential improvements.
rotate an image by a given angle
Given the following Python 3 function, write the documentation 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.getRotationMa...
You are a Python code architect, reviewing and designing scalable and efficient code
This function adjusts the image uncertainty to the exposure time of the given event.
Make a summary of the following Python 3 code 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 un...
As a Python code composer, you craft elegant and concise scripts.
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...
Implement a Python 3 function for writing images to a video file.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the image with the specified color and dtype.
Can you tell what is the following Python 3 function doing 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 } ...
You are a Python code architect, reviewing and designing scalable and efficient code
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...
How would you code a function in Python 3 to add an image to the image list and roi - upper left corner of the image
As a Python code composer, you craft elegant and concise scripts.
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 ...
Write a Python 3 function that can 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
You are a Python code architect, reviewing and designing scalable and efficient code
same as interpolate2dStructuredPointSpreadIDW but using the point spread method
Can you tell what is the following Python 3 function doing 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 big...
As a python code expert, you are capable of creating scripts from specifications.
Returns a signal - to - noise - map for the two images img1 and img2.
How would you explain what the following Python 3 function does 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 publis...
As a Python code analyst, you investigate and solve complex coding mysteries
sort the corners of a given quadrilateral of the type
Can you generate a brief explanation for the following Python 3 code 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...
As a Python code analyst, you investigate and solve complex coding mysteries
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
How would you implement a function in Python 3 that returns an array with contains the closest distance to the next positive value given in arr within a given kernel size
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a binary 2darray with the closest distance from every pixel to the target.
Here you have a function in Python 3, explain what it does 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 cl...
As a python code expert, you are capable of creating scripts from specifications.
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...
Can you implement a function in Python 3 that 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...
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a list of arrays of contour arrays from a binary image.
Here you have a function in Python 3, explain what it does 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): ...
As a python code expert, you are capable of creating scripts from specifications.
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...
Can you implement a function in Python 3 that returns the cumulative density function of a given array or a given position
As a python code expert, you are capable of creating scripts from specifications.
Generator to access evenly sized sub - cells in a 2d array
Can you generate a brief explanation for the following Python 3 code 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 ...
As a Python code analyst, you investigate and solve complex coding mysteries
Generator to access evenly sized sub - cells in a 2d array
Explain what the following Python 3 code does 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...
As a Python code translator, you convert algorithms and pseudocode into Python.
Same as subCell2DSlices but returning coordinates
Given the following Python 3 function, write the documentation 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 subCell2DSlice...
You are a Python code generator, capable of creating scripts from specifications.
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: ...
Can you implement a function in Python 3 that returns array where every cell equals result of fn on all sub - arrays
You are a Python code generator, capable of creating scripts from specifications.
Returns the defocus through a scene point uf f and fn
Can you generate the documentation for the following Python 3 function 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 focus...
As a Python code composer, you craft elegant and concise scripts.
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...
Implement a Python 3 function for extending array for convolution
You are a Python code generator, capable of creating scripts from specifications.
Create a new instance of the appropriate class based on the parameters of the specified method.
Can you generate a brief explanation for the following Python 3 code 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 sen...
You are a Python code analyst, evaluating scripts for potential improvements.
add corner points directly to extract them from image
Given the following Python 3 function, write the documentation 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) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
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
Given the following Python 3 function, write the documentation 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 ''' ...
As a Python code composer, you craft elegant and concise scripts.
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)
Write a Python 3 function that can add a new image using a continous stream
You are a Python code architect, reviewing and designing scalable and efficient code
add one chessboard image for detection lens distortion
Can you generate the documentation for the following Python 3 function 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.me...
As a Python code analyst, you investigate and solve complex coding mysteries
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
Implement a function in Python 3 to get the distortion coeffs in a formated string
As a Python code composer, you craft elegant and concise scripts.
draw a chessboard on the last added image - > image with the most recent found pattern
Make a summary of the following Python 3 code 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.findC...
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Can you write a function in Python 3 where it writes the distortion coeffs to file
As a Python code translator, you convert algorithms and pseudocode into Python.