本文整理汇总了Python中numpy.histogram方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.histogram方法的具体用法?Python numpy.histogram怎么用?Python numpy.histogram使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.histogram方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: compareHistograms
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram [as 别名]
def compareHistograms(image,x,y,w,h, ppl):
#temporary crop detected target
tempCrop = image[x:x+w, y:y+h]
#generate temporary histogram to compare to existant ones
tempHist = generateHistogram(tempCrop)
if(len(ppl) > 0):
b = checkSimilarity(tempHist, ppl, image)
if(b):
return (b.x, b.y, b.w, b.h, b.color, b.label)
else:
return None
else:
return None
return None
示例2: get_hardness_distribution
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram [as 别名]
def get_hardness_distribution(gtG, max_dist, min_dist, rng, trials, bins, nodes,
n_ori, step_size):
heuristic_fn = lambda node_ids, node_id: \
heuristic_fn_vec(nodes[node_ids, :], nodes[[node_id], :], n_ori, step_size)
num_nodes = gtG.num_vertices()
gt_dists = []; h_dists = [];
for i in range(trials):
end_node_id = rng.choice(num_nodes)
gt_dist = gt.topology.shortest_distance(gt.GraphView(gtG, reversed=True),
source=gtG.vertex(end_node_id),
target=None, max_dist=max_dist)
gt_dist = np.array(gt_dist.get_array())
ind = np.where(np.logical_and(gt_dist <= max_dist, gt_dist >= min_dist))[0]
gt_dist = gt_dist[ind]
h_dist = heuristic_fn(ind, end_node_id)[:,0]
gt_dists.append(gt_dist)
h_dists.append(h_dist)
gt_dists = np.concatenate(gt_dists)
h_dists = np.concatenate(h_dists)
hardness = 1. - h_dists*1./gt_dists
hist, _ = np.histogram(hardness, bins)
hist = hist.astype(np.float64)
hist = hist / np.sum(hist)
return hist
示例3: test_gen_sma
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram [as 别名]
def test_gen_sma(self):
r"""Test gen_sma method.
Approach: Ensures the output is set, of the correct type, length, and units.
Check that they are in the correct range and follow the distribution.
"""
plan_pop = self.fixture
n = 10000
sma = plan_pop.gen_sma(n)
# ensure the units are length
self.assertEqual((sma/u.km).decompose().unit, u.dimensionless_unscaled)
# sma > 0
self.assertTrue(np.all(sma.value >= 0))
# sma >= arange[0], sma <= arange[1]
self.assertTrue(np.all(sma - plan_pop.arange[0] >= 0))
self.assertTrue(np.all(plan_pop.arange[1] - sma >= 0))
h = np.histogram(sma.to('AU').value,100,density=True)
hx = np.diff(h[1])/2.+h[1][:-1]
hp = plan_pop.dist_sma(hx)
chi2 = scipy.stats.chisquare(h[0],hp)
self.assertGreaterEqual(chi2[1],0.95)
示例4: test_gen_plan_params
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram [as 别名]
def test_gen_plan_params(self):
r"""Test generated planet parameters:
Expected: all 1 R_E, all p = 0.67, e = 0, and uniform a in arange
"""
obj = EarthTwinHabZone1(**self.spec)
x = 10000
a, e, p, Rp = obj.gen_plan_params(x)
assert(np.all(e == 0))
assert(np.all(p == 0.367))
assert(np.all(Rp == 1.0*u.R_earth))
h = np.histogram(a.to('AU').value,100,density=True)
chi2 = scipy.stats.chisquare(h[0],[1.0/np.diff(obj.arange.to('AU').value)[0]]*len(h[0]))
self.assertGreater(chi2[1], 0.95)
示例5: test_gen_plan_params
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram [as 别名]
def test_gen_plan_params(self):
r"""Test generated planet parameters:
Expected: all 1 R_E, all p = 0.67, e = 0, and uniform a,e in arange,erange
"""
obj = EarthTwinHabZone2(constrainOrbits=False,erange=[0.1,0.5],**self.spec)
x = 10000
a, e, p, Rp = obj.gen_plan_params(x)
assert(np.all(p == 0.367))
assert(np.all(Rp == 1.0*u.R_earth))
for param,param_range in zip([a.value,e],[obj.arange.value,obj.erange]):
h = np.histogram(param,100,density=True)
chi2 = scipy.stats.chisquare(h[0],[1.0/np.diff(param_range)[0]]*len(h[0]))
self.assertGreater(chi2[1], 0.95)
示例6: test_gen_radius
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram [as 别名]
def test_gen_radius(self):
r"""Test gen_radius method.
Approach: Ensures the output is set, of the correct type, length, and units.
Check distributional agreement.
"""
plan_pop = self.fixture
n = 10000
radii = plan_pop.gen_radius(n)
# ensure the units are length
self.assertEqual((radii/u.km).decompose().unit, u.dimensionless_unscaled)
# radius > 0
self.assertTrue(np.all(radii.value > 0))
self.assertTrue(np.all(np.isfinite(radii.value)))
h = np.histogram(radii.to('earthRad').value,bins=plan_pop.Rs)
np.testing.assert_allclose(plan_pop.Rvals.sum()*h[0]/float(n),plan_pop.Rvals,rtol=0.05)
示例7: hist_chars
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram [as 别名]
def hist_chars(x, m=None, M=None, width=50):
'''
Prints a one-line histogram with one char per bin. The bin count is
quantized into only a few values and scaled to create a visual
representation. Min and max values are displayed on the ends.
'''
(h, hbins, m, M) = _gethist(x, width, m, M)
nchars = len(_strhist_chars)
if np.any(h > 0):
hmin = np.min(h)
hmax = np.max(h)
hchar = np.round((nchars-1)*(h - hmin)/(hmax - hmin))
hstr = ''.join([_strhist_chars[int(i)] for i in hchar])
else:
hstr = ' ' * width
return '% .5f |%s| %.5f' % (m, hstr, M)
示例8: histogram
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram [as 别名]
def histogram(t, L):
"""
A: If t is a list of tensors/np.ndarrays, B is executed for all, yielding len(ts) histograms, which are summed
per bin
B: convert t to numpy, count bins.
:param t: tensor or list of tensor, each expected to be in [0, L)
:param L: number of symbols
:return: length-L array, containing at l the number of values mapping to to symbol l
"""
if isinstance(t, list):
ts = t
histograms = np.stack((histogram(t, L) for t in ts), axis=0) # get array (len(ts) x L)
return np.sum(histograms, 0)
assert 0 <= t.min() and t.max() < L, (t.min(), t.max())
a = tensor_to_np(t)
counts, _ = np.histogram(a, np.arange(L+1)) # +1 because np.histogram takes bin edges, including rightmost edge
return counts
# Gradients --------------------------------------------------------------------
示例9: threshold
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram [as 别名]
def threshold(self, morph):
"""Find the threshold value for a given morphology
"""
_morph = morph[morph > 0]
_bins = 50
# Decrease the bin size for sources with a small number of pixels
if _morph.size < 500:
_bins = max(np.int(_morph.size / 10), 1)
if _bins == 1:
return 0, _bins
hist, bins = np.histogram(np.log10(_morph).reshape(-1), _bins)
cutoff = np.where(hist == 0)[0]
# If all of the pixels are used there is no need to threshold
if len(cutoff) == 0:
return 0, _bins
return 10 ** bins[cutoff[-1]], _bins
示例10: plot_histograms
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram [as 别名]
def plot_histograms(file_name, candidate_data_multiple_bands,
reference_data_multiple_bands=None,
# Default is for Blue-Green-Red-NIR:
colour_order=['b', 'g', 'r', 'y'],
x_limits=None, y_limits=None):
logging.info('Display: Creating histogram plot - {}'.format(file_name))
fig = plt.figure()
plt.hold(True)
for colour, c_band in zip(colour_order, candidate_data_multiple_bands):
c_bh, c_bins = numpy.histogram(c_band, bins=256)
plt.plot(c_bins[:-1], c_bh, color=colour, linestyle='-', linewidth=2)
if reference_data_multiple_bands:
for colour, r_band in zip(colour_order, reference_data_multiple_bands):
r_bh, r_bins = numpy.histogram(r_band, bins=256)
plt.plot(
r_bins[:-1], r_bh, color=colour, linestyle='--', linewidth=2)
plt.xlabel('DN')
plt.ylabel('Number of pixels')
if x_limits:
plt.xlim(x_limits)
if y_limits:
plt.ylim(y_limits)
fig.savefig(file_name, bbox_inches='tight')
plt.close(fig)
示例11: intersectionAndUnion
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram [as 别名]
def intersectionAndUnion(imPred, imLab, numClass=150):
"""
Computes the intersection and Union for all the classes between two images
:param imPred: Predictions image
:param imLab: Ground-truth image
:param numClass: Number of semantic classes. Default:150
:return: Intersection and union for all the classes
"""
# Remove classes from unlabeled pixels in gt image.
# We should not penalize detections in unlabeled portions of the image.
imPred = imPred * (imLab > 0).long()
# Compute area intersection:
intersection = imPred * (imPred == imLab).long()
(area_intersection, _) = np.histogram(intersection, bins=numClass, range=(1, numClass))
# Compute area union:
(area_pred, _) = np.histogram(imPred, bins=numClass, range=(1, numClass))
(area_lab, _) = np.histogram(imLab, bins=numClass, range=(1, numClass))
area_union = area_pred + area_lab - area_intersection
IoU = area_intersection / (area_union + 1e-10)
return IoU
示例12: read_image
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram [as 别名]
def read_image(self,im):
if self.i >= self.k :
self.i = 0
try:
img = Image.open(im)
osize = img.size
img.thumbnail((self.resample,self.resample))
v = [float(p)/float(img.size[0]*img.size[1])*100 for p in np.histogram(np.asarray(img))[0]]
if self.size :
v += [osize[0], osize[1]]
pbar.update(1)
i = self.i
self.i += 1
return [i, v, im]
except Exception as e:
print("Error reading ",im,e)
return [None, None, None]
示例13: read_image
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram [as 别名]
def read_image(self,im):
if self.i >= self.k :
self.i = 0
try:
img = Image.open(im)
osize = img.size
img.thumbnail((self.resample,self.resample))
v = [float(p)/float(img.size[0]*img.size[1])*100 for p in np.histogram(np.asarray(img))[0]]
if self.size :
v += [osize[0], osize[1]]
i = self.i
self.i += 1
return [i, v, im]
except Exception as e:
print("Error reading ",im,e)
return [None, None, None]
示例14: _hist_bin_sqrt
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram [as 别名]
def _hist_bin_sqrt(x, range):
"""
Square root histogram bin estimator.
Bin width is inversely proportional to the data size. Used by many
programs for its simplicity.
Parameters
----------
x : array_like
Input data that is to be histogrammed, trimmed to range. May not
be empty.
Returns
-------
h : An estimate of the optimal bin width for the given data.
"""
del range # unused
return x.ptp() / np.sqrt(x.size)
示例15: _hist_bin_sturges
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram [as 别名]
def _hist_bin_sturges(x, range):
"""
Sturges histogram bin estimator.
A very simplistic estimator based on the assumption of normality of
the data. This estimator has poor performance for non-normal data,
which becomes especially obvious for large data sets. The estimate
depends only on size of the data.
Parameters
----------
x : array_like
Input data that is to be histogrammed, trimmed to range. May not
be empty.
Returns
-------
h : An estimate of the optimal bin width for the given data.
"""
del range # unused
return x.ptp() / (np.log2(x.size) + 1.0)