Beispiel #1
0
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])
Beispiel #2
0
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]))
Beispiel #3
0
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
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)
Beispiel #5
0
 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
Beispiel #6
0
def preprocImageV(fimg):
    nbin=64
    dn = 24
    img=skimage.img_as_float(io.imread(fimg,as_grey=True))
    siz=img.shape
    sizMax=np.max(siz)
    siz2=(sizMax,sizMax)
    msk=np.zeros(siz)
    cv2.circle(msk, (siz[1]/2, siz[0]/2), (np.min(siz)/2)-3, (1,1,1), -1) ##cv2.cv.CV_FILLED
    s0 = 0.3440
    h1,xx = exposure.histogram(img[msk==1], nbin)
    s1 = np.std(img[msk==1])
    h  = h1.copy()
    h[np.argwhere(h > 0)[-1]] = 0
    h[np.argwhere(h > 0)[-1]] = 0
    st = np.percentile(img[msk==1], 1)
    p1 = np.argwhere(np.fabs(xx - st)==np.min(abs(xx - st)))[0][0]
    h[p1:np.min((nbin, p1 + np.round(dn * s1 / s0)))]=0
    p2 = np.argwhere(h==np.max(h))[0][0]
    max1=xx[p1]
    max2=xx[p2]
    ret= 0.8*(img-max1)/(max2-max1)
    ret[ret<0]=0
    ret[ret>1]=1
    ret=np.uint8(255*ret)
    ret2=np.zeros(siz2, np.uint8)
    r0=np.floor((sizMax-siz[0])/2)
    c0=np.floor((sizMax-siz[1])/2)
    ret2[r0:r0+siz[0], c0:c0+siz[1]]=ret
    # cv2.imshow("ret", ret)
    # cv2.imshow("ret2", ret2)
    # cv2.waitKey(0)
    return ret2
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')
Beispiel #8
0
    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()
Beispiel #9
0
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)
Beispiel #10
0
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
Beispiel #11
0
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
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)
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
Beispiel #14
0
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)
Beispiel #15
0
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
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;
def test_peak_int_range_dtype():
    im = np.array([10, 100], dtype=np.int8)
    frequencies, bin_centers = exposure.histogram(im, source_range='dtype')
    assert_array_equal(bin_centers, np.arange(-128, 128))
    assert_equal(frequencies[128+10], 1)
    assert_equal(frequencies[128+100], 1)
    assert_equal(frequencies[128+101], 0)
    assert_equal(frequencies.shape, (256,))
    def estimate_healthy_pdf(self, data, mask, params):
        perc = params['perc']
        k_std_l = params['k_std_h']
        simple_estim = params['healthy_simple_estim']
        show_me = params['show_healthy_pdf_estim']

        # data = tools.smoothing_tv(data.astype(np.uint8), tv_weight)
        ints = data[np.nonzero(mask)]
        hist, bins = skiexp.histogram(ints, nbins=256)
        if simple_estim:
            mu, sigma = scista.norm.fit(ints)
        else:
            ints = data[np.nonzero(mask)]

            n_pts = mask.sum()
            perc_in = n_pts * perc / 100

            peak_idx = np.argmax(hist)
            n_in = hist[peak_idx]
            win_width = 0

            while n_in < perc_in:
                win_width += 1
                n_in = hist[peak_idx - win_width:peak_idx + win_width].sum()

            idx_start = bins[peak_idx - win_width]
            idx_end = bins[peak_idx + win_width]
            inners_m = np.logical_and(ints > idx_start, ints < idx_end)
            inners = ints[np.nonzero(inners_m)]

            # liver pdf -------------
            mu = bins[peak_idx] + params['hack_healthy_mu']
            sigma = k_std_l * np.std(inners) + params['hack_healthy_sigma']

        mu = int(mu)
        sigma = int(sigma)
        rv = scista.norm(mu, sigma)

        if show_me:
            plt.figure()
            plt.subplot(211)
            plt.plot(bins, hist)
            plt.title('histogram with max peak')
            plt.hold(True)
            plt.plot([mu, mu], [0, hist.max()], 'g')
            ax = plt.axis()
            plt.axis([0, 256, ax[2], ax[3]])
            # plt.subplot(212), plt.plot(bins, rv_l.pdf(bins), 'g')
            x = np.arange(0, 256, 0.1)
            plt.subplot(212), plt.plot(x, rv.pdf(x), 'g')
            plt.hold(True)
            plt.plot(mu, rv.pdf(mu), 'go')
            ax = plt.axis()
            plt.axis([0, 256, ax[2], ax[3]])
            plt.title('estimated normal pdf of healthy parenchym')
            # plt.show()

        return rv
def features_extractor(trimmed):

    from color_quantinization import quantinization
    image_gray = quantinization(trimmed)
    # image_gray = color.rgb2hsv(image_gray)

    featuresh = []

    hh = exposure.histogram(image_gray[:, :, 0])
    featuresh.extend(hh[0])

    hs = exposure.histogram(image_gray[:, :, 1])
    featuresh.extend(hs[0])

    hv = exposure.histogram(image_gray[:, :, 2])
    featuresh.extend(hv[0])

    return featuresh
Beispiel #20
0
def test_dask_histogram():
    pytest.importorskip('dask', reason="dask python library is not installed")
    import dask.array as da
    dask_array = da.from_array(np.array([[0, 1], [1, 2]]), chunks=(1, 2))
    output_hist, output_bins = exposure.histogram(dask_array)
    expected_bins = [0, 1, 2]
    expected_hist = [1, 2, 1]
    assert np.allclose(expected_bins, output_bins)
    assert np.allclose(expected_hist, output_hist)
Beispiel #21
0
    def open_image(self):
        ''' Open the image given the path'''
        
        img = imread(self.path)

        counts,grays = histogram(img, nbins = 256)
         
        #img = (img-0)/(255 -0)

        return img,counts,grays
Beispiel #22
0
def cal_edge_curvature(binary, contours, cbins=15):
    contours = contours[0]

    height = binary.shape[0]
    width = binary.shape[1]

    mask = np.zeros((height, width), dtype=np.uint8)
    radius = 20
    rr, cc = draw.circle(height // 2, width // 2, radius)
    mask[rr, cc] = 1
    S = np.count_nonzero(mask)

    def count_with_edge(dot):
        r, c = dot
        mask = np.zeros((height, width), dtype=np.uint8)
        rr, cc = draw.circle(r, c, radius)

        # min_r = np.where(rr >= 0)[0][0]
        # min_c = np.where(cc >= 0)[0][0]
        # min_i = max(min_r, min_c)

        # print(r, c)
        # print(height, width)
        # print(rr)
        # print(cc)
        # max_r = np.where(rr < height)[0][-1]
        # max_c = np.where(cc < width)[0][-1]
        # max_i = min(max_r, max_c)

        # # print(width, height)
        # # print(rr.shape)
        # # print(cc.shape)
        # # print(rr[min_i: max_i])
        # # print(cc[min_i: max_i])
        # rr = rr[min_i: max_i]
        # cc = cc[min_i: max_i]
        # print(rr)
        # print(cc)

        for _r, _c in zip(rr, cc):
            if 0 <= _r < height and 0 <= _c < width:
                mask[_r, _c] = 1

        # mask[rr, cc] = 1
        binary_for_cal = np.where(mask == 1, binary, False)
        return np.count_nonzero(binary_for_cal)

    I = np.array([count_with_edge(contour) for contour in contours])

    c = I / S

    c_hist = exposure.histogram(c, nbins=cbins)

    return c_hist
Beispiel #23
0
def preprocImage(fimg):
    nbin=64
    img=io.imread(fimg,as_grey=True)
    siz=img.shape
    msk=np.zeros(siz, np.uint8)
    rr,cc=draw.circle(siz[1]/2, siz[0]/2, (np.min(siz)/2)-3)
    msk[rr,cc]=1
    thresh=threshold_otsu(img[msk==1])
    msk1=msk&(img<=thresh)
    msk2=msk&(img>thresh)
    ret1=exposure.histogram(img[msk1==1],nbins=nbin)
    ret2=exposure.histogram(img[msk2==1],nbins=nbin)
    var1=0*np.std(img[msk1==1])
    max1=-var1+ret1[1][np.argmax(ret1[0])]
    max2=ret2[1][np.argmax(ret2[0])]
    ret=(0.8*(img-max1)/(max2-max1))
    ret[ret<0]=0
    ret[ret>1]=1
    # print np.min(ret), " * " , np.max(ret)
    return np.uint8(255*ret)
Beispiel #24
0
    def __init__(self, image_window):
        with utils.toolbar_off():
            figure = plt.figure(figsize=(6.5, 2))
        ax_hist = plt.subplot2grid((6, 1), (0, 0), rowspan=4)
        ax_low = plt.subplot2grid((6, 1), (4, 0), rowspan=1)
        ax_high = plt.subplot2grid((6, 1), (5, 0), rowspan=1)
        self.ax_hist = ax_hist

        Plugin.__init__(self, image_window, figure=figure)

        hmin, hmax = dtype_range[self.image.dtype.type]
        if hmax > 255:
            bins = int(hmax - hmin)
        else:
            bins = 256
        self.hist, self.bin_centers = histogram(self.image.data, bins)
        self.cmin = self.bin_centers[0]
        self.cmax = self.bin_centers[-1]

        # draw marker lines before histogram so they're behind histogram
        self.low_marker = self.ax_hist.axvline(self.cmin, color='w')
        self.high_marker = self.ax_hist.axvline(self.cmax, color='k')

        ax_hist.step(self.bin_centers, self.hist, color='r', lw=2, alpha=1.)
        self.ax_hist.set_xlim(self.cmin, self.cmax)
        self.ax_hist.set_xticks([])
        self.ax_hist.set_yticks([])

        slider_range = self.cmin, self.cmax
        self.slider_high = Slider(ax_high, slider_range, label='Max',
                                  value=self.cmax,
                                  on_release=self.update_image)
        self.slider_low = Slider(ax_low, slider_range, label='Min',
                                 value=self.cmin,
                                 on_release=self.update_image)
        self.slider_low.slidermax = self.slider_high
        self.slider_high.slidermin = self.slider_low

        # initialize histogram background
        imshow = self.ax_hist.imshow
        xmin, xmax, ymin, ymax = self.ax_hist.axis()
        self.black_bg = imshow(zeros((1, 2)), aspect='auto',
                               extent=(xmin, self.cmin, ymin, ymax))
        self.white_bg = imshow(ones((1, 2)), aspect='auto', vmin=0, vmax=1,
                               extent=(self.cmax, xmax, ymin, ymax))
        gradient = linspace(self.cmin, self.cmax, 256).reshape((1, 256))
        self.grad_bg = imshow(gradient, aspect='auto',
                              extent=(self.cmin, self.cmax, ymin, ymax))

        self.connect_event('key_press_event', self.on_key_press)
        self.connect_event('scroll_event', self.on_scroll)
        self.original_image = self.imgview.image.copy()
        self.update_image()
        print self.help
Beispiel #25
0
def test_loadImage():
    import matplotlib.pyplot as plt
    resistor_path = HAND_DRAWN_DIR + 'resistor1.jpg'
    img = Data.loadImage(resistor_path, square=True)
    print img
    plt.imshow(img, cmap='gray')
    plt.title("Should be Square")
    plt.show()
    hist, bins = exposure.histogram(img)
    plt.plot(bins, hist)
    plt.show()
def get_histogram(image, channel, bins=None):
    """
    Calculate histogram and bins for an image based on specification of Red, Green, Blue or Greyscale
    :params image: image for calculating histogram
    :params channel: 0 = Red, 1 = Green, 2 = Blue, 3 = Greyscale
    :return: array of bin counts, array of bins
    """
    if channel == 3:
        return expoure.histogram(image)
    else:
        return exposure.histogram(image[:, :, channel])
Beispiel #27
0
 def threshAUHist( imgIn, avg, sd ):
     pxCnt, gL = exposure.histogram( imgIn )
     auh = 0
     gli = 0 #index into pxCnt and gL
     
     while( auh < avg + sd ):
         auh += pxCnt[gli]
         gli += 1
         t = gL[gli-1]
     
     imgOut = imgProc.applyThresh( imgIn, t )
     return imgOut
Beispiel #28
0
def test_loadTrainTest():
    import matplotlib.pyplot as plt
    trX, teX, trY, teY = Data.loadTrainTest(0.8, RAND_ECOMPS_DIR)
    img = teX[0].reshape((100, 100))
    print img
    img_label = "resistor" if teY[0, 0] == 1 else "capacitor"
    plt.imshow(img, cmap='gray')
    plt.title("Should be %s" % img_label)
    plt.show()
    hist, bins = exposure.histogram(img)
    plt.plot(bins, hist)
    plt.show()
Beispiel #29
0
 def mean_exposure_hist(nbins, *images):
     """ calculates mean histogram of many exposure histograms
     args:
         nbins: number of bins
         *args: must be images (ndarrays) i.e r1, r2
     returns:
         histogram capturing pixel intensities """
     hists = []
     for img in images:
         hist, _ = exposure.histogram(img, nbins)
         hists.append(hist)
     return np.sum(hists, axis=0) / len(images)
def loadImage(filename):
    scaler = 15
    image = misc.imread(filename)
    h = []
    for channel in range(3):
        tmp = image.astype(np.float64)
        h.append(exposure.histogram(tmp[:,:,channel], nbins=10)[0])
    image = transform.resize(image, (int(scaler*2.56), int(scaler*1.53))) # small image 256px x 153px, largeimage 2592px 1552px
    image = image.flatten()
    h = np.array(h)
    h = h.flatten()
    return np.hstack((image, h))
def showHist(img):
    # An "interface" to matplotlib.axes.Axes.hist() method
    plt.figure()
    imgHist = histogram(img, nbins=256)
    bar(imgHist[1].astype(np.uint8), imgHist[0], width=0.8, align='center')
Beispiel #32
0
def test_threshold_minimum_histogram():
    camera = util.img_as_ubyte(data.camera())
    hist = histogram(camera.ravel(), 256, source_range='image')
    threshold = threshold_minimum(hist=hist)
    assert_equal(threshold, 85)
Beispiel #33
0
def build_histogram_file(in_image,
                         dest,
                         hist_type: HistogramType,
                         overwrite: bool = False):
    """
    Build an histogram for an image and save it as zarr file.
    Parameters
    ----------
    in_image : Image
        The image from which histogram has to be extracted.
    dest : Path
        The path where the histogram file will be saved.
    hist_type : HistogramType
        The type of histogram to build (FAST or COMPLETE)
    overwrite : bool (default: False)
        Whether overwrite existing histogram file at `dest` if any

    Returns
    -------
    histogram : Histogram
        The zarr histogram file in read-only mode
    """
    n_values = 2**min(in_image.significant_bits, 16)

    if in_image.n_pixels <= MAX_PIXELS_COMPLETE_HISTOGRAM:
        extract_fn = _extract_np_thumb
        hist_type = HistogramType.COMPLETE
    else:
        if hist_type == HistogramType.FAST:
            extract_fn = _extract_np_thumb
        else:
            extract_fn = in_image.tile
            raise NotImplementedError()  # TODO

    if not overwrite and dest.exists():
        raise FileExistsError(dest)

    # While the file is not fully built, we save it at a temporary location
    tmp_dest = dest.parent / Path(f"tmp_{dest.name}")
    zroot = zarr.open_group(str(tmp_dest), mode='w')
    zroot.attrs[ZHF_ATTR_TYPE] = hist_type
    zroot.attrs[ZHF_ATTR_FORMAT] = "PIMS-1.0"

    # Create the group for plane histogram
    # TODO: usa Dask to manipulate Zarr arrays (for bounds)
    #  so that we can fill the zarr array incrementally
    # https://github.com/zarr-developers/zarr-python/issues/446
    shape = (in_image.duration, in_image.depth, in_image.n_channels)
    zplane = zroot.create_group(ZHF_PER_PLANE)
    npplane_hist = np.zeros(shape=shape + (n_values, ), dtype=np.uint64)
    for data, c_range, z, t, ratio in extract_fn(in_image):
        for read, c in enumerate(c_range):
            h, _ = histogram(data[:, :, read], source_range='dtype')
            npplane_hist[t, z, c, :] += np.rint(h * ratio).astype(np.uint64)
    zplane.array(ZHF_HIST, npplane_hist)
    zplane.array(
        ZHF_BOUNDS,
        np.stack((argmin_nonzero(npplane_hist), argmax_nonzero(npplane_hist)),
                 axis=-1))

    # Create the group for channel histogram
    zchannel = zroot.create_group(ZHF_PER_CHANNEL)
    npchannel_hist = np.sum(npplane_hist, axis=(0, 1))
    zchannel.array(ZHF_HIST, npchannel_hist)
    zchannel.array(
        ZHF_BOUNDS,
        np.stack(
            (argmin_nonzero(npchannel_hist), argmax_nonzero(npchannel_hist)),
            axis=-1))

    # Create the group for image histogram
    zimage = zroot.create_group(ZHF_PER_IMAGE)
    npimage_hist = np.sum(npchannel_hist, axis=0)
    zimage.array(ZHF_HIST, npimage_hist)
    zimage.array(ZHF_BOUNDS,
                 [argmin_nonzero(npimage_hist),
                  argmax_nonzero(npimage_hist)])

    # Remove redundant data
    if in_image.duration == 1 and in_image.depth == 1:
        del zroot[ZHF_PER_PLANE]
        if in_image.n_channels == 1:
            del zroot[ZHF_PER_CHANNEL]

    # Move the zarr file (directory) to final location
    if overwrite and dest.exists():
        shutil.rmtree(dest)
    tmp_dest.replace(dest)
    return Histogram(dest, format=ZarrHistogramFormat)
Beispiel #34
0
def threshold_otsu(image, nbins=256):
    """Return threshold value based on Otsu's method.
    Parameters
    ----------
    image : (N, M) ndarray
        Grayscale input image.
    nbins : int, optional
        Number of bins used to calculate histogram. This value is ignored for
        integer arrays.
    Returns
    -------
    threshold : float
        Upper threshold value. All pixels with an intensity higher than
        this value are assumed to be foreground.
    Raises
    ------
    ValueError
         If `image` only contains a single grayscale value.
    References
    ----------
    .. [1] Wikipedia, http://en.wikipedia.org/wiki/Otsu's_Method
    Examples
    --------
    >>> from skimage.data import camera
    >>> image = camera()
    >>> thresh = threshold_otsu(image)
    >>> binary = image <= thresh
    Notes
    -----
    The input image must be grayscale.
    """
    if len(image.shape) > 2 and image.shape[-1] in (3, 4):
        msg = "threshold_otsu is expected to work correctly only for " \
              "grayscale images; image shape {0} looks like an RGB image"
        warn(msg.format(image.shape))

    # Check if the image is multi-colored or not
    if image.min() == image.max():
        raise ValueError("threshold_otsu is expected to work with images "
                         "having more than one color. The input image seems "
                         "to have just one color {0}.".format(image.min()))

    image = np.asarray([x for x in image.ravel() if x != 255])
    image = np.asarray([x for x in image.ravel() if x != 0])
    print(image.ravel())

    hist, bin_centers = histogram(image.ravel(), nbins)
    hist = hist.astype(float)

    # class probabilities for all possible thresholds
    weight1 = np.cumsum(hist)
    weight2 = np.cumsum(hist[::-1])[::-1]
    # class means for all possible thresholds
    mean1 = np.cumsum(hist * bin_centers) / weight1
    mean2 = (np.cumsum((hist * bin_centers)[::-1]) / weight2[::-1])[::-1]

    # Clip ends to align class 1 and class 2 variables:
    # The last value of `weight1`/`mean1` should pair with zero values in
    # `weight2`/`mean2`, which do not exist.
    variance12 = weight1[:-1] * weight2[1:] * (mean1[:-1] - mean2[1:])**2

    idx = np.argmax(variance12)
    threshold = bin_centers[:-1][idx]

    #threshold = 150
    return threshold
Beispiel #35
0
def test_yen_camera_image_counts():
    camera = util.img_as_ubyte(data.camera())
    counts, bin_centers = histogram(camera.ravel(), 256, source_range='image')
    assert 145 < threshold_yen(hist=counts) < 147
Beispiel #36
0
def test_isodata_camera_image_histogram():
    camera = util.img_as_ubyte(data.camera())
    hist = histogram(camera.ravel(), 256, source_range='image')
    threshold = threshold_isodata(hist=hist)
    assert threshold == 102
Beispiel #37
0
def test_int_range_image():
    im = np.array([10, 100], dtype=np.int8)
    frequencies, bin_centers = exposure.histogram(im)
    assert_equal(len(bin_centers), len(frequencies))
    assert_equal(bin_centers[0], 10)
    assert_equal(bin_centers[-1], 100)
Beispiel #38
0
def HistCues_img(greyimg, area):
    hist5 = exposure.histogram(greyimg, nbins=5)[0] / area
    hist3 = exposure.histogram(greyimg, nbins=3)[0] / area

    return hist5, hist3
Beispiel #39
0
def test_wrong_source_range():
    im = np.array([-1, 100], dtype=np.int8)
    with testing.raises(ValueError):
        frequencies, bin_centers = exposure.histogram(im,
                                                      source_range='foobar')
 def time_histogram(self):
     # Running it 10 times to achieve significant performance time.
     for i in range(10):
         result = exposure.histogram(self.image)
Beispiel #41
0
def threshold_isodata(image, nbins=256):
    """Return threshold value based on ISODATA method.

    Histogram-based threshold, known as Ridler-Calvard method or intermeans.

    Parameters
    ----------
    image : array
        Input image.
    nbins : int, optional
        Number of bins used to calculate histogram. This value is ignored for
        integer arrays.

    Returns
    -------
    threshold : float or int, corresponding input array dtype.
        Upper threshold value. All pixels intensities that less or equal of
        this value assumed as background.

    References
    ----------
    .. [1] Ridler, TW & Calvard, S (1978), "Picture thresholding using an
           iterative selection method"
    .. [2] IEEE Transactions on Systems, Man and Cybernetics 8: 630-632,
           http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=4310039
    .. [3] 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
    .. [4] ImageJ AutoThresholder code,
           http://fiji.sc/wiki/index.php/Auto_Threshold

    Examples
    --------
    >>> from skimage.data import coins
    >>> image = coins()
    >>> thresh = threshold_isodata(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]
    # It is not necessary to calculate the probability mass function here,
    # because the l and h fractions already include the normalization.
    pmf = hist.astype(np.float32)  # / hist.sum()
    cpmfl = np.cumsum(pmf, dtype=np.float32)
    cpmfh = np.cumsum(pmf[::-1], dtype=np.float32)[::-1]

    binnums = np.arange(pmf.size, dtype=np.uint8)
    # l and h contain average value of pixels in sum of bins, calculated
    # from lower to higher and from higher to lower respectively.
    l = np.ma.divide(np.cumsum(pmf * binnums, dtype=np.float32), cpmfl)
    h = np.ma.divide(
        np.cumsum((pmf[::-1] * binnums[::-1]), dtype=np.float32)[::-1],
        cpmfh)

    allmean = (l + h) / 2.0
    threshold = bin_centers[np.nonzero(allmean.round() == binnums)[0][0]]
    # This implementation returns threshold where
    # `background <= threshold < foreground`.
    return threshold
Beispiel #42
0
def findfeatures_training(filename, ploton):
    # type: (basestring, bool) -> list
    img = io.imread(filename)
    fileletter = filename[0]
    if ploton:
        print img.shape
        io.imshow(img)
        plt.title('Original Image')
        io.show()
        hist = exposure.histogram(img)
        plt.bar(hist[1], hist[0])
        plt.title('Histogram')
        plt.show()
    th = threshold_otsu(img)
    img_binary = (img < th).astype(np.double)
    if ploton:
        print th
        io.imshow(img_binary)
        plt.title('Binary Image')
        io.show()
    selem = square(1)
    dilated_img_binary = dilation(img_binary, selem)
    if ploton:
        io.imshow(dilated_img_binary)
        plt.title('closed')
        io.show()
    img_label = label(dilated_img_binary, background=0)
    if ploton:
        io.imshow(img_label)
        plt.title('Labeled Image')
        io.show()
        print np.amax(img_label)
    regions = regionprops(img_label)
    ax = plt.gca()
    if ploton:
        io.imshow(dilated_img_binary)
        plt.title('Bounding boxes')
    features = []
    count = 0
    for props in regions:
        minr, minc, maxr, maxc = props.bbox
        if maxc - minc > 9 and maxr - minr > 9:
            count += 1
            ax.add_patch(
                Rectangle((minc, minr),
                          maxc - minc,
                          maxr - minr,
                          fill=False,
                          edgecolor='red',
                          linewidth=1))
            roi = dilated_img_binary[minr:maxr, minc:maxc]
            m = moments(roi)
            cr = m[0, 1] / m[0, 0]
            cc = m[1, 0] / m[0, 0]
            mu = moments_central(roi, cr, cc)
            nu = moments_normalized(mu)
            hu = moments_hu(nu)
            features.append(hu)
            letters.append(fileletter)
    if ploton:
        print count
        io.show()
    return features
Beispiel #43
0
def test_isodata_camera_image_counts():
    camera = util.img_as_ubyte(data.camera())
    counts, bin_centers = histogram(camera.ravel(), 256, source_range='image')
    threshold = threshold_isodata(hist=counts)
    assert threshold == 102
Beispiel #44
0
def test_threshold_minimum_deprecated_max_iter_kwarg():
    camera = util.img_as_ubyte(data.camera())
    hist = histogram(camera.ravel(), 256, source_range='image')
    with expected_warnings(["`max_iter` is a deprecated argument"]):
        threshold_minimum(hist=hist, max_iter=5000)
Beispiel #45
0
import numpy as np
import matplotlib.pyplot as plt
from skimage.color import label2rgb
from skimage.exposure import histogram
from skimage.io import imread
from skimage import morphology
from skimage.filters import sobel
from scipy import ndimage as ndi

coins = imread('Cap403.bmp', as_gray=True)
hist, hist_centers = histogram(coins)

fig, axes = plt.subplots(1, 2, figsize=(8, 3))
axes[0].imshow(coins, cmap=plt.cm.gray, interpolation='nearest')
# axes[0].axis('off')
axes[1].plot(hist_centers, hist, lw=2)
axes[1].set_title('histogram of gray values')
# Region-based segmentation
# =========================
#
# We therefore try a region-based method using the watershed transform.
# First, we find an elevation map using the Sobel gradient of the image.

elevation_map = sobel(coins)

fig, ax = plt.subplots(figsize=(4, 3))
ax.imshow(elevation_map, cmap=plt.cm.gray, interpolation='nearest')
ax.set_title('elevation map')
ax.axis('off')

######################################################################
Beispiel #46
0
                labels[i, j] = 1
            else:
                ()
    return labels


plt.close('all')  # Close all remaining figures

fileList = os.listdir(os.getcwd() + '/move1-polar/')
i = 1
# Try to get a pattern from histograms

for filename in fileList:
    try:
        if filename[0] == 'D':
            im = io.imread('move1-polar/' + filename)
            im = img_as_ubyte(im)
            hist, bins = exposure.histogram(im)
            m = 1. / np.max(bins)
            bins = m * bins
            #plt.plot(bins, hist)
            labels = thresholding(im, 0.2, 0.3)
            plt.imshow(labels)
            plt.savefig('misc2/' + filename)

    except IOError:
        print(
            filename +
            ' : Not a file or not an image (IOError). This file will be skipped.'
        )
Beispiel #47
0
def get_down_up(img, thrs=(0.7, 1.0)):
    hist = exposure.histogram(img)[0]
    histmax = np.argmax(hist)
    down = histmax * thrs[0]
    up = histmax * thrs[1]
    return down, up
Beispiel #48
0
linear and non-linear filters available in skimage. We use the ``camera`` image
from ``skimage.data`` for all comparisons.

.. [1] Pierre Soille, On morphological operators based on rank filters, Pattern
       Recognition 35 (2002) 527-535, :DOI:`10.1016/S0031-3203(01)00047-4`
"""

import numpy as np
import matplotlib.pyplot as plt

from skimage.util import img_as_ubyte
from skimage import data
from skimage.exposure import histogram

noisy_image = img_as_ubyte(data.camera())
hist, hist_centers = histogram(noisy_image)

fig, ax = plt.subplots(ncols=2, figsize=(10, 5))

ax[0].imshow(noisy_image, cmap=plt.cm.gray)
ax[0].axis('off')

ax[1].plot(hist_centers, hist, lw=2)
ax[1].set_title('Histogram of grey values')

plt.tight_layout()

######################################################################
#
# Noise removal
# =============
Beispiel #49
0
from skimage.color import rgb2gray
from skimage.exposure import histogram
from matplotlib.pyplot import imread

def cum_hist(histogram):
  """Takes a histogram of length 256 with integer values as input
  and returns the cumulative histogram represented as an array
  from 0 to 255 with elements normalized from 0 to 1"""
  cum_his = np.cumsum(histogram)
  total = sum(histogram)
  normalized = cum_his / total 
  return np.round(normalized, 8)


def fix_bins(histogram_as_pair):
  (counts, bins) = histogram_as_pair
  result = [0 for i in range(256)]
  for i in range(min(bins), max(bins) + 1):
    result[i] = counts[i - min(bins)]
  return result
    

im1= imread("Images/pout.tif")
im2= rgb2gray(imread("Images/movie_flicker1.tif"))

from skimage.exposure import histogram
h1 = histogram(im1)
h2 = histogram(im2)
fix = fix_bins(h1)
result = cum_hist(fix)
Beispiel #50
0
def threshold_minimum(image, nbins=256, bias='min', max_iter=10000):
    """Return threshold value based on minimum method.

    The histogram of the input `image` is computed and smoothed until there are
    only two maxima. Then the minimum in between is the threshold value.

    Parameters
    ----------
    image : (M, N) ndarray
        Input image.
    nbins : int, optional
        Number of bins used to calculate histogram. This value is ignored for
        integer arrays.
    bias : {'min', 'mid', 'max'}, optional
        'min', 'mid', 'max' return lowest, middle, or highest pixel value
        with minimum histogram value.
    max_iter: int, optional
        Maximum number of iterations to smooth the histogram.

    Returns
    -------
    threshold : float
        Upper threshold value. All pixels with an intensity higher than
        this value are assumed to be foreground.

    Raises
    ------
    RuntimeError
        If unable to find two local maxima in the histogram or if the
        smoothing takes more than 1e4 iterations.

    References
    ----------
    .. [1] Prewitt, JMS & Mendelsohn, ML (1966), "The analysis of cell images",
           Annals of the New York Academy of Sciences 128: 1035-1053
           DOI:10.1111/j.1749-6632.1965.tb11715.x

    Examples
    --------
    >>> from skimage.data import camera
    >>> image = camera()
    >>> thresh = threshold_minimum(image)
    >>> binary = image > thresh
    """
    def find_local_maxima(hist):
        # We can't use scipy.signal.argrelmax
        # as it fails on plateaus
        maximums = list()
        direction = 1
        for i in range(hist.shape[0] - 1):
            if direction > 0:
                if hist[i + 1] < hist[i]:
                    direction = -1
                    maximums.append(i)
            else:
                if hist[i + 1] > hist[i]:
                    direction = 1
        return maximums

    if bias not in ('min', 'mid', 'max'):
        raise ValueError("Unknown bias: {0}".format(bias))

    hist, bin_centers = histogram(image.ravel(), nbins)

    smooth_hist = np.copy(hist)
    for counter in range(max_iter):
        smooth_hist = ndif.uniform_filter1d(smooth_hist, 3)
        maximums = find_local_maxima(smooth_hist)
        if len(maximums) < 3:
            break
    if len(maximums) != 2:
        raise RuntimeError('Unable to find two maxima in histogram')
    elif counter == max_iter - 1:
        raise RuntimeError('Maximum iteration reached for histogram'
                           'smoothing')

    # Find lowest point between the maxima, biased to the low end (min)
    minimum = smooth_hist[maximums[0]]
    threshold = maximums[0]
    for i in range(maximums[0], maximums[1] + 1):
        if smooth_hist[i] < minimum:
            minimum = smooth_hist[i]
            threshold = i

    if bias == 'min':
        return bin_centers[threshold]
    else:
        upper_bound = threshold
        while smooth_hist[upper_bound] == smooth_hist[threshold]:
            upper_bound += 1
        upper_bound -= 1
        if bias == 'max':
            return bin_centers[upper_bound]
        elif bias == 'mid':
            return bin_centers[(threshold + upper_bound) // 2]
Beispiel #51
0
def test_yen_camera_image_histogram():
    camera = util.img_as_ubyte(data.camera())
    hist = histogram(camera.ravel(), 256, source_range='image')
    assert 145 < threshold_yen(hist=hist) < 147
Beispiel #52
0
def threshold_isodata(image, nbins=256, return_all=False):
    """Return threshold value(s) based on ISODATA method.

    Histogram-based threshold, known as Ridler-Calvard method or inter-means.
    Threshold values returned satisfy the following equality:

    `threshold = (image[image <= threshold].mean() +`
                 `image[image > threshold].mean()) / 2.0`

    That is, returned thresholds are intensities that separate the image into
    two groups of pixels, where the threshold intensity is midway between the
    mean intensities of these groups.

    For integer images, the above equality holds to within one; for floating-
    point images, the equality holds to within the histogram bin-width.

    Parameters
    ----------
    image : (N, M) ndarray
        Input image.
    nbins : int, optional
        Number of bins used to calculate histogram. This value is ignored for
        integer arrays.
    return_all: bool, optional
        If False (default), return only the lowest threshold that satisfies
        the above equality. If True, return all valid thresholds.

    Returns
    -------
    threshold : float or int or array
        Threshold value(s).

    References
    ----------
    .. [1] Ridler, TW & Calvard, S (1978), "Picture thresholding using an
           iterative selection method"
           IEEE Transactions on Systems, Man and Cybernetics 8: 630-632,
           DOI:10.1109/TSMC.1978.4310039
    .. [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
           DOI:10.1117/1.1631315
    .. [3] ImageJ AutoThresholder code,
           http://fiji.sc/wiki/index.php/Auto_Threshold

    Examples
    --------
    >>> from skimage.data import coins
    >>> image = coins()
    >>> thresh = threshold_isodata(image)
    >>> binary = image > thresh
    """
    hist, bin_centers = histogram(image.ravel(), nbins)

    # image only contains one unique value
    if len(bin_centers) == 1:
        if return_all:
            return bin_centers
        else:
            return bin_centers[0]

    hist = hist.astype(np.float32)

    # csuml and csumh contain the count of pixels in that bin or lower, and
    # in all bins strictly higher than that bin, respectively
    csuml = np.cumsum(hist)
    csumh = np.cumsum(hist[::-1])[::-1] - hist

    # intensity_sum contains the total pixel intensity from each bin
    intensity_sum = hist * bin_centers

    # l and h contain average value of all pixels in that bin or lower, and
    # in all bins strictly higher than that bin, respectively.
    # Note that since exp.histogram does not include empty bins at the low or
    # high end of the range, csuml and csumh are strictly > 0, except in the
    # last bin of csumh, which is zero by construction.
    # So no worries about division by zero in the following lines, except
    # for the last bin, but we can ignore that because no valid threshold
    # can be in the top bin. So we just patch up csumh[-1] to not cause 0/0
    # errors.
    csumh[-1] = 1
    l = np.cumsum(intensity_sum) / csuml
    h = (np.cumsum(intensity_sum[::-1])[::-1] - intensity_sum) / csumh

    # isodata finds threshold values that meet the criterion t = (l + m)/2
    # where l is the mean of all pixels <= t and h is the mean of all pixels
    # > t, as calculated above. So we are looking for places where
    # (l + m) / 2 equals the intensity value for which those l and m figures
    # were calculated -- which is, of course, the histogram bin centers.
    # We only require this equality to be within the precision of the bin
    # width, of course.
    all_mean = (l + h) / 2.0
    bin_width = bin_centers[1] - bin_centers[0]

    # Look only at thresholds that are below the actual all_mean value,
    # for consistency with the threshold being included in the lower pixel
    # group. Otherwise can get thresholds that are not actually fixed-points
    # of the isodata algorithm. For float images, this matters less, since
    # there really can't be any guarantees anymore anyway.
    distances = all_mean - bin_centers
    thresholds = bin_centers[(distances >= 0) & (distances < bin_width)]

    if return_all:
        return thresholds
    else:
        return thresholds[0]
Beispiel #53
0
def test_flat_int_range_dtype():
    im = np.linspace(-128, 128, 256, dtype=np.int8)
    frequencies, bin_centers = exposure.histogram(im, source_range='dtype')
    assert_array_equal(bin_centers, np.arange(-128, 128))
    assert_equal(frequencies.shape, (256, ))
Beispiel #54
0
def test_threshold_minimum_counts():
    camera = util.img_as_ubyte(data.camera())
    counts, bin_centers = histogram(camera.ravel(), 256, source_range='image')
    threshold = threshold_minimum(hist=counts)
    assert_equal(threshold, 85)
Beispiel #55
0
# variance between the two segmented groups of pixels. Therefore, it is can be
# interpreted as a **clustering** algorithm. Samples are pixels and have a
# single feature, which is their grayscale value.



# <codecell>

from skimage import data, exposure, filters
camera = data.camera()   



# <codecell>

hi = exposure.histogram(camera)   



# <codecell>

val = filters.threshold_otsu(camera)   



# <codecell>

fig, axes = plt.subplots(1, 2)
axes[0].imshow(camera, cmap='gray')
axes[0].contour(camera, [val], colors='y')
axes[1].plot(hi[1], hi[0])
Beispiel #56
0
def test_peak_float_out_of_range_image():
    im = np.array([10, 100], dtype=np.float16)
    frequencies, bin_centers = exposure.histogram(im, nbins=90)
    # offset values by 0.5 for float...
    assert_array_equal(bin_centers, np.arange(10, 100) + 0.5)
from skimage import data, exposure, img_as_float, img_as_ubyte
import matplotlib.pyplot as plt

image = img_as_float(data.camera())
image_uint8 = img_as_ubyte(data.camera())

hi = exposure.histogram(image_uint8)
cdf = exposure.cumulative_distribution(image_uint8)

plt.figure(1)

plt.subplot(1, 2, 1)
plt.imshow(image_uint8, cmap='gray')
plt.title('Sample Image')

plt.subplot(1, 2, 2)
plt.bar(hi[1], hi[0])
plt.hold(True)
plt.plot(cdf[1], cdf[0] * 6400, 'r')
plt.hold(False)
plt.title('Histogram and CDF')
plt.xlabel('Pixel Intensity')

plt.show()
Beispiel #58
0
def histo(img, bins):
    return exposure.histogram(img, nbins=bins)
Beispiel #59
0
def threshold_triangle(image, nbins=256):
    """Return threshold value based on the triangle algorithm.

    Parameters
    ----------
    image : (N, M[, ..., P]) ndarray
        Grayscale input image.
    nbins : int, optional
        Number of bins used to calculate histogram. This value is ignored for
        integer arrays.

    Returns
    -------
    threshold : float
        Upper threshold value. All pixels with an intensity higher than
        this value are assumed to be foreground.

    References
    ----------
    .. [1] Zack, G. W., Rogers, W. E. and Latt, S. A., 1977,
       Automatic Measurement of Sister Chromatid Exchange Frequency,
       Journal of Histochemistry and Cytochemistry 25 (7), pp. 741-753
       DOI:10.1177/25.7.70454
    .. [2] ImageJ AutoThresholder code,
       http://fiji.sc/wiki/index.php/Auto_Threshold

    Examples
    --------
    >>> from skimage.data import camera
    >>> image = camera()
    >>> thresh = threshold_triangle(image)
    >>> binary = image > thresh
    """
    # nbins is ignored for integer arrays
    # so, we recalculate the effective nbins.
    hist, bin_centers = histogram(image.ravel(), nbins)
    nbins = len(hist)

    # Find peak, lowest and highest gray levels.
    arg_peak_height = np.argmax(hist)
    peak_height = hist[arg_peak_height]
    arg_low_level, arg_high_level = np.where(hist > 0)[0][[0, -1]]

    # Flip is True if left tail is shorter.
    flip = arg_peak_height - arg_low_level < arg_high_level - arg_peak_height
    if flip:
        hist = hist[::-1]
        arg_low_level = nbins - arg_high_level - 1
        arg_peak_height = nbins - arg_peak_height - 1

    # If flip == True, arg_high_level becomes incorrect
    # but we don't need it anymore.
    del (arg_high_level)

    # Set up the coordinate system.
    width = arg_peak_height - arg_low_level
    x1 = np.arange(width)
    y1 = hist[x1 + arg_low_level]

    # Normalize.
    norm = np.sqrt(peak_height**2 + width**2)
    peak_height /= norm
    width /= norm

    # Maximize the length.
    # The ImageJ implementation includes an additional constant when calculating
    # the length, but here we omit it as it does not affect the location of the
    # minimum.
    length = peak_height * x1 - width * y1
    arg_level = np.argmax(length) + arg_low_level

    if flip:
        arg_level = nbins - arg_level - 1

    return bin_centers[arg_level]
Beispiel #60
0
def vector_hist(image, nbins):
    vctr, b = exposure.histogram(img_as_float(image), nbins=nbins)
    out = vctr
    out = out / max(out)
    return out