def __powerise10(x): """ Returns x as a * 10 ^ b with 0<= a <10 """ if x == 0: return 0, 0 Neg = x < 0 if Neg: x = -x a = 1.0 * x / 10**(floor(log10(x))) b = int(floor(log10(x))) if Neg: a = -a return a, b
def better_features(filename: str, debug=False) -> List: img = cv2.imread(filename) img = cv2.resize(img, (400, 300)) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) clean = cv2.GaussianBlur(gray, (3, 3), 0) _, clean = cv2.threshold(clean, 100, 255, 0) DEBUG(clean, debug) hm = cv2.HuMoments(cv2.moments(clean)).flatten() for i in range(0, 7): hm[i] = -1 * \ copysign(1.0, hm[i]) * log10(abs(hm[i])) # return hm return [hm[0], hm[1], hm[3]]
def get_ticks_and_labels(self, data_low, data_high, bounds_low, bounds_high): ticks = self.get_ticks(data_low, data_high, bounds_low, bounds_high, 'auto') labels = array(['{:n}'.format(t) for t in ticks]) # only label 0.1,1,10,100,1000... try: labels[log10(ticks) % 1 != 0] = '' except ValueError: pass return ticks, labels
def get_ticks(self, *args, **kw): oticks = super(SparseLogTicks, self).get_ticks(*args, **kw) # get only 0.1,1,10,100,1000... ticks = oticks[oticks > 0] ticks = ticks[log10(ticks) % 1 == 0] if ticks.shape[0] == 1: tlow = 10**math.floor(math.log10(ticks[0])) if tlow == ticks[0]: tlow = 10**math.floor(math.log10(ticks[0]) - 1) ticks = hstack(([tlow], ticks)) ticks = hstack((ticks, [10**math.ceil(math.log10(oticks[-1]))])) ticks[0] = max(oticks[0], ticks[0]) return ticks
def get_ticks(self, *args, **kw): oticks = super(SparseLogTicks, self).get_ticks(*args, **kw) # get only 0.1,1,10,100,1000... ticks = oticks[oticks > 0] ticks = ticks[log10(ticks) % 1 == 0] if ticks.shape[0] == 1: tlow = 10 ** math.floor(math.log10(ticks[0])) if tlow == ticks[0]: tlow = 10 ** math.floor(math.log10(ticks[0]) - 1) ticks = hstack(([tlow], ticks)) ticks = hstack((ticks, [10 ** math.ceil(math.log10(oticks[-1]))])) ticks[0] = max(oticks[0], ticks[0]) return ticks
def to_hu_moments(filename: str, debug=False) -> List[float]: im = cv2.imread(filename, cv2.IMREAD_GRAYSCALE) # Binary Image ret, thresh = cv2.threshold(im, 127, 255, 0) # Processing # Finding contours contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) # Sorting Contours contours.sort(key=lambda x: cv2.contourArea(x), reverse=True) cnt = contours[1] # First is a box containing the hole image. x, y, w, h = cv2.boundingRect(cnt) # Cutted image to avoid shadows. im = im[y:y + h, x:x + w] DEBUG(im, mode="plt", debug=debug) # im = cv2.GaussianBlur(im, (5, 5), 0) _, im = cv2.threshold(im, 100, 255, cv2.THRESH_BINARY) DEBUG(im, mode="plt", debug=debug) contours, hierarchy = cv2.findContours(im, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) contours.sort(key=lambda x: cv2.contourArea(x), reverse=True) for cnt in contours[1:]: cv2.fillPoly(im, pts=[cnt], color=(0, 0, 0)) # img = cv2.drawContours(im, cnt, -1, (255), cv2.FILLED) DEBUG(im, mode="plt", debug=debug) # Calculate Moments moments = cv2.moments(im) # Calculate Hu Moments huMoments = cv2.HuMoments(moments) # Log scale hu moments for i in range(0, 7): huMoments[i] = -1 * \ copysign(1.0, huMoments[i]) * log10(abs(huMoments[i])) return huMoments[:-3]
def histogramdd(sample, bins=10, range=None, normed=False, weights=None): """histogramdd(sample, bins=10, range=None, normed=False, weights=None) Return the N-dimensional histogram of the sample. Parameters: sample : sequence or array A sequence containing N arrays or an NxM array. Input data. bins : sequence or scalar A sequence of edge arrays, a sequence of bin counts, or a scalar which is the bin count for all dimensions. Default is 10. range : sequence A sequence of lower and upper bin edges. Default is [min, max]. normed : boolean If False, return the number of samples in each bin, if True, returns the density. weights : array Array of weights. The weights are normed only if normed is True. Should the sum of the weights not equal N, the total bin count will not be equal to the number of samples. Returns: hist : array Histogram array. edges : list List of arrays defining the lower bin edges. SeeAlso: histogram Example >>> x = random.randn(100,3) >>> hist3d, edges = histogramdd(x, bins = (5, 6, 7)) """ try: # Sample is an ND-array. N, D = sample.shape except (AttributeError, ValueError): # Sample is a sequence of 1D arrays. sample = atleast_2d(sample).T N, D = sample.shape nbin = empty(D, int) edges = D * [None] dedges = D * [None] if weights is not None: weights = asarray(weights) try: M = len(bins) if M != D: raise AttributeError, 'The dimension of bins must be a equal to the dimension of the sample x.' except TypeError: bins = D * [bins] # Select range for each dimension # Used only if number of bins is given. if range is None: smin = atleast_1d(array(sample.min(0), float)) smax = atleast_1d(array(sample.max(0), float)) else: smin = zeros(D) smax = zeros(D) for i in arange(D): smin[i], smax[i] = range[i] # Make sure the bins have a finite width. for i in arange(len(smin)): if smin[i] == smax[i]: smin[i] = smin[i] - .5 smax[i] = smax[i] + .5 # Create edge arrays for i in arange(D): if isscalar(bins[i]): nbin[i] = bins[i] + 2 # +2 for outlier bins edges[i] = linspace(smin[i], smax[i], nbin[i] - 1) else: edges[i] = asarray(bins[i], float) nbin[i] = len(edges[i]) + 1 # +1 for outlier bins dedges[i] = diff(edges[i]) nbin = asarray(nbin) # Compute the bin number each sample falls into. Ncount = {} for i in arange(D): Ncount[i] = digitize(sample[:, i], edges[i]) # Using digitize, values that fall on an edge are put in the right bin. # For the rightmost bin, we want values equal to the right # edge to be counted in the last bin, and not as an outlier. outliers = zeros(N, int) for i in arange(D): # Rounding precision decimal = int(-log10(dedges[i].min())) + 6 # Find which points are on the rightmost edge. on_edge = where( around(sample[:, i], decimal) == around(edges[i][-1], decimal))[0] # Shift these points one bin to the left. Ncount[i][on_edge] -= 1 # Flattened histogram matrix (1D) hist = zeros(nbin.prod(), float) # Compute the sample indices in the flattened histogram matrix. ni = nbin.argsort() shape = [] xy = zeros(N, int) for i in arange(0, D - 1): xy += Ncount[ni[i]] * nbin[ni[i + 1:]].prod() xy += Ncount[ni[-1]] # Compute the number of repetitions in xy and assign it to the flattened histmat. if len(xy) == 0: return zeros(nbin - 2, int), edges flatcount = bincount(xy, weights) a = arange(len(flatcount)) hist[a] = flatcount # Shape into a proper matrix hist = hist.reshape(sort(nbin)) for i in arange(nbin.size): j = ni[i] hist = hist.swapaxes(i, j) ni[i], ni[j] = ni[j], ni[i] # Remove outliers (indices 0 and -1 for each dimension). core = D * [slice(1, -1)] hist = hist[core] # Normalize if normed is True if normed: s = hist.sum() for i in arange(D): shape = ones(D, int) shape[i] = nbin[i] - 2 hist = hist / dedges[i].reshape(shape) hist /= s return hist, edges
def log_opp(x): return 105*log10(x+1)
def histogramdd(sample, bins=10, range=None, normed=False, weights=None): """histogramdd(sample, bins=10, range=None, normed=False, weights=None) Return the N-dimensional histogram of the sample. Parameters: sample : sequence or array A sequence containing N arrays or an NxM array. Input data. bins : sequence or scalar A sequence of edge arrays, a sequence of bin counts, or a scalar which is the bin count for all dimensions. Default is 10. range : sequence A sequence of lower and upper bin edges. Default is [min, max]. normed : boolean If False, return the number of samples in each bin, if True, returns the density. weights : array Array of weights. The weights are normed only if normed is True. Should the sum of the weights not equal N, the total bin count will not be equal to the number of samples. Returns: hist : array Histogram array. edges : list List of arrays defining the lower bin edges. SeeAlso: histogram Example >>> x = random.randn(100,3) >>> hist3d, edges = histogramdd(x, bins = (5, 6, 7)) """ try: # Sample is an ND-array. N, D = sample.shape except (AttributeError, ValueError): # Sample is a sequence of 1D arrays. sample = atleast_2d(sample).T N, D = sample.shape nbin = empty(D, int) edges = D*[None] dedges = D*[None] if weights is not None: weights = asarray(weights) try: M = len(bins) if M != D: raise AttributeError, 'The dimension of bins must be a equal to the dimension of the sample x.' except TypeError: bins = D*[bins] # Select range for each dimension # Used only if number of bins is given. if range is None: smin = atleast_1d(array(sample.min(0), float)) smax = atleast_1d(array(sample.max(0), float)) else: smin = zeros(D) smax = zeros(D) for i in arange(D): smin[i], smax[i] = range[i] # Make sure the bins have a finite width. for i in arange(len(smin)): if smin[i] == smax[i]: smin[i] = smin[i] - .5 smax[i] = smax[i] + .5 # Create edge arrays for i in arange(D): if isscalar(bins[i]): nbin[i] = bins[i] + 2 # +2 for outlier bins edges[i] = linspace(smin[i], smax[i], nbin[i]-1) else: edges[i] = asarray(bins[i], float) nbin[i] = len(edges[i])+1 # +1 for outlier bins dedges[i] = diff(edges[i]) nbin = asarray(nbin) # Compute the bin number each sample falls into. Ncount = {} for i in arange(D): Ncount[i] = digitize(sample[:,i], edges[i]) # Using digitize, values that fall on an edge are put in the right bin. # For the rightmost bin, we want values equal to the right # edge to be counted in the last bin, and not as an outlier. outliers = zeros(N, int) for i in arange(D): # Rounding precision decimal = int(-log10(dedges[i].min())) +6 # Find which points are on the rightmost edge. on_edge = where(around(sample[:,i], decimal) == around(edges[i][-1], decimal))[0] # Shift these points one bin to the left. Ncount[i][on_edge] -= 1 # Flattened histogram matrix (1D) hist = zeros(nbin.prod(), float) # Compute the sample indices in the flattened histogram matrix. ni = nbin.argsort() shape = [] xy = zeros(N, int) for i in arange(0, D-1): xy += Ncount[ni[i]] * nbin[ni[i+1:]].prod() xy += Ncount[ni[-1]] # Compute the number of repetitions in xy and assign it to the flattened histmat. if len(xy) == 0: return zeros(nbin-2, int), edges flatcount = bincount(xy, weights) a = arange(len(flatcount)) hist[a] = flatcount # Shape into a proper matrix hist = hist.reshape(sort(nbin)) for i in arange(nbin.size): j = ni[i] hist = hist.swapaxes(i,j) ni[i],ni[j] = ni[j],ni[i] # Remove outliers (indices 0 and -1 for each dimension). core = D*[slice(1,-1)] hist = hist[core] # Normalize if normed is True if normed: s = hist.sum() for i in arange(D): shape = ones(D, int) shape[i] = nbin[i]-2 hist = hist / dedges[i].reshape(shape) hist /= s return hist, edges