Exemplo n.º 1
0
def analyze_im_for_features(fn, show=True, show_now=True):
    mask_fn = fn.replace('.%s' % (fn.split('.')[-1]), '_mask.%s' % (fn.split('.')[-1]))
    im = cv2.imread(fn, 0)
    ims = tools.smoothing(im, d=10, sigmaColor=50, sigmaSpace=10)
    mask = cv2.imread(mask_fn, 0) > 0
    pts = ims[np.nonzero(mask)]

    # fuz.fcm(ims, mask=mask, n_clusters=2, show=True)
    # color_clustering(ims, mask=mask, k=2)

    hist, bins = skiexp.histogram(pts)
    glcm = tools.graycomatrix_3D(ims, mask=mask)
    # glcm *= glcm > 3

    # glcm_p = glcm > (0.4 * glcm.max())
    glcm_p = glcm > 2 * (glcm[np.nonzero(glcm)].mean())
    # glcm_p = glcm > (np.median(glcm[np.nonzero(glcm)]))
    glcm_pts = np.nonzero(glcm_p)
    width = glcm_pts[1].max() - glcm_pts[1].min()

    plt.figure()
    plt.subplot(121), plt.imshow(glcm)
    plt.subplot(122), plt.imshow(glcm_p, 'gray')
    # plt.show()

    mu, std = scista.norm.fit(pts.flatten())
    # b = scista.norm.pdf(bins, mu, std)
    # k = hist.max() / b.max()
    # plt.figure()
    # plt.plot(bins, hist, 'b-')
    # plt.plot(bins, k * b, 'r-')
    # plt.show()

    if show:
        plt.figure()
        plt.suptitle('std=%.2f, width=%i' % (std, width))
        plt.subplot(131), plt.imshow(skiseg.mark_boundaries(im, mask, color=(1,0,0), mode='thick'), 'gray', interpolation='nearest')
        # plt.subplot(142), plt.imshow(mask, 'gray', interpolation='nearest')
        plt.subplot(132), plt.plot(bins, hist, 'b-')
        plt.xlim([0, 255])
        plt.subplot(133), plt.imshow(glcm, interpolation='nearest')#, vmax=5 * glcm.mean())
        if show_now:
            plt.show()

    return bins, hist, glcm
Exemplo n.º 2
0
def glcm_meanshift(glcm):
    print 'calculating glcm ...',
    mask = (img > 0) * (img < 255)
    glcm = tools.graycomatrix_3D(img, mask=mask)
    print 'done'

    print 'preparing data ...',
    data = data_from_glcm(glcm)
    print 'done'

    print 'estimating bandwidth ...',
    bandwidth = estimate_bandwidth(data, quantile=0.08, n_samples=2000)
    print 'done'

    print 'fitting mean shift ...',
    ms = MeanShift(bandwidth=bandwidth, bin_seeding=True)
    # ms = MeanShift()
    ms.fit(data)
    labels = ms.labels_
    cluster_centers = ms.cluster_centers_
    print 'done'

    labels_unique = np.unique(labels)
    n_clusters_ = len(labels_unique)

    print 'number of estimated clusters : %d' % n_clusters_
    print 'cluster centers :', cluster_centers

    y_pred = ms.predict(data)
    glcm_labs = np.zeros(glcm.shape, dtype=np.uint8)
    for x, y in zip(data, y_pred):
        glcm_labs[tuple(x)] = int(y + 1)

    inds = np.argsort(ms.cluster_centers_.mean(axis=1))
    glcm_labs2 = glcm_labs.copy()
    for i, l in enumerate(inds):
        glcm_labs2 = np.where(glcm_labs == l + 1, i + 1, glcm_labs2)

    # plt.figure()
    # plt.subplot(121), plt.imshow(glcm_labs)
    # plt.subplot(122), plt.imshow(glcm_labs2)

    glcm_labs = glcm_labs2

    labint = ms.predict(np.vstack((range(0, 256), range(0, 256))).T)
    labim = labint[img.flatten()].reshape(img.shape)
    # labim += 10
    labim2 = labim.copy()
    for i, l in enumerate(inds):
        labim2 = np.where(labim == l, i + 1, labim2)
    labim = labim2

    labim_f = scindifil.median_filter(labim, size=3)
    # plt.figure()
    # plt.subplot(131), plt.imshow(img, 'gray', interpolation='nearest'), plt.axis('off')
    # plt.subplot(132), plt.imshow(labim, 'jet', interpolation='nearest'), plt.axis('off')
    # plt.subplot(133), plt.imshow(labim_f, 'jet', interpolation='nearest'), plt.axis('off')
    # plt.show()

    # deriving seeds
    # int_labels = []
    # for x in range(256):
    #     int_labels.append(ms.predict(np.array([[x, x]])))
    # seeds = np.array(int_labels)[img.flatten()].reshape(img.shape)
    # seeds_f = scindifil.median_filter(seeds, size=3)

    plt.figure()
    plt.subplot(131), plt.imshow(img, 'gray',
                                 interpolation='nearest'), plt.axis('off')
    plt.subplot(132), plt.imshow(labim, 'jet', interpolation='nearest',
                                 vmin=0), plt.axis('off')
    plt.subplot(133), plt.imshow(labim_f,
                                 'jet',
                                 interpolation='nearest',
                                 vmin=0), plt.axis('off')

    plt.figure()
    plt.subplot(121), plt.imshow(glcm, 'jet', interpolation='nearest',
                                 vmin=0), plt.axis('off')
    for c in ms.cluster_centers_:
        plt.plot(c[0],
                 c[1],
                 'o',
                 markerfacecolor='w',
                 markeredgecolor='k',
                 markersize=12)
    plt.subplot(122), plt.imshow(glcm_labs,
                                 'jet',
                                 interpolation='nearest',
                                 vmin=0), plt.axis('off')
    for c in ms.cluster_centers_:
        plt.plot(c[0],
                 c[1],
                 'o',
                 markerfacecolor='w',
                 markeredgecolor='k',
                 markersize=12)

    # visualization
    # plt.figure()
    # plt.subplot(131), plt.imshow(img, 'gray'), plt.axis('off')
    # plt.subplot(132), plt.imshow(seeds, 'jet', interpolation='nearest'), plt.axis('off')
    # plt.subplot(133), plt.imshow(seeds_f, 'jet', interpolation='nearest'), plt.axis('off')
    #
    # plt.figure()
    # plt.subplot(121), plt.imshow(glcm, 'jet')
    # for c in cluster_centers:
    #     plt.plot(c[0], c[1], 'o', markerfacecolor='w', markeredgecolor='k', markersize=8)
    # plt.axis('image')
    # plt.axis('off')
    # plt.subplot(122), plt.imshow(glcm, 'jet')
    # colors = itertools.cycle('bgrcmykbgrcmykbgrcmykbgrcmyk')
    # for k, col in zip(range(n_clusters_), colors):
    #     my_members = labels == k
    #     cluster_center = cluster_centers[k]
    #     plt.plot(data[my_members, 0], data[my_members, 1], col + '.')
    #     plt.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor='w', markeredgecolor='k', markersize=8)
    # plt.title('Estimated number of clusters: %d' % n_clusters_)
    # plt.axis('image')
    # plt.axis('off')

    plt.show()
Exemplo n.º 3
0
def glcm_dpgmm(img):
    # deriving glcm
    mask = (img > 0) * (img < 255)
    glcm = tools.graycomatrix_3D(img, mask=mask)

    # inds = tuple(inds.flatten())

    # processing glcm
    # glcm_gc = skimor.closing(glcm, selem=skimor.disk(1))
    # glcm_go = skimor.opening(glcm, selem=skimor.disk(1))

    # plt.figure()
    # plt.subplot(131), plt.imshow(glcm, 'gray', interpolation='nearest'), plt.title('glcm')
    # plt.subplot(132), plt.imshow(glcm_gc, 'gray', interpolation='nearest'), plt.title('glcm_gc')
    # plt.subplot(133), plt.imshow(glcm_go, 'gray', interpolation='nearest'), plt.title('glcm_go')

    # thresholding glcm
    c_t = 4
    thresh = c_t * np.mean(glcm)
    glcm_t = glcm > thresh
    glcm_to = skimor.binary_closing(glcm_t, selem=skimor.disk(3))
    glcm_to = skimor.binary_opening(glcm_to, selem=skimor.disk(3))
    # tools.blob_from_gcm(glcm_to, img, return_rvs=True, show=True, show_now=False)
    #
    # labs_im, num = skimea.label(glcm_to, return_num=True)
    #
    # labels = np.unique(labs_im)[1:]
    # for l in labels:
    #     tmp = glcm * (labs_im == l)
    #     fit_mixture(tmp, n_components=0, type='gmm')

    # syntetic glcm
    # glcm = np.array([[0,1,1,2,0,0,0,0],
    #                  [1,2,2,3,1,0,0,1],
    #                  [1,3,4,2,1,0,0,0],
    #                  [0,1,3,1,0,0,0,1],
    #                  [1,0,0,0,0,0,1,3],
    #                  [0,2,0,0,0,2,2,1],
    #                  [0,0,0,0,1,3,4,0],
    #                  [0,0,0,0,1,2,0,0]])

    # dpgmm
    glcm_o = glcm.copy()
    # glcm = glcm_go * glcm_to
    # glcm = glcm_go
    # glcm = glcm_gc
    glcm = glcm * glcm_to
    data = data_from_glcm(glcm)

    # fitting DPGMM
    # print 'fitting DPGMM ...'
    # types = ['spherical', 'tied', 'diag', 'full']
    # n_comps = range(2, 11)
    # # n_comps = range(2, 4)
    # aics = np.zeros((len(types), len(n_comps)))
    # bics = np.zeros((len(types), len(n_comps)))
    # scores = np.zeros((len(types), len(n_comps)))
    # for i, type in enumerate(types):
    #     print '\nTYPE:', type
    #     for j, n in enumerate(n_comps):
    #         # dpgmm = mixture.DPGMM(n_components=6, covariance_type='tied', alpha=0.100)
    #         dpgmm = mixture.GMM(n_components=n, covariance_type=type)
    #         dpgmm.fit(data)
    #         aic = dpgmm.aic(data)
    #         bic = dpgmm.bic(data)
    #         score = dpgmm.score(data).mean()
    #         # aics.append(aic)
    #         # bics.append(bic)
    #         # scores.append(score)
    #         aics[i, j] = aic
    #         bics[i, j] = bic
    #         scores[i, j] = score
    #         print 'n_comps=%i, score=%.2f, aic=%.2f, bic=%.2f' % (n, score, aic, bic)
    #
    # plt.figure()
    # color_iter = itertools.cycle(['r', 'g', 'b', 'c', 'm', 'y', 'k'])
    # for aic, color in zip(aics, color_iter):
    #     plt.plot(n_comps, aic, color + '-')
    # plt.legend(types)
    # plt.title('aic')
    #
    # plt.figure()
    # color_iter = itertools.cycle(['r', 'g', 'b', 'c', 'm', 'y', 'k'])
    # for bic, color in zip(bics, color_iter):
    #     plt.plot(n_comps, bic, color + '-')
    # plt.legend(types)
    # plt.title('bic')
    #
    # plt.figure()
    # color_iter = itertools.cycle(['r', 'g', 'b', 'c', 'm', 'y', 'k'])
    # for score, color in zip(scores, color_iter):
    #     plt.plot(n_comps, score, color + '-')
    # plt.legend(types)
    # plt.title('scores')

    print 'fitting DPGMM ...',
    # dpgmm = mixture.GMM(n_components=3, covariance_type='tied')
    dpgmm = mixture.DPGMM(n_components=6, covariance_type='tied', alpha=1.)
    dpgmm.fit(data)
    print 'done'
    print 'means:'
    print dpgmm.means_

    # dpgmm = mixture.GMM(n_components=3, covariance_type='tied')
    # dpgmm.fit(data)
    # print 'n_comps=3, score=%.2f, aic=%.2f, bic=%.2f' % (dpgmm.score(data).mean(), dpgmm.aic(data), dpgmm.bic(data))
    # dpgmm = mixture.GMM(n_components=4, covariance_type='tied')
    # dpgmm.fit(data)
    # print 'n_comps=4, score=%.2f, aic=%.2f, bic=%.2f' % (dpgmm.score(data).mean(), dpgmm.aic(data), dpgmm.bic(data))
    # dpgmm = mixture.GMM(n_components=5, covariance_type='tied')
    # dpgmm.fit(data)
    # print 'n_comps=5, score=%.2f, aic=%.2f, bic=%.2f' % (dpgmm.score(data).mean(), dpgmm.aic(data), dpgmm.bic(data))

    # predicting DPGMM
    print 'predicting DPGMM ...',
    data = data_from_glcm(glcm_o)
    y_pred = dpgmm.predict(data)
    glcm_labs = np.zeros(glcm.shape, dtype=np.uint8)
    for x, y in zip(data, y_pred):
        glcm_labs[tuple(x)] = int(y + 1)
    print 'done'

    # glcm_labs += 10
    inds = np.argsort(dpgmm.means_.mean(axis=1))
    glcm_labs2 = glcm_labs.copy()
    for i, l in enumerate(inds):
        glcm_labs2 = np.where(glcm_labs == l + 1, i + 1, glcm_labs2)
    glcm_labs = glcm_labs2
    # glcm_labs3 = inds[glcm_labs.flatten()].reshape(glcm_labs.shape)

    # plt.figure()
    # plt.subplot(121), plt.imshow(glcm_labs)
    # plt.subplot(122), plt.imshow(glcm_labs2)
    # plt.show()

    labint = dpgmm.predict(np.vstack((range(0, 256), range(0, 256))).T)
    labim = labint[img.flatten()].reshape(img.shape)
    # labim += 10
    labim2 = labim.copy()
    for i, l in enumerate(inds):
        labim2 = np.where(labim == l, i + 1, labim2)
    labim = labim2
    # labim3 = inds[labim.flatten()].reshape(labim.shape)
    # plt.figure()
    # plt.subplot(121), plt.imshow(labim)
    # plt.subplot(122), plt.imshow(labim2)
    # # plt.subplot(133), plt.imshow(labim3)
    # plt.show()

    labim_f = scindifil.median_filter(labim, size=3)
    plt.figure()
    plt.subplot(131), plt.imshow(img, 'gray',
                                 interpolation='nearest'), plt.axis('off')
    plt.subplot(132), plt.imshow(labim, 'jet', interpolation='nearest',
                                 vmin=0), plt.axis('off')
    plt.subplot(133), plt.imshow(labim_f,
                                 'jet',
                                 interpolation='nearest',
                                 vmin=0), plt.axis('off')

    plt.figure()
    plt.subplot(121), plt.imshow(glcm_o,
                                 'jet',
                                 interpolation='nearest',
                                 vmin=0), plt.axis('off')
    for c in dpgmm.means_:
        plt.plot(c[0],
                 c[1],
                 'o',
                 markerfacecolor='w',
                 markeredgecolor='k',
                 markersize=12)
    plt.subplot(122), plt.imshow(glcm_labs,
                                 'jet',
                                 interpolation='nearest',
                                 vmin=0), plt.axis('off')
    for c in dpgmm.means_:
        plt.plot(c[0],
                 c[1],
                 'o',
                 markerfacecolor='w',
                 markeredgecolor='k',
                 markersize=12)

    plt.show()
Exemplo n.º 4
0
def initialize_graycom_deprecated(
        data,
        slice=None,
        distances=[
            1,
        ],
        scale=0.5,
        angles=[0, np.pi / 4, np.pi / 2, 3 * np.pi / 4],
        symmetric=False,
        c_t=5,
        show=False,
        show_now=True):
    if scale != 1:
        data = tools.resize3D(data, scale, sliceId=0)

    # computing gray co-occurence matrix
    print 'Computing gray co-occurence matrix ...',
    if data.ndim == 2:
        gcm = skifea.greycomatrix(data, distances, angles, symmetric=symmetric)
        # summing over distances and directions
        gcm = gcm.sum(axis=3).sum(axis=2)
    else:
        gcm = tools.graycomatrix_3D(data, connectivity=1)
    print 'done'

    # plt.figure()
    # plt.subplot(121), plt.imshow(gcm, 'jet', vmax=10 * gcm.mean())
    # plt.subplot(122), plt.imshow(gcm2, 'jet', vmax=10 * gcm.mean())
    # plt.show()

    # ----
    # gcm2 = skifea.greycomatrix(data[10,...], distances, angles, symmetric=symmetric).sum(axis=3).sum(axis=2)
    # plt.figure()
    # plt.subplot(121), plt.imshow(gcm, 'jet', vmax=10 * gcm.mean()), plt.title('3D gcm')
    # plt.subplot(122), plt.imshow(gcm2, 'jet', vmax=10 * gcm2.mean()), plt.title('gcm of a slice')
    # plt.show()
    # ----

    # plt.figure()
    # thresh = np.mean(gcm)
    # ts = (thresh * np.array([1, 3, 6, 9, 12])).astype(int)
    # for i, t in enumerate(ts):
    #     plt.subplot(100 + 10 * len(ts) + i + 1)
    #     plt.imshow(gcm > t, 'gray')
    #     plt.title('t = %i' % t)
    # plt.show()

    # thresholding graycomatrix (GCM)
    thresh = c_t * np.mean(gcm)
    gcm_t = gcm > thresh
    gcm_to = skimor.binary_opening(gcm_t, selem=skimor.disk(3))

    # find peaks in the GCM and return them as random variables
    rvs = analyze_glcm(gcm_to)

    if slice is not None:
        data = data[slice, ...]

    # deriving seed points
    seeds = np.zeros(data.shape, dtype=np.uint8)
    best_probs = np.zeros(
        data.shape
    )  # assign the most probable label if more than one are possible
    for i, rv in enumerate(rvs):
        probs = rv.pdf(data)
        s = probs > probs.mean()  # probability threshold
        # sfh = skimor.remove_small_holes(s, min_size=0.1 * s.sum(), connectivity=2)
        s = tools.fill_holes_watch_borders(s)
        # s = skimor.binary_opening(s, selem=skimor.disk(3))
        # plt.figure()
        # plt.subplot(131), plt.imshow(s, 'gray')
        # plt.subplot(132), plt.imshow(sfh, 'gray')
        # plt.subplot(133), plt.imshow(sfh2, 'gray')
        # plt.show()
        s = np.where((probs * s) > (best_probs * s), i + 1,
                     s)  # assign new label only if its probability is higher
        best_probs = np.where(s, probs, best_probs)  # update best probs
        seeds = np.where(s, i + 1, seeds)  # update seeds

    # # running Grow cut
    # gc = growcut.GrowCut(data, seeds, smooth_cell=False, enemies_T=0.7)
    # gc.run()
    #
    # postprocessing labels
    # labs = gc.get_labeled_im().astype(np.uint8)[0,...]
    # labs_f = scindifil.median_filter(labs, size=5)
    labs_f = scindifil.median_filter(seeds, size=3)

    # plt.figure()
    # plt.subplot(131), plt.imshow(gcm, 'gray', vmax=gcm.mean()), plt.title('gcm')
    # plt.subplot(132), plt.imshow(gcm_t, 'gray'), plt.title('thresholded')
    # plt.subplot(133), plt.imshow(gcm_to, 'gray'), plt.title('opened')
    #
    # plt.figure()
    # plt.subplot(121), plt.imshow(data, 'gray', interpolation='nearest'), plt.title('input')
    # plt.subplot(122), plt.imshow(seeds, 'jet', interpolation='nearest'), plt.title('seeds')
    # divider = make_axes_locatable(plt.gca())
    # cax = divider.append_axes('right', size='5%', pad=0.05)
    # plt.colorbar(cax=cax, ticks=np.unique(seeds))

    # plt.figure()
    # plt.subplot(141), plt.imshow(data, 'gray'), plt.title('input')
    # plt.subplot(142), plt.imshow(labs_f, 'gray'), plt.title('labels')
    # plt.subplot(143), plt.imshow(liver_blob, 'gray'), plt.title('liver blob')
    # plt.subplot(144), plt.imshow(init_mask, 'gray'), plt.title('init mask')

    # finding liver blob
    liver_blob = find_liver_blob(data,
                                 labs_f,
                                 slice=slice,
                                 show=show,
                                 show_now=show_now)

    # hole filling - adding (and then removing) a capsule of zeros, otherwise it'd fill holes touching image borders
    init_mask = tools.fill_holes_watch_borders(liver_blob)
    # init_mask = np.zeros([x + 2 for x in liver_blob.shape], dtype=np.uint8)
    # if liver_blob.ndim == 3:
    #     for i, im in enumerate(liver_blob):
    #         init_mask[i + 1, 1:-1, 1:-1] = im
    # else:
    #     init_mask[1:-1, 1:-1] = liver_blob
    # init_mask = skimor.remove_small_holes(init_mask, min_size=0.1 * liver_blob.sum(), connectivity=2)
    # if liver_blob.ndim == 3:
    #     init_mask = init_mask[1:-1, 1:-1, 1:-1]
    # else:
    #     init_mask = init_mask[1:-1, 1:-1]

    # visualization
    if show:
        if slice is None:
            slice = 0
        data_vis = data if data.ndim == 2 else data[slice, ...]
        seeds_vis = seeds if data.ndim == 2 else seeds[slice, ...]
        labs_f_vis = labs_f if data.ndim == 2 else labs_f[slice, ...]
        liver_blob_vis = liver_blob if data.ndim == 2 else liver_blob[slice,
                                                                      ...]
        init_mask_vis = init_mask if data.ndim == 2 else init_mask[slice, ...]

        plt.figure()
        plt.subplot(131), plt.imshow(gcm, 'gray',
                                     vmax=gcm.mean()), plt.title('gcm')
        plt.subplot(132), plt.imshow(gcm_t, 'gray'), plt.title('thresholded')
        plt.subplot(133), plt.imshow(gcm_to, 'gray'), plt.title('opened')

        plt.figure()
        plt.subplot(121), plt.imshow(
            data_vis, 'gray', interpolation='nearest'), plt.title('input')
        plt.subplot(122), plt.imshow(
            seeds_vis, 'jet', interpolation='nearest'), plt.title('seeds')
        divider = make_axes_locatable(plt.gca())
        cax = divider.append_axes('right', size='5%', pad=0.05)
        plt.colorbar(cax=cax, ticks=np.unique(seeds))

        plt.figure()
        plt.subplot(141), plt.imshow(data_vis, 'gray'), plt.title('input')
        plt.subplot(142), plt.imshow(labs_f_vis, 'gray'), plt.title('labels')
        plt.subplot(143), plt.imshow(liver_blob_vis,
                                     'gray'), plt.title('liver blob')
        plt.subplot(144), plt.imshow(init_mask_vis,
                                     'gray'), plt.title('init mask')

        if show_now:
            plt.show()

    return data, init_mask
Exemplo n.º 5
0
def blob_from_glcm(data, show=False, show_now=True, min_int=0, max_int=255):
    data = tools.windowing(data, sliceId=0)
    data_f = tools.resize_ND(data, scale=0.1).astype(np.uint8)
    data_f = tools.smoothing(data_f, sliceId=0)

    min_interval = int((0 + 125) / 350. * 255)
    max_interval = int((100 + 125) / 350. * 255)
    # min_int = 20
    # max_int = 80

    print 'calculating glcm ...',
    glcm = tools.graycomatrix_3D(data_f)
    print 'done'

    glcm_rec = glcm.copy()
    mask = np.zeros_like(glcm_rec)
    mask[min_interval:max_interval, min_interval:max_interval] = 1
    glcm_rec *= mask
    max_r, max_c = np.unravel_index(np.argmax(glcm_rec), glcm_rec.shape)
    glcm_ind = (max_r + max_c) / 2

    glcm_hu = glcm_ind / 255 * 350 - 125
    print 'glcm ind: %.1f = %i HU' % (glcm_ind, int(glcm_hu))

    img = data[21, ...]

    if show:
        plt.figure()
        plt.subplot(121), plt.imshow(glcm,
                                     interpolation='nearest',
                                     vmax=5 * glcm.mean())
        plt.subplot(122), plt.imshow(glcm,
                                     interpolation='nearest',
                                     vmax=5 * glcm.mean())
        plt.plot((min_interval, min_interval), (min_interval, max_interval),
                 'm-',
                 lw=5)
        plt.plot((min_interval, max_interval), (max_interval, max_interval),
                 'm-',
                 lw=5)
        plt.plot((max_interval, max_interval), (max_interval, min_interval),
                 'm-',
                 lw=5)
        plt.plot((max_interval, min_interval), (min_interval, min_interval),
                 'm-',
                 lw=5)
        plt.plot(max_c, max_r, 'wo', markersize=12)
        plt.axis('image')

        glcm_diff = abs(img.astype(np.int64) - glcm_ind)
        plt.figure()
        plt.subplot(121), plt.imshow(img, 'gray',
                                     interpolation='nearest'), plt.axis('off')
        plt.subplot(122), plt.imshow(glcm_diff,
                                     'gray',
                                     interpolation='nearest'), plt.axis('off')

        if show_now:
            plt.show()

    return glcm_ind
Exemplo n.º 6
0
def conspicuity_int_glcm(im,
                         mask=None,
                         use_sigmoid=False,
                         morph_proc=True,
                         type='hypo',
                         a=3):
    # im = tools.resize_ND(im, scale=0.5)
    # mask = tools.resize_ND(mask, scale=0.5)
    im = im.copy()
    if mask is None:
        mask = np.ones_like(im)

    if im.max() <= 1:
        im = skiexp.rescale_intensity(im, (0, 1), (0, 255)).astype(np.int)

    glcm = tools.graycomatrix_3D(im, mask=mask)

    min_num = 2 * glcm.mean()
    glcm = np.where(glcm < min_num, 0, glcm)
    diag = np.ones(glcm.shape)
    k = 20
    tu = np.triu(diag, -k)
    tl = np.tril(diag, k)
    diag = tu * tl
    glcm *= diag.astype(glcm.dtype)

    # print 'data from glcm ...',
    data = tools.data_from_glcm(glcm)
    quantiles = [0.2, 0.1, 0.4]
    n_clusters_ = 0
    for q in quantiles:
        # print 'estimating bandwidth ...',
        bandwidth = estimate_bandwidth(data, quantile=q, n_samples=2000)
        if bandwidth == 0:
            continue
        # bandwidth = estimate_bandwidth(data, quantile=0.1, n_samples=2000)
        # print 'meanshift ...',
        ms = MeanShift(bandwidth=bandwidth,
                       bin_seeding=True)  #, min_bin_freq=1000)
        ms.fit(data)
        labels = ms.labels_
        cluster_centers = ms.cluster_centers_
        n_clusters_ = len(np.unique(labels))
        # print q, n_clusters_

        if n_clusters_ > 1:
            break

    # n_clusters_ = 0
    if n_clusters_ > 1:
        # print 'number of estimated clusters : %d' % n_clusters_
        # print 'cluster centers: {}'.format(cluster_centers)
        lab_im = (1 + ms.predict(
            np.array(np.vstack(
                (im.flatten(), im.flatten()))).T).reshape(im.shape)) * mask
    else:  # pokud meanshift najde pouze jeden mode, pouziji jiny pristup
        rvs = tools.analyze_glcm(glcm)
        rvs = sorted(rvs, key=lambda rv: rv.mean())
        lab_im = rvs[0].pdf(im)
        n_clusters_ = len(rvs)

    mean_v = im[np.nonzero(mask)].mean()
    labs = np.unique(lab_im)[1:]
    res = np.zeros_like(lab_im)
    for l in labs:
        tmp = lab_im == l
        mv = im[np.nonzero(tmp)].mean()
        if mv < mean_v:
            res = np.where(tmp, 1, res)

    # plt.figure()
    # plt.subplot(121), plt.imshow(glcm, 'jet')
    # for c in cluster_centers:
    #     plt.plot(c[0], c[1], 'o', markerfacecolor='w', markeredgecolor='k', markersize=8)
    # plt.axis('image')
    # plt.axis('off')
    # plt.subplot(122), plt.imshow(glcm, 'jet')
    # colors = itertools.cycle('bgrcmykbgrcmykbgrcmykbgrcmyk')
    # for k, col in zip(range(n_clusters_), colors):
    #     my_members = labels == k
    #     cluster_center = cluster_centers[k]
    #     plt.plot(data[my_members, 0], data[my_members, 1], col + '.')
    #     plt.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor='w', markeredgecolor='k', markersize=8)
    # plt.title('Estimated number of clusters: %d' % n_clusters_)
    # plt.axis('image')
    # plt.axis('off')
    # plt.show()

    # plt.figure()
    # plt.subplot(131), plt.imshow(im, 'gray', interpolation='nearest')
    # plt.subplot(132), plt.imshow(lab_im, 'jet', interpolation='nearest')
    # plt.subplot(133), plt.imshow(res, 'gray', interpolation='nearest')
    # plt.show()

    # thresholding graycomatrix (GCM)
    # c_t = 5
    # thresh = c_t * np.mean(glcm)
    # glcm_t = glcm > thresh
    # glcm_to = skimor.binary_opening(glcm_t, selem=skimor.disk(3))
    #
    # rvs = tools.analyze_glcm(glcm_to)

    # filtering
    # rvs = sorted(rvs, key=lambda rv: rv.mean())
    # im_int = rvs[0].pdf(im)
    # mean_v = rvs[0].mean()

    im_int = res

    a = 20
    c = mean_v / 255
    im_res = conspicuity_processing(im_int,
                                    mask,
                                    use_sigmoid=use_sigmoid,
                                    a=a,
                                    c=c,
                                    sigm_t=0.2,
                                    use_morph=morph_proc,
                                    radius=3)

    return im_res