本文整理汇总了Python中skimage.exposure.histogram函数的典型用法代码示例。如果您正苦于以下问题:Python histogram函数的具体用法?Python histogram怎么用?Python histogram使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了histogram函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: color_feature
def color_feature(blur, hbins=15, sbins=15):
hsv = color.rgb2hsv(blur)
# cal hist
h_hist = exposure.histogram(hsv[:, :, 0], nbins=hbins)
s_hist = exposure.histogram(hsv[:, :, 1], nbins=sbins)
return np.append(normalize(h_hist[0]), normalize(s_hist[0]))
示例2: getColorVector
def getColorVector(im, nbin):
h1, v1 = exposure.histogram(im[:,:,0], nbin)
h2, v2 = exposure.histogram(im[:,:,1], nbin)
h3, v3 = exposure.histogram(im[:,:,2], nbin)
h1 = h1 / (h1.sum() * 1.0)
h2 = h2 / (h2.sum() * 1.0)
h3 = h3 / (h3.sum() * 1.0)
return np.append(h1,[h2,h3])
示例3: plotImageWithHistogram
def plotImageWithHistogram(im, size, alpha=0.3, interpolation='nearest'):
r"""Plot an image alongside its histogram
Parameters
----------
im : a numpy array
The input image
size : number
The size (in in) for the single figure. The plot will be
that high and twice that wide.
alpha : float
The transparency. A value of 0.3 is great for an RGB image,
a value of 0.8 is a bit better for a grayscale image.
Returns
-------
(ax__image, ax_hist)
The matplotlib axes for the figure.
Examples
--------
from jmToolsPy3 import plotImageWithHistogram
import numpy as np
from skimage import data
img1 = data.camera()
axImg1, axHis1 = plotImageWithHistogram(img1, 5, alpha=0.8)
img2 = data.lena()
axImg2, axHis2 = plotImageWithHistogram(img2, 5, alpha=0.3)
"""
from skimage import exposure
from matplotlib import pyplot as plt
fig, (ax_image, ax_hist) = plt.subplots(ncols=2, figsize=(2*size, size))
ax_image.imshow(im, cmap=plt.cm.gray, interpolation=interplolation)
if im.ndim == 2:
hist, bin_centers = exposure.histogram(im)
ax_hist.fill_between(bin_centers, hist, alpha=alpha, color='gray')
elif im.ndim == 3:
for channel, channel_color in zip(iter_channels(im), 'rgb'):
hist, bin_centers = exposure.histogram(channel)
ax_hist.fill_between(bin_centers, hist, alpha=alpha, color=channel_color)
ax_hist.set_ylabel('# pixels')
ax_hist.set_xlabel('intensity')
ax_hist.set_yticklabels("")
ax_image.set_axis_off()
# match_axes_height(ax_image, ax_hist)
dst = ax_hist.get_position()
src = ax_image.get_position()
ax_hist.set_position([dst.xmin, src.ymin, dst.width, src.height])
return ax_image, ax_hist
示例4: test_normalize
def test_normalize():
im = np.array([0, 255, 255], dtype=np.uint8)
frequencies, bin_centers = exposure.histogram(im, source_range='dtype',
normalize=False)
expected = np.zeros(256)
expected[0] = 1
expected[-1] = 2
assert_equal(frequencies, expected)
frequencies, bin_centers = exposure.histogram(im, source_range='dtype',
normalize=True)
expected /= 3.
assert_equal(frequencies, expected)
示例5: threshHist
def threshHist(imgIn):
imgIn1 = imgIn.ravel()
# Histogram analysis to find maximum peak and associated gl
pxCnt, gL = exposure.histogram( imgIn )
indMaxBG = int(np.arange( len(imgIn1) )[pxCnt == pxCnt.max()]) #int()
BGlevel = gL[indMaxBG]
# Nearest min below this max is threshold
d1 = np.zeros( np.shape(pxCnt) )
for i in range( 2 , len(pxCnt) - 1):
# derivative approximation
d1[i] = pxCnt[ i + 1 ] - pxCnt[ i ]
i = 1
p = 0
while ( d1[ indMaxBG - i ] > 0): ### - i!!!
p = indMaxBG - i
i = i + 1
t = gL[ p ]
imgOut = imgProc.applyThresh( imgIn, t )
return imgOut
示例6: threshold_yen
def threshold_yen(image, nbins=256, shift=None):
"""Return threshold value based on Yen's method.
Parameters
----------
image : array
Input image.
nbins : int, optional
Number of bins used to calculate histogram. This value is ignored for
integer arrays.
shift : int, optional
Shift threshold value by percent up (positive) or down (negative).
Returns
-------
threshold : float
Upper threshold value. All pixels intensities that less or equal of
this value assumed as foreground.
References
----------
.. [1] Yen J.C., Chang F.J., and Chang S. (1995) "A New Criterion
for Automatic Multilevel Thresholding" IEEE Trans. on Image
Processing, 4(3): 370-378
.. [2] Sezgin M. and Sankur B. (2004) "Survey over Image Thresholding
Techniques and Quantitative Performance Evaluation" Journal of
Electronic Imaging, 13(1): 146-165,
http://www.busim.ee.boun.edu.tr/~sankur/SankurFolder/Threshold_survey.pdf
.. [3] ImageJ AutoThresholder code, http://fiji.sc/wiki/index.php/Auto_Threshold
Examples
--------
>>> from skimage.data import camera
>>> image = camera()
>>> thresh = threshold_yen(image)
>>> binary = image <= thresh
"""
hist, bin_centers = histogram(image, nbins)
# On blank images (e.g. filled with 0) with int dtype, `histogram()`
# returns `bin_centers` containing only one value. Speed up with it.
if bin_centers.size == 1:
return bin_centers[0]
# Calculate probability mass function
pmf = hist.astype(np.float32) / hist.sum()
P1 = np.cumsum(pmf) # Cumulative normalized histogram
P1_sq = np.cumsum(pmf ** 2)
# Get cumsum calculated from end of squared array:
P2_sq = np.cumsum(pmf[::-1] ** 2)[::-1]
# P2_sq indexes is shifted +1. I assume, with P1[:-1] it's help avoid '-inf'
# in crit. ImageJ Yen implementation replaces those values by zero.
crit = np.log(((P1_sq[:-1] * P2_sq[1:]) ** -1) *
(P1[:-1] * (1.0 - P1[:-1])) ** 2)
threshold = bin_centers[crit.argmax()]
ptp = (bin_centers[-1] - bin_centers[0]) / 100. # Peek to peek range
if shift:
threshold += ptp * shift
# print("Threshold value shift", (threshold - bin_centers[0]) / float(ptp))
return threshold
示例7: statxture
def statxture(pixels):
"""computes a variety of texture stats from
the image histogram.
See Digital Image Processing Using MATLAB, ch. 11"""
average_gray_level = np.mean(pixels)
average_contrast = np.std(pixels)
H = histogram(pixels)[0]
H = H / (1. * len(pixels))
L = len(H)
d = (L - 1.)**2
normvar = np.var(pixels) / d
smoothness = 1. - 1. / (1. + normvar)
third_moment = moment(pixels,3) / d
uniformity = np.sum(H**2)
eps = np.finfo(float).eps
entropy = 0. - np.sum(H * np.log2(H + eps))
return average_gray_level, average_contrast, smoothness, \
third_moment, uniformity, entropy
示例8: test_all_negative_image
def test_all_negative_image():
im = np.array([-128, -1], dtype=np.int8)
frequencies, bin_centers = exposure.histogram(im)
assert_array_equal(bin_centers, np.arange(-128, 0))
assert frequencies[0] == 1
assert frequencies[-1] == 1
assert_array_equal(frequencies[1:-1], 0)
示例9: analyse_histogram
def analyse_histogram(data, roi=None, debug=False, dens_min=20, dens_max=255, minT=0.95, maxT=1.05):
if roi == None:
#roi = np.ones(data.shape, dtype=np.bool)
roi = np.logical_and(data >= dens_min, data <= dens_max)
voxels = data[np.nonzero(roi)]
hist, bins = skiexp.histogram(voxels)
max_peakIdx = hist.argmax()
minT = minT * hist[max_peakIdx]
maxT = maxT * hist[max_peakIdx]
histTIdxs = (hist >= minT) * (hist <= maxT)
histTIdxs = np.nonzero(histTIdxs)[0]
histTIdxs = histTIdxs.astype(np.int)
class1TMin = bins[histTIdxs[0]]
class1TMax = bins[histTIdxs[-1]]
liver = data * (roi > 0)
class1 = np.where( (liver >= class1TMin) * (liver <= class1TMax), 1, 0)
if debug:
plt.figure()
plt.plot(bins, hist)
plt.hold(True)
plt.plot(bins[max_peakIdx], hist[max_peakIdx], 'ro')
plt.plot(bins[histTIdxs], hist[histTIdxs], 'r')
plt.plot(bins[histTIdxs[0]], hist[histTIdxs[0]], 'rx')
plt.plot(bins[histTIdxs[-1]], hist[histTIdxs[-1]], 'rx')
plt.title('Histogram of liver density and its class1 = maximal peak (red dot) +-5% of its density (red line).')
plt.show()
return class1
示例10: test_peak_float_out_of_range_dtype
def test_peak_float_out_of_range_dtype():
im = np.array([10, 100], dtype=np.float16)
nbins = 10
frequencies, bin_centers = exposure.histogram(im, nbins=nbins, source_range='dtype')
assert_almost_equal(np.min(bin_centers), -0.9, 3)
assert_almost_equal(np.max(bin_centers), 0.9, 3)
assert_equal(len(bin_centers), 10)
示例11: _plot_histogram
def _plot_histogram(ax, image, alpha=0.3, **kwargs):
# Use skimage's histogram function which has nice defaults for
# integer and float images.
hist, bin_centers = exposure.histogram(image)
ax.fill_between(bin_centers, hist, alpha=alpha, **kwargs)
ax.set_xlabel('intensity')
ax.set_ylabel('# pixels')
示例12: histogram
def histogram(image):
# Iterate throught a.) Colors, b.) Channels to create lines
for color, channel in zip('rgb', np.rollaxis(image, axis=-1)):
counts, bin_centers = exposure.histogram(channel)
a = plt.fill_between(bin_centers, counts, color=color, alpha=0.4)
return a;
示例13: set_data
def set_data(self, data):#, mask):
self.data = data
# self.mask = mask
# if self.data is not None:
self.hist, self.bins = skiexp.histogram(self.data, nbins=1000)
# if mask is not None:
# self.data_m = self.data[np.nonzero(self.mask)]
# else:
# self.data_m = self.data
if self.params and self.params.has_key('data_min'):
self.data_min = self.params['data_min']
# elif self.data is not None:
self.data_min = self.data.min()
# else:
# self.data_min = 0
if self.params and self.params.has_key('datam_max'):
self.data_max = self.params['data_max']
# elif self.data is not None:
self.data_max = self.data.max()
# else:
# self.data_max = 0
self.ui.hypo_mean_SL.setMinimum(self.data_min)
self.ui.heal_mean_SL.setMinimum(self.data_min)
self.ui.hyper_mean_SL.setMinimum(self.data_min)
self.ui.hypo_mean_SL.setMaximum(self.data_max)
self.ui.heal_mean_SL.setMaximum(self.data_max)
self.ui.hyper_mean_SL.setMaximum(self.data_max)
self.update_figures()
示例14: test_negative_overflow
def test_negative_overflow():
im = np.array([-1, 127], dtype=np.int8)
frequencies, bin_centers = exposure.histogram(im)
assert_array_equal(bin_centers, np.arange(-1, 128))
assert frequencies[0] == 1
assert frequencies[-1] == 1
assert_array_equal(frequencies[1:-1], 0)
示例15: testSkimage2
def testSkimage2():
img = Image.open('../img/1.png')
# img = Image.open('../img/2.png')
img = np.array(img)
imggray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# (thresh, imgbw) = cv2.threshold(imggray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
camera = imggray
# camera = data.camera()
val = filters.threshold_otsu(camera)
hist, bins_center = exposure.histogram(camera)
plt.figure(figsize=(9, 4))
plt.subplot(131)
plt.imshow(camera, cmap='gray', interpolation='nearest')
plt.axis('off')
plt.subplot(132)
plt.imshow(camera < val, cmap='gray', interpolation='nearest')
plt.axis('off')
plt.subplot(133)
plt.plot(bins_center, hist, lw=2)
plt.axvline(val, color='k', ls='--')
plt.tight_layout()
plt.show()
return