示例#1
0
def test_color():
    rnd = np.random.RandomState(0)
    img = np.zeros((20, 21, 3))
    img[:10, :10, 0] = 1
    img[10:, :10, 1] = 1
    img[10:, 10:, 2] = 1
    img += 0.01 * rnd.normal(size=img.shape)
    img[img > 1] = 1
    img[img < 0] = 0
    seg = quickshift(img, random_seed=0, max_dist=30, kernel_size=10, sigma=0)
    # we expect 4 segments:
    assert_equal(len(np.unique(seg)), 4)
    assert_array_equal(seg[:10, :10], 1)
    assert_array_equal(seg[10:, :10], 2)
    assert_array_equal(seg[:10, 10:], 0)
    assert_array_equal(seg[10:, 10:], 3)

    seg2 = quickshift(img,
                      kernel_size=1,
                      max_dist=2,
                      random_seed=0,
                      convert2lab=False,
                      sigma=0)
    # very oversegmented:
    assert_equal(len(np.unique(seg2)), 7)
    # still don't cross lines
    assert (seg2[9, :] != seg2[10, :]).all()
    assert (seg2[:, 9] != seg2[:, 10]).all()
示例#2
0
def test_color(dtype, channel_axis):
    rnd = np.random.default_rng(583428449)
    img = np.zeros((20, 21, 3))
    img[:10, :10, 0] = 1
    img[10:, :10, 1] = 1
    img[10:, 10:, 2] = 1
    img += 0.01 * rnd.normal(size=img.shape)
    img[img > 1] = 1
    img[img < 0] = 0
    img = img.astype(dtype, copy=False)

    img = np.moveaxis(img, source=-1, destination=channel_axis)
    seg = quickshift(img, random_seed=0, max_dist=30, kernel_size=10, sigma=0,
                     channel_axis=channel_axis)
    # we expect 4 segments:
    assert_equal(len(np.unique(seg)), 4)
    assert_array_equal(seg[:10, :10], 1)
    assert_array_equal(seg[10:, :10], 3)
    assert_array_equal(seg[:10, 10:], 0)
    assert_array_equal(seg[10:, 10:], 2)

    seg2 = quickshift(img, kernel_size=1, max_dist=2, random_seed=0,
                      convert2lab=False, sigma=0,
                      channel_axis=channel_axis)
    # very oversegmented:
    assert len(np.unique(seg2)) > 10
    # still don't cross lines
    assert (seg2[9, :] != seg2[10, :]).all()
    assert (seg2[:, 9] != seg2[:, 10]).all()
示例#3
0
def test_QuickShift():
    """Unit test for QuickShift method. Checks if evaluate function output\
     is the same as manually running the skimage function."""
    qs1 = Segmentors.QuickShift()
    assert qs1.evaluate(TEST_IM_COLOR).all() == segmentation.quickshift(\
                TEST_IM_COLOR, ratio=2, kernel_size=5, max_dist=60, sigma=5, random_seed=1).all()
    assert qs1.evaluate(TEST_IM_GRAY).all() == segmentation.quickshift(color.gray2rgb(\
                TEST_IM_GRAY), ratio=2, kernel_size=5, max_dist=60, sigma=5, random_seed=1).all()
示例#4
0
def getQuickseg(img, nb_of_90_rotation=0, kernel_size=2):
    if nb_of_90_rotation == 0:
        return find_boundaries(
            quickshift(gray2rgb(img),
                       kernel_size=kernel_size,
                       max_dist=6,
                       ratio=3))
    else:
        return np.rot90(
            find_boundaries(
                quickshift(gray2rgb(np.rot90(img, nb_of_90_rotation)),
                           kernel_size=kernel_size,
                           max_dist=6,
                           ratio=3)), 4 - nb_of_90_rotation)
示例#5
0
def create_segments(image_path,
                    algorithm='Slic',
                    n_segments=200,
                    compactness=10):
    image = Image.open(image_path)
    if algorithm == 'Slic':
        segments = slic(image,
                        n_segments=n_segments,
                        compactness=compactness,
                        sigma=0,
                        multichannel=True).ravel()
        segments = np.repeat(segments, 4).tolist()
    elif algorithm == 'Watershed':
        gradient = sobel(rgb2gray(np.array(image)))
        segments = watershed(gradient, markers=250, compactness=0.001).ravel()
        segments = np.repeat(segments, 4).tolist()
    elif algorithm == 'Felzenszwalb':
        segments = felzenszwalb(image, scale=100, sigma=0.5,
                                min_size=50).ravel()
        segments = np.repeat(segments, 4).tolist()
    else:
        segments = quickshift(image, kernel_size=3, max_dist=6,
                              ratio=0.5).ravel()
        segments = np.repeat(segments, 4).tolist()
    return segments
示例#6
0
    def computeSegments(img,
                        n_seg=20000,
                        compactness=1.1,
                        method='slic',
                        convert2lab=True,
                        kernel_size=5,
                        scale=50,
                        mask=None,
                        verbose=True):
        start = time.time()
        if verbose: print('---  Computing SuperPixels  ---')
        if method == 'slic':
            segments = slic(img,
                            n_segments=n_seg,
                            compactness=compactness,
                            convert2lab=convert2lab)
        elif method == 'quickshift':
            segments = quickshift(img, kernel_size=kernel_size)

        elif method == 'felzenszwalb':
            segments = felzenszwalb(img, scale=scale)
        else:
            segments = None
            print(method, 'Not supported')
        if mask is not None:
            segments[mask] = -1

        segments = label(segments, connectivity=2, background=-1)

        if verbose:
            print(
                '---   Done - execution time: {} seconds'.format(time.time() -
                                                                 start))
        return segments
示例#7
0
    def segments(self, image, options=None):
        if options is None:
            options = self.options_map
        print("ACTIVE OPTIONS", options)
        if self.segmentator_type == ImageSegmentator.SEGMENTATOR_SLIC:
            return slic(image,
                        sigma=options['sigma'],
                        n_segments=options['n_segments'],
                        convert2lab=True,
                        multichannel=True,
                        compactness=options['compactness'])
        elif self.segmentator_type == ImageSegmentator.SEGMENTATOR_SLIC_MONO:
            gray = skimage.color.rgb2grey(image)
            return slic(gray,
                        sigma=options['sigma'],
                        n_segments=options['n_segments'],
                        convert2lab=False,
                        multichannel=True,
                        compactness=options['compactness'])
        elif self.segmentator_type == ImageSegmentator.SEGMENTATOR_QUICKSHIFT:
            return quickshift(image, kernel_size=3, max_dist=6, ratio=0.1)
        elif self.segmentator_type == ImageSegmentator.SEGMENTATOR_FELZENSZWALB:
            return felzenszwalb(image, scale=100, sigma=0.5, min_size=50)

        if self.segmentator_type == ImageSegmentator.SEGMENTATOR_WATERSHED:
            gradient = sobel(rgb2gray(image))
            return watershed(gradient,
                             markers=options['n_segments'],
                             compactness=0.001)
示例#8
0
def snap_saliency_to_superpixel(saliency_mask, img, arg_super_pixel):

    if img.max() > 1:
        img = img / 255.0

    img_shape = img.shape[:2]
    saliency_mask_rez = resize(saliency_mask, img_shape, mode='constant')
    saliency_mask_snapped = np.zeros(img_shape)

    if arg_super_pixel == 'felzenszwalb':
        seg = felzenszwalb(img, scale=100, sigma=1.5, min_size=10)
    elif arg_super_pixel == 'slic':
        seg = slic(img, n_segments=100, compactness=20, sigma=0.8)
    elif arg_super_pixel == 'quickshift':
        seg = quickshift(img, kernel_size=5, max_dist=10, ratio=0.5, sigma=1)

    num_seg = int(seg.max()) + 1

    for i_seg in range(num_seg):
        cur_seg = (seg == i_seg)
        cur_saliency_region = saliency_mask_rez[cur_seg]
        saliency_mask_snapped[cur_seg] = cur_saliency_region.mean()

    print(num_seg)
    plt.subplot(2,3,1); plt.imshow(img); plt.title('Input image'); plt.axis('off')
    plt.subplot(2,3,3); plt.imshow(saliency_mask_rez); plt.title('original saliency'); plt.axis('off')
    plt.subplot(2,3,4); plt.imshow(seg); plt.title('super pixel'); plt.axis('off')
    plt.subplot(2,3,5); plt.imshow(mark_boundaries(img,seg)); plt.title('super pixel'); plt.axis('off')
    plt.subplot(2,3,6); plt.imshow(saliency_mask_snapped); plt.title('snapped saliency'); plt.axis('off')

    return saliency_mask_snapped, seg
    def slider_refresh(self):
        if (self.segment_type_choice.get() == 1):
            numSeg = self.slider1.get()
            comp = self.slider2.get()
            sigma = self.slider3.get()
            self.segments = slic(self.image,
                                 n_segments=numSeg,
                                 compactness=comp,
                                 sigma=sigma,
                                 slic_zero=True)

        if (self.segment_type_choice.get() == 2):
            scale = self.slider1.get()
            min_size = self.slider2.get()
            sigma = self.slider3.get()
            self.segments = felzenszwalb(self.image,
                                         scale=scale,
                                         sigma=sigma,
                                         min_size=min_size)

        if (self.segment_type_choice.get() == 3):
            kernel_size = self.slider1.get()
            max_dist = self.slider2.get()
            ratio = self.slider3.get()
            self.segments = quickshift(self.image,
                                       kernel_size=3,
                                       max_dist=6,
                                       ratio=0.5)

        imageOUT = np.where(self.mask == (0, 0, 0), self.image, self.mask)
        imageOUT = toimage(mark_boundaries(imageOUT, self.segments))
        imageOUT = ImageTk.PhotoImage(imageOUT)

        self.panelA.create_image(0, 0, image=imageOUT, anchor=NW)
        self.panelA.image = imageOUT
示例#10
0
def quickshift_segmentaion(img_2d_one_band,
                           ratio=1.0,
                           kernel_size=5,
                           max_dist=10,
                           return_tree=False,
                           sigma=0,
                           convert2lab=True,
                           random_seed=42):
    # Segments image using quickshift clustering in Color-(x,y) space.
    # Produces an oversegmentation of the image using the quickshift mode-seeking algorithm.

    # https://scikit-image.org/docs/dev/auto_examples/segmentation/plot_segmentations.html?highlight=segmentation
    # Quickshift has two main parameters: sigma controls the scale of the local density approximation,
    # max_dist selects a level in the hierarchical segmentation that is produced.
    # There is also a trade-off between distance in color-space and distance in image-space, given by ratio.

    # ValueError: the input array must be have a shape == (.., ..,[ ..,] 3)), got (1882, 1895, 1), set convert2lab=False

    img_2d_one_band = img_2d_one_band.astype(np.float64)
    out_labels = segmentation.quickshift(img_2d_one_band,
                                         ratio=ratio,
                                         kernel_size=kernel_size,
                                         max_dist=max_dist,
                                         return_tree=return_tree,
                                         sigma=sigma,
                                         convert2lab=convert2lab,
                                         random_seed=random_seed)
    out_labels = out_labels.astype(np.int32)
    return out_labels
示例#11
0
 def __init__(self, im_location, ref_locations, iterations = 5, threshold = 0.1, verbose = True):
     
     # Load image and reference images
     self.im2class = io.imread(im_location)
     self.ref_images = [io.imread(l) for l in ref_locations]
     
     # Apply quickshift image segmentation algorithm
     self.segments = quickshift(self.im2class, kernel_size=7, max_dist=3, ratio=0.35, convert2lab=False)
     self.n_segments = len(np.unique(self.segments))
     if verbose: print("Detected ",self.n_segments," in input image.")
         
     # Use unique dictionary to create list of pixels within each segment
     self.segment_dict = UniqueDict()
     for x, row in enumerate(self.segments):
         for y, val in enumerate(row):
             try:
                 self.segment_dict[val] = []
                 self.segment_dict[val].append(tuple(self.im2class[x,y]))
             except KeyError:
                 self.segment_dict[val].append(tuple(self.im2class[x,y]))
      
     # Create unique set of reference pixels
     self.ref_pixels = []
     for im in self.ref_images:
         for row in im:
             for val in row:
                 self.ref_pixels.append(tuple(val))
     self.ref_pixels = set(self.ref_pixels)
     self.ref_pixels.discard((0,0,0))
             
     self.matched_segments = match_segments(self.segment_dict, self.ref_pixels, threshold)
     self.treeclass_image =reclass_segments(self.segments, self.matched_segments)
示例#12
0
def show_important_parts(image,
                         lime_weights,
                         label=None,
                         segments=None,
                         ratio_superpixels=0.2):
    if label is None:
        label = list(lime_weights.keys())[0]

    if label not in lime_weights:
        raise KeyError('Label not in interpretation')

    if segments is None:
        segments = quickshift(image, sigma=1)

    num_sp = int(ratio_superpixels * len(lime_weights[label]))
    lime_weight = lime_weights[label]
    mask = np.zeros(segments.shape, segments.dtype)
    temp = image.copy()

    fs = [x[0] for x in lime_weight if x[1] > 0][:num_sp]
    for f in fs:
        temp[segments == f, 1] = 255
        mask[segments == f] = 1

    return mark_boundaries(temp, mask)
示例#13
0
def superpixel(image_path,
               method='quickshift',
               if_plot=False,
               numSegments=200):
    # load the image and convert it to a floating point data type
    img = io.imread(image_path)
    image = img_as_float(img)
    # apply SLIC and extract (approximately) the supplied number
    # of segments
    if method == 'quickshift':
        segments = quickshift(img, kernel_size=3, max_dist=6, ratio=0.5)
    elif method == 'slic':
        segments = slic(img, numSegments, sigma=5)
    elif method == 'felzenszwalb':
        segments = felzenszwalb(img, scale=100, sigma=0.5, min_size=50)
    else:
        raise TypeError('Method %s doesn\'t exists' % method)

    if if_plot:
        # show the output of SLIC
        fig = plt.figure("Superpixels -- %s segments" % method)
        ax = fig.add_subplot(1, 1, 1)
        ax.imshow(mark_boundaries(image, segments))
        plt.axis("off")
        # show the plots
        plt.show()

    return segments.astype(np.int32)
示例#14
0
    def predict(self, filenames_list):
        if not isinstance(filenames_list, list):
            raise Exception('Input list of files is not a list actually')
        rectangles = []
        for filename in filenames_list:
            image = imread(filename)
            img_copy = skimage.transform.resize(image, (100, 100, 3))
            img_copy = skimage.filters.gaussian(img_copy,
                                                sigma=0.5,
                                                multichannel=True)
            img_norm = color.normalize_RGBratio(img_copy, method=self.method)
            if self.algorithm == 'slic':
                seg = slic(img_norm,
                           n_segments=200,
                           max_iter=100,
                           enforce_connectivity=True,
                           max_size_factor=10,
                           start_label=0)
            elif self.algorithm == 'quickshift':
                seg = quickshift(img_norm,
                                 kernel_size=3,
                                 sigma=0,
                                 convert2lab=True,
                                 max_dist=6,
                                 ratio=0.5)
            data = seg_stats_retrieve(seg, img_copy)
            seg = seg_reduction(seg, data)
            seg = seg_selection(seg, img_copy, img_norm)
            res = resize_seg(seg, image)

            ### Draw boundary rectangle
            rectangles.append(blob.bound_rect(res))
        return rectangles
示例#15
0
    def initial_segmentation(self, *args):
        """Perform the quick shift superpixel segmentation on an image.
        The quick shift algorithm is invoked with its default parameters.

        Parameters
        ----------
        *args : 3D numpy array with size 3 in the third dimension
            Input image to be segmented. If not given, the original image is used.

        Returns
        -------
        segment_mask : ndarray
            Label image, output of the quick shift algorithm.
        """

        if args:
            image = args[0]
        else:
            image = self.original_image
        segment_mask = segmentation.quickshift(image)
        if self.__interactive_mode:
            io.imshow(color.label2rgb(segment_mask, self.original_image, kind='avg'))
            io.show()
            print('Quick shift segmentation finished. '
                  'Number of segments: {0}'.format(np.amax(segment_mask)))
        return segment_mask
示例#16
0
def quickshift(image, ratio=1, kernel_size=5, max_dist=1, sigma=0):
    image = _preprocess(image)
    return segmentation.quickshift(image,
                                   ratio,
                                   kernel_size,
                                   max_dist,
                                   sigma=sigma)
def generate_segments(x_input, opt):
    img = img_as_float(x_input[::2, ::2])
    height, width = img.shape[:2]
    patch_size = 8 * 2**(opt["down_scale"])
    n_segments = int(height / patch_size) * int(width / patch_size)
    if "felzenszwalb" in opt["super_pixel_method"]:
        scale = 2**opt["down_scale"]
        segments = felzenszwalb(img, scale=scale, sigma=0.5, min_size=50)
    elif "slic" in opt["super_pixel_method"]:
        segments = slic(img,
                        n_segments=n_segments,
                        compactness=10,
                        sigma=1,
                        start_label=1)
    elif "quickshift" in opt["super_pixel_method"]:
        kernel_size = 3 * (opt["down_scale"] + 1)
        segments = quickshift(img,
                              kernel_size=kernel_size,
                              max_dist=6,
                              ratio=0.5)
    elif "watershed" in opt["super_pixel_method"]:
        gradient = sobel(rgb2gray(img))
        segments = watershed(gradient, markers=n_segments, compactness=0.001)
    elif "patches" in opt["super_pixel_method"]:
        segments = patches(img, patch_size=patch_size)
    else:
        raise ValueError("SuperPixel-Option: {} unknown!".format(
            opt["super_pixel_method"]))
    return segments
示例#18
0
def QUICKSHIFT(Input_Image,ks, md, r):
        
    '''
    Description:    Segments image using quickshift clustering in Color space.

    source:         skimage, openCv python 
    
    parameters:     Input_Image : ndarray
                    Input image
    
                    kernel size : float
                    Width of Gaussian kernel used in smoothing the sample density. Higher means fewer clusters.
    
                    max distance:  float
                    Cut-off point for data distances. Higher means fewer clusters.
    
                    ratio : float, between 0 and 1 
                    Balances color-space proximity and image-space proximity. Higher values give more weight to color-space.
    
    return:         Segment_mask : ndarray (cols, rows)
                    Integer mask indicating segment labels.
    '''
    #default values, set in case of 0 as input
    if ks == 0:
        ks = 5
    if md == 0:
        md = 10
    if r == 0:
        r = 1
    # print kernel_size,max_dist, ratio    
    img = cv2.imread(Input_Image)
    segments_quick = quickshift(img, kernel_size=ks, max_dist=md, ratio=r)
    #print segments_quick.shape
    print("Quickshift number of segments: %d" % len(np.unique(segments_quick)))
    return segments_quick
示例#19
0
def generate_superpixels(image, algorithm):
    if algorithm == 'slic':
        print 'call the base slic algorithm'
        L = segmentation.slic(image.get_rgb(), n_segments=Option.sNseg, compactness=Option.sCompact, \
          sigma=Option.sSigma,convert2lab=True)   #call slic
    elif algorithm == 'quickshift':
        print 'call the quickshift algorithm'
        L = segmentation.quickshift(image.get_rgb(), ratio=Option.qRatio, kernel_size=Option.qKernel, \
          max_dist=Option.qDist, return_tree=False, sigma=0, convert2lab=True, random_seed=Option.qSeed)
    else:
        print 'call the felzenszwalb algorithm'
        L = segmentation.felzenszwalb(image.get_rgb(),
                                      scale=20,
                                      sigma=5,
                                      min_size=60)

    L = regions.distinct_label(L)
    print np.max(L), 'superPixels generated'
    L = clusters.merge_tiny_regions(image.get_lab(), L, Option.tsize)
    print np.max(L), 'superPixels remained'

    #clustering the super-pixels
    print 'merge the superpixels'
    L = dbscan.merge_region(image, L, [Option.dbTresh, Option.dbText])

    return L
示例#20
0
def seg(img, Debug=False):
    # Level 1
    start = time.time() * 1000
    Level = "QuickShift"
    if Level == "QuickShift":
        labels = segmentation.quickshift(
            img, kernel_size=3, max_dist=10,
            ratio=1.0)  #.slic(img, compactness=30, n_segments=400)
    elif Level == "SLIC":
        labels = segmentation.slic(img, compactness=30, n_segments=400)
    elif Level == "felzenszwalb":
        labels = segmentation.felzenszwalb(img,
                                           scale=100,
                                           sigma=0.5,
                                           min_size=50)
    elif Level == "Watershed":
        gradient = sobel(rgb2gray(img))
        labels = segmentation.watershed(gradient,
                                        markers=250,
                                        compactness=0.001)
    # Show Result
    if Debug:
        print("level1 took ", int(time.time() * 1000 - start), "ms")
        showResult(img, labels)
    return labels
示例#21
0
    def _Execute_Segmentation(self, wx_spx, img):

        scale_factor = img.shape[0] * img.shape[1] / (self.xsize * self.ysize)

        ID_Algorithm = wx_spx.SelectAlgorithm.GetSelection()
        if ID_Algorithm == 0: # Felzenszwalbs's method
            f_scale   = wx_spx.f_scale.GetValue()
            f_sigma   = wx_spx.f_sigma.GetValue()
            f_minsize = wx_spx.f_minsize.GetValue()
            segments = felzenszwalb(img, scale=f_scale, sigma=f_sigma, min_size=f_minsize)
            print("Felzenszwalb number of segments: {}".format(len(np.unique(segments))))
        elif ID_Algorithm == 1: # SLIC
            s_nseg = wx_spx.s_nseg.GetValue() * scale_factor
            s_comp = wx_spx.s_comp.GetValue()
            s_sigma = wx_spx.s_sigma.GetValue()
            segments = slic(gray2rgb(img), n_segments=s_nseg, compactness=s_comp, sigma=s_sigma)
            print('SLIC number of segments: {}'.format(len(np.unique(segments))))
        elif ID_Algorithm == 2: # Quickshift
            q_ksize   = wx_spx.q_ksize.GetValue()
            q_maxdist = wx_spx.q_maxdist.GetValue()
            q_ratio   = wx_spx.q_ratio.GetValue()
            segments = quickshift(gray2rgb(img), kernel_size=q_ksize, max_dist=q_maxdist, ratio=q_ratio)
            print('Quickshift number of segments: {}'.format(len(np.unique(segments))))
        elif ID_Algorithm == 3: # Compact watershed
            w_nmark   = wx_spx.w_nmark.GetValue() * scale_factor
            w_comp    = wx_spx.w_comp.GetValue()
            gradient = sobel(img)
            segments = watershed(gradient, markers=w_nmark, compactness=w_comp)

        return segments
示例#22
0
def quickshift_skimage(input_band_list, kernel_size, max_distance, ratio):

    """Quickshift segmentation from Skimage library, works with RGB
    
    :param input_band_list: list of 2darrays (list of numpy arrays)
    :param kernel_size: width of Gaussian kernel used in smoothing the sample density. Higher means fewer clusters. (float)
    :param max_distance:cut-off point for data distances. Higher means fewer clusters. (float)
    :param ratio: balances color-space proximity and image-space proximity. Higher values give more weight to color-space. (float between 0 and 1)
    :returns:  2darray with the result of the segmentation (numpy array)
    
    Author: Daniele De Vecchi - Mostapha Harb
    Last modified: 22/03/2014
    
    Reference: http://scikit-image.org/docs/dev/api/skimage.segmentation.html#skimage.segmentation.quickshift
    """

    # TODO: Would add here directly also the related publication reference (for all functions that are based on scientific papers)

    # default values, set in case of 0 as input
    if kernel_size == 0:
        kernel_size = 5
    if max_distance == 0:
        max_distance = 10
    if ratio == 0:
        ratio = 1

    img = np.dstack((input_band_list[0], input_band_list[1], input_band_list[2]))
    segments_quick = quickshift(img, kernel_size, max_distance, ratio)

    return segments_quick
def fun_compare_colorsegmentation_and_display(image_data, number_segments=250, compactness_factor=10):
    """
    The function is a copy of what does this link http://scikit-image.org/docs/dev/auto_examples/plot_segmentations.html
    """
    segments_fz = felzenszwalb(image_data, scale=100, sigma=0.5, min_size=50)
    segments_slic = slic(image_data, n_segments=number_segments, compactness=compactness_factor, sigma=1)
    segments_quick = quickshift(image_data, kernel_size=3, max_dist=6, ratio=0.5)

    print ("Felzenszwalb's number of segments: %d" % len(np.unique(segments_fz)))
    print ("Slic number of segments: %d" % len(np.unique(segments_slic)))
    print ("Quickshift number of segments: %d" % len(np.unique(segments_quick)))

    fig, ax = plt.subplots(1, 3, sharex=True, sharey=True, subplot_kw={"adjustable": "box-forced"})
    fig.set_size_inches(8, 3, forward=True)
    fig.subplots_adjust(0.05, 0.05, 0.95, 0.95, 0.05, 0.05)

    ax[0].imshow(mark_boundaries(image_data, segments_fz, color=(1, 0, 0)))
    ax[0].set_title("Felzenszwalbs's method")
    ax[1].imshow(mark_boundaries(image_data, segments_slic, color=(1, 0, 0)))
    ax[1].set_title("SLIC")
    ax[2].imshow(mark_boundaries(image_data, segments_quick, color=(1, 0, 0)))
    ax[2].set_title("Quickshift")
    for a in ax:
        a.set_xticks(())
        a.set_yticks(())
    plt.show()
示例#24
0
def quickshift_skimage(input_band_list, kernel_size, max_distance, ratio):
    '''Quickshift segmentation from Skimage library, works with RGB
    
    :param input_band_list: list of 2darrays (list of numpy arrays)
    :param kernel_size: width of Gaussian kernel used in smoothing the sample density. Higher means fewer clusters. (float)
    :param max_distance:cut-off point for data distances. Higher means fewer clusters. (float)
    :param ratio: balances color-space proximity and image-space proximity. Higher values give more weight to color-space. (float between 0 and 1)
    :returns:  2darray with the result of the segmentation (numpy array)
    
    Author: Daniele De Vecchi - Mostapha Harb
    Last modified: 22/03/2014
    
    Reference: http://scikit-image.org/docs/dev/api/skimage.segmentation.html#skimage.segmentation.quickshift
    '''

    #TODO: Would add here directly also the related publication reference (for all functions that are based on scientific papers)

    #default values, set in case of 0 as input
    if kernel_size == 0:
        kernel_size = 5
    if max_distance == 0:
        max_distance = 10
    if ratio == 0:
        ratio = 1

    img = np.dstack(
        (input_band_list[0], input_band_list[1], input_band_list[2]))
    segments_quick = quickshift(img, kernel_size, max_distance, ratio)

    return segments_quick
示例#25
0
def comparison_of_segmentation_and_superpixel_algorithms_example():
    img = img_as_float(data.astronaut()[::2, ::2])

    segments_fz = felzenszwalb(img, scale=100, sigma=0.5, min_size=50)
    segments_slic = slic(img, n_segments=250, compactness=10, sigma=1)
    segments_quick = quickshift(img, kernel_size=3, max_dist=6, ratio=0.5)
    gradient = sobel(rgb2gray(img))
    segments_watershed = watershed(gradient, markers=250, compactness=0.001)

    print('Felzenszwalb number of segments: {}'.format(
        len(np.unique(segments_fz))))
    print('SLIC number of segments: {}'.format(len(np.unique(segments_slic))))
    print('Quickshift number of segments: {}'.format(
        len(np.unique(segments_quick))))

    fig, ax = plt.subplots(2, 2, figsize=(10, 10), sharex=True, sharey=True)

    ax[0, 0].imshow(mark_boundaries(img, segments_fz))
    ax[0, 0].set_title("Felzenszwalbs's method")
    ax[0, 1].imshow(mark_boundaries(img, segments_slic))
    ax[0, 1].set_title('SLIC')
    ax[1, 0].imshow(mark_boundaries(img, segments_quick))
    ax[1, 0].set_title('Quickshift')
    ax[1, 1].imshow(mark_boundaries(img, segments_watershed))
    ax[1, 1].set_title('Compact watershed')

    for a in ax.ravel():
        a.set_axis_off()

    plt.tight_layout()
    plt.show()
示例#26
0
文件: test.py 项目: Rhoana/TreeFusion
def build_tree(im):
    # im = boundary probability

    print "QS"
    segs = quickshift(im, sigma=2.0, return_tree=False, convert2lab=False, max_dist=10)
    orig_segs = segs.copy()
    print "done"

    # Find all neighboring regions and the values between them
    plus = np.array([
        [0, 1, 0],
        [1, 1, 1],
        [0, 1, 0]]).astype(np.bool)
    lo = minimum_filter(segs, footprint=plus).astype(np.int32)
    hi = maximum_filter(segs, footprint=plus).astype(np.int32)

    counter = ValueCountInt64()
    counter.add_values_pair32(lo.ravel(), hi.ravel())
    loc, hic, edge_counts = counter.get_counts_pair32()
    weighter = WeightedCountInt64()
    weighter.add_values_pair32(lo.ravel(), hi.ravel(), im.astype(np.float32).ravel())
    low, hiw, edge_weights = weighter.get_weights_pair32()

    max_regions = 2 * segs.max() + 1 #  number of regions is max() + 1
    counts = np.zeros((max_regions, max_regions), dtype=np.uint64)
    weights = np.zeros((max_regions, max_regions), dtype=float)
    counts[loc, hic] = edge_counts
    weights[low, hiw] = edge_weights
    # zero diagonal
    counts[np.arange(max_regions), np.arange(max_regions)] = 0

    next_region = segs.max() + 1
    parents = {}
    # set up heap
    heap = [(weights[l, h] / counts[l, h], l, h) for l, h in zip(*np.nonzero(counts))]
    heapify(heap)

    # successively merge regions
    while heap:
        w, lo, hi = heappop(heap)
        if (lo in parents) or (hi in parents):
            continue
        print next_region, max_regions
        parents[lo] = next_region
        parents[hi] = next_region
        counts[next_region, :] = counts[lo, :] + counts[hi, :]
        weights[next_region, :] = weights[lo, :] + weights[hi, :]
        counts[:, next_region] = counts[next_region, :]
        weights[:, next_region] = weights[next_region, :]
        for idx in range(next_region):
            if idx in parents:
                continue
            if counts[idx, next_region] > 0 and (idx not in parents):
                heappush(heap, (weights[idx, next_region] / counts[idx, next_region], idx, next_region))
        segs[segs == lo] = next_region
        segs[segs == hi] = next_region
        next_region += 1
    print "done"
    return orig_segs, parents
示例#27
0
def doSegment(param, img):
  if param[0] == 'slic':
    segments_res = slic(img, n_segments=int(param[1]), compactness=int(param[2]), sigma=int(param[3]), convert2lab=True)
  elif param[0] == 'pff':
    segments_res = felzenszwalb(img, scale=int(param[1]), sigma=float(param[2]), min_size=int(param[3]))
  elif param[0] == 'quick':
    segments_res = quickshift(img, kernel_size=int(param[1]), max_dist=int(param[2]), ratio=float(param[3]), convert2lab=True)
  return segments_res
示例#28
0
def doSegment(param, img):
  if param[0] == 'slic':
    segments_res = slic(img, n_segments=int(param[1]), compactness=int(param[2]), sigma=int(param[3]), convert2lab=True)
  elif param[0] == 'pff':
    segments_res = felzenszwalb(img, scale=int(param[1]), sigma=float(param[2]), min_size=int(param[3]))
  elif param[0] == 'quick':
    segments_res = quickshift(img, kernel_size=int(param[1]), max_dist=int(param[2]), ratio=float(param[3]), convert2lab=True)
  return segments_res
示例#29
0
def tf_seg_quickshift(imgpath, tffolder, ratio=1, kernel_siz=10, max_dist=200):
    img = io.imread(imgpath)
    label = segmentation.quickshift(img,
                                    ratio=ratio,
                                    kernel_size=kernel_siz,
                                    max_dist=max_dist)
    # https://scikit-image.org/docs/dev/api/skimage.segmentation.html
    save_label(imgpath, tffolder, label, "segment quickshift")
    return (label)
示例#30
0
def create_quickshift_mask(in_image_path, out_path, params = None):
    """Creates an image segmentation mask using quickshift. Saves results at out_path
    Uses quickshift coeffieicents from https://pure.aber.ac.uk/portal/files/29175686/remotesensing_11_00658.pdf,
    table 3"""
    swir_image = gdal.Open(in_image_path)
    swir_raw_array = swir_image.GetVirtualMemArray()
    swir_sklean_format = np.transpose(swir_raw_array, [1, 2, 0])
    #swir_sklean_format = scale_array_to_255(np.transpose(swir_raw_array, [1, 2, 0]))

    if params:
        class_masks = quickshift(swir_sklean_format, *params)

    class_masks = quickshift(swir_sklean_format, convert2lab=True, ratio=0.8, kernel_size=30, max_dist=3, sigma=0)
    #where ratio is the tradeoff between color importance and spatial importance (larger values give more importance to color), kernelsize is the size of the kernel used to estimate the density, and maxdist is the maximum distance between points in the feature space that may be linked if the density is increased.
    # http://www.vlfeat.org/overview/quickshift.html

    s2_functions.create_tif(filename=out_path, g=swir_image, Nx=swir_raw_array.shape[1],
                            Ny=swir_raw_array.shape[2], new_array=class_masks, noData=0, data_type=gdal.GDT_Int32)
示例#31
0
def seg(img):
    transposed = np.transpose(img, (1, 2, 0))
    quickshifted = quickshift(transposed,
                              kernel_size=4,
                              max_dist=200,
                              ratio=0.2,
                              random_seed=123)
    ret = np.tile(quickshifted, (3, 1, 1))
    return ret
示例#32
0
 def segment(self, img):
     im = img_as_float(img)
     segments_quick = quickshift(im,
                                 kernel_size=self.k_size,
                                 max_dist=self.max_dist,
                                 ratio=self.ratio,
                                 sigma=self.sigma,
                                 convert2lab=False)
     return segments_quick.astype(np.uint8)
示例#33
0
def segmentation(image, nclusters=2, method='slic'):
    if method == 'slic':
        labels = slic(image, n_segments=nclusters, compactness=5, sigma=2.5)
    elif method == 'fz':
        labels = felzenszwalb(image, scale=1500, sigma=0.9, min_size=2500)
    elif method == 'qs':
        labels = quickshift(image, kernel_size=3, max_dist=6, ratio=0.5)
    else:
        raise NotImplementedError
    return labels
示例#34
0
 def run(self, ips, imgs, para = None):
     if not para['stack']: imgs = [ips.img]
     ips.swap()
     rst = []
     for i in range(len(imgs)):
         rst.append(segmentation.quickshift(imgs[i], para['ratio'], para['kernel_size'],
             para['max_dist'], para['sigma']).astype('int32'))
         rst[-1] += 1
         self.progress(i, len(imgs))
     self.app.show_img(rst, ips.title+'-quickshiftlab')
示例#35
0
    def test_instanciate_segmentation_algorithm(self):
        img = img_as_float(astronaut()[::2, ::2])

        # wrapped functions provide the same result
        fn = SegmentationAlgorithm('quickshift', kernel_size=3, max_dist=6,
                                   ratio=0.5, random_seed=133)
        fn_result = fn(img)
        original_result = quickshift(img, kernel_size=3, max_dist=6, ratio=0.5,
                                     random_seed=133)

        # same segments
        self.assertTrue(np.array_equal(fn_result, original_result))
示例#36
0
    def test_instanciate_segmentation_algorithm(self):
        img = img_as_float(chelsea()[::2, ::2])

        # wrapped functions provide the same result
        fn = SegmentationAlgorithm('quickshift', kernel_size=3, max_dist=6,
                                   ratio=0.5, random_seed=133)
        fn_result = fn(img)
        original_result = quickshift(img, kernel_size=3, max_dist=6, ratio=0.5,
                                     random_seed=133)

        # same segments
        self.assertTrue(np.array_equal(fn_result, original_result))
示例#37
0
def test_grey():
    rnd = np.random.RandomState(0)
    img = np.zeros((20, 21))
    img[:10, 10:] = 0.2
    img[10:, :10] = 0.4
    img[10:, 10:] = 0.6
    img += 0.1 * rnd.normal(size=img.shape)
    seg = quickshift(img, kernel_size=2, max_dist=3, random_seed=0,
                     convert2lab=False, sigma=0)
    # we expect 4 segments:
    assert_equal(len(np.unique(seg)), 4)
    # that mostly respect the 4 regions:
    for i in range(4):
        hist = np.histogram(img[seg == i], bins=[0, 0.1, 0.3, 0.5, 1])[0]
        assert_greater(hist[i], 20)
示例#38
0
def test_color():
    rnd = np.random.RandomState(0)
    img = np.zeros((20, 21, 3))
    img[:10, :10, 0] = 1
    img[10:, :10, 1] = 1
    img[10:, 10:, 2] = 1
    img += 0.01 * rnd.normal(size=img.shape)
    img[img > 1] = 1
    img[img < 0] = 0
    seg = quickshift(img, random_seed=0, max_dist=30, kernel_size=10, sigma=0)
    # we expect 4 segments:
    assert_equal(len(np.unique(seg)), 4)
    assert_array_equal(seg[:10, :10], 1)
    assert_array_equal(seg[10:, :10], 2)
    assert_array_equal(seg[:10, 10:], 0)
    assert_array_equal(seg[10:, 10:], 3)

    seg2 = quickshift(img, kernel_size=1, max_dist=2, random_seed=0,
                      convert2lab=False, sigma=0)
    # very oversegmented:
    assert_equal(len(np.unique(seg2)), 7)
    # still don't cross lines
    assert_true((seg2[9, :] != seg2[10, :]).all())
    assert_true((seg2[:, 9] != seg2[:, 10]).all())
示例#39
0
def segment(img):
    """
    segment an image

    @type img; LAB image
    """
    if 3 != img.ndim:
        return None

    # convert to lab
    #img_lab = rgb2lab(img)

    #print provider.img
    # quickshift
    qs = quickshift(img, return_tree=False, convert2lab=False)

    return qs
示例#40
0
def quickshift(request):

    image, response = skread(request)

    if len(image.shape) == 2:
        
        image = cv2.cvtColor(image,cv2.COLOR_GRAY2RGB)

    kernel = int(request.GET.get('quickshift-kernel'))

    dist = int(request.GET.get('quickshift-max-dist'))

    ratio = float(request.GET.get('quickshift-ratio')) 

    segments = segmentation.quickshift(image, kernel_size = kernel, max_dist = dist, ratio = ratio)

    image = segmentation.mark_boundaries(image, segments)

    io.imsave(response['filename'], image)

    return JsonResponse(response)
def superpixel_majority_vote(image, segmentation):
    """Mark superpixels by majority vote."""
    image = image.astype(float)
    segments = quickshift(image, ratio=0.5, max_dist=10, sigma=1.0)
    # segments = slic(image, n_segments=50, compactness=20)
    # watershed -
    ("http://scikit-image.org/docs/dev/auto_examples/segmentation/"
     "plot_marked_watershed.html")
    # http://scikit-image.org/docs/dev/auto_examples/
    height, width = segments.shape
    segment_count = {}
    for x in range(width):
        for y in range(height):
            s = segments[y][x]
            if s not in segment_count:
                segment_count[s] = {0: 0, 1: 0}  # binary
            segment_count[s][segmentation[y][x]] += 1
    for x in range(width):
        for y in range(height):
            s = segments[y][x]
            class_ = int(segment_count[s][1] > segment_count[s][0])
            segmentation[y][x] = class_
    return segmentation
示例#42
0
img = coffee()
drip = ("/home/moose/GitHub/MediSeg/DATA/Segmentation_Rigid_Training/"
        "Training/OP4/Raw/")


for i in range(10, 40):
    im = Image.open(drip + "img_%i_raw.png" % i)
    img = numpy.array(im)

    w, h, d = original_shape = tuple(img.shape)

    segments = slic(img,
                    n_segments=50,
                    compactness=20)
    b1 = mark_boundaries(img, segments, color=(1, 1, 0))
    segments = quickshift(img, ratio=0.5, max_dist=10, sigma=0.0)
    b2 = mark_boundaries(img, segments, color=(1, 1, 0))
    segments = quickshift(img, ratio=0.5, max_dist=10, sigma=0.1)
    b3 = mark_boundaries(img, segments, color=(1, 1, 0))
    segments = quickshift(img, ratio=0.5, max_dist=10, sigma=1.0)
    b4 = mark_boundaries(img, segments, color=(1, 1, 0))
    # Display all results, alongside original image
    fig = plt.figure()

    a = fig.add_subplot(2, 2, 1)
    imgplot = plt.imshow(b1)
    a.set_title('slic')

    a = fig.add_subplot(2, 2, 2)
    imgplot = plt.imshow(b2)
    a.set_title('20,30')
示例#43
0
def quick(im, ratio, max_dist, display_im):
    labels = quickshift(im, ratio, max_dist)
    marked = mark_boundaries(display_im, labels)
    return marked
示例#44
0
文件: test.py 项目: 007/hackweek2015
def segment_quick(fig, image):
    segmented = quickshift(image, kernel_size=3, max_dist=60, ratio=0.5)
    fig_label_segments(fig, image, segmented, 'quick')
示例#45
0
from skimage.data import lena
from skimage.segmentation import felzenszwalb, slic, quickshift
from skimage.segmentation import mark_boundaries
from skimage.util import img_as_float

'''
[::2,::2]表示每隔两个index娶一个sample,就是down-sampling
'''
img = img_as_float(lena()[::2, ::2])
segments_fz = felzenszwalb(img, scale=100, sigma=0.5, min_size=50)
print (segments_fz)
print (segments_fz.shape)
segments_slic = slic(img, n_segments=4, compactness=10, sigma=1)
np.savetxt('test.txt', segments_slic, fmt='%1i')
segments_quick = quickshift(img, kernel_size=3, max_dist=6, ratio=0.5)

print("Felzenszwalb's number of segments: %d" % len(np.unique(segments_fz)))
print("Slic number of segments: %d" % len(np.unique(segments_slic)))
print("Quickshift number of segments: %d" % len(np.unique(segments_quick)))

fig, ax = plt.subplots(1, 3)
fig.set_size_inches(8, 3, forward=True)
fig.subplots_adjust(0.05, 0.05, 0.95, 0.95, 0.05, 0.05)

ax[0].imshow(mark_boundaries(img, segments_fz))
ax[0].set_title("Felzenszwalbs's method")
ax[1].imshow(mark_boundaries(img, segments_slic))
ax[1].set_title("SLIC")
ax[2].imshow(mark_boundaries(img, segments_quick))
ax[2].set_title("Quickshift")
示例#46
0
from skimage.data import lena
from skimage.segmentation import felzenszwalb, slic, quickshift
from skimage.segmentation import mark_boundaries
from skimage.util import img_as_float

img = img_as_float(lena()[::2, ::2])

slic_image = Image.open("input/locker_1.png").convert('RGB')
#print(slic_image)

slic_image = np.asarray(slic_image)

segments_fz = felzenszwalb(slic_image, scale=100, sigma=0.5, min_size=50)
segments_slic = slic(slic_image, ratio=10, n_segments=250, sigma=1)
segments_quick = quickshift(slic_image, kernel_size=3, max_dist=6, ratio=0.5)

print(segments_quick)

print("Felzenszwalb's number of segments: %d" % len(np.unique(segments_fz)))
print("Slic number of segments: %d" % len(np.unique(segments_slic)))
print("Quickshift number of segments: %d" % len(np.unique(segments_quick)))

fig, ax = plt.subplots(1, 3)
fig.set_size_inches(8, 3, forward=True)
plt.subplots_adjust(0.05, 0.05, 0.95, 0.95, 0.05, 0.05)

ax[0].imshow(mark_boundaries(slic_image, segments_fz))
ax[0].set_title("Felzenszwalbs's method")
ax[1].imshow(mark_boundaries(slic_image, segments_slic))
ax[1].set_title("SLIC")
示例#47
0
if scale != 1:
    pil_image = pil_image.resize((int(scale*width), int(scale*height)), Image.ANTIALIAS)

first_std_image = image_std(pil_image)

first_image = np.asarray(pil_image)
first_image_final = np.copy(first_image)

# Compute clustering
print("Compute structured hierarchical clustering...")

#first_label = felzenszwalb(pil_image, scale=100, sigma=0.5, min_size=50)
#first_label = slic(pil_image, ratio=10, n_segments=250, sigma=1)
#first_image_edges = filter.canny(first_image, sigma=5)
first_label = quickshift(pil_image, kernel_size=kernel_size, max_dist=max_dist, ratio=ratio)

fig, ax = plt.subplots(1, 3)
fig.set_size_inches(8, 3, forward=True)
plt.subplots_adjust(0.05, 0.05, 0.95, 0.95, 0.05, 0.05)
ax[0].imshow(mark_boundaries(first_image_final, first_label))
ax[0].set_title("1st Image")

first_image = pl.mean(first_image,2)

first_label = np.reshape(first_label, first_image.shape)

###############################################################################
#SECOND IMAGE
###############################################################################
pil_image = Image.open(second_image_name)
from skimage.util import img_as_float
from scipy import misc
#img = img_as_float(lena()[::2, ::2])
img_name = 'B:/2_SatelliteImagery/Gmaps/Imagery/Test4/reprojected_1m/tile_91.4761820742629_22.5230230586932_17_j_clip_proj.img'
img = brick(img_name,'',50,50,150,150)
#img = scipy.misc.imread(img_name)
print len(img)
print img
img = numpy.transpose(img, axes = [1,2,0])
print img
print 'Computing Felzenszwalkbs segmentation'
segments_fz = felzenszwalb(img, scale=20, sigma=1, min_size=50)
print 'Computing slic k-means segmentation'
segments_slic = slic(img, compactness=10, n_segments=50, sigma=1, max_iter = 50)
print 'Computing quickshift segmentation'
segments_quick = quickshift(img, kernel_size=5, max_dist=50, sigma = 1,ratio=1)

##print "Felzenszwalb's number of segments: %d" % len(np.unique(segments_fz))
##print "Slic number of segments: %d" % len(np.unique(segments_slic))
##print "Quickshift number of segments: %d" % len(np.unique(segments_quick))

fig, ax = plt.subplots(1, 3)
fig.set_size_inches(8, 3, forward=True)
plt.subplots_adjust(0.05, 0.05, 0.95, 0.95, 0.05, 0.05)

ax[0].imshow(mark_boundaries(img, segments_fz))
ax[0].set_title("Felzenszwalbs's method")
ax[1].imshow(mark_boundaries(img, segments_slic))
ax[1].set_title("SLIC")
ax[2].imshow(mark_boundaries(img, segments_quick))
ax[2].set_title("Quickshift")
示例#49
0
from skimage.viewer import ImageViewer
from skimage import img_as_ubyte
from skimage.data import imread
from skimage.color import rgb2grey
from skimage.segmentation import slic, quickshift
from skimage.segmentation import mark_boundaries

im = imread('grumpy.jpg')

viewer = ImageViewer(im)
viewer.show()

# segmented = slic(img_as_ubyte(im),n_segments=100,max_iter=1)
segmented = quickshift(img_as_ubyte(im),max_dist=15)

viewer = ImageViewer(mark_boundaries(im,segmented))
viewer.show()
示例#50
0
from skimage.segmentation import quickshift, mark_boundaries
from skimage import feature
import skimage
import cv2

filePath = "C:\\Users\\Phil\\Desktop\\Sea Ice Photo for XSEDE16\\examples\\072610_00104.jpg"

img = cv2.imread(filePath)

out = quickshift(img)

def maskSuperPixel(superPix,index,image):
	mask = np.zeros(img.shape[:2], dtype = "uint8")
	mask[superPix == index] = 255
	cv2.imshow("", cv2.bitwise_and(image, image, mask = mask))
	cv2.waitKey(0)

props = skimage.measure.regionprops(out,img[:,:,0], cache=False)
r=[prop.mean_intensity for prop in props]
props = skimage.measure.regionprops(out,img[:,:,1], cache=False)
g=[prop.mean_intensity for prop in props]
props = skimage.measure.regionprops(out,img[:,:,2], cache=False)
b=[prop.mean_intensity for prop in props]
brRatio = np.divide(b,r)
bgRatio = np.divide(b,g)
grRatio = np.divide(g,r)
samples = np.column_stack((r,g,b,brRatio,bgRatio,grRatio))
示例#51
0
##import arcpy
##arcpy.CheckOutExtension("Spatial")

import matplotlib.pyplot as plt
import numpy as np
from skimage import io
from skimage.segmentation import quickshift

# The input 4-band NAIP image
river = r'C:\path\to\naip_image.tif'

# Convert image to numpy array
img = io.imread(river)

# Run the quick shift segmentation
segments = quickshift(img, kernel_size=3, convert2lab=False, max_dist=6, ratio=0.5)
print("Quickshift number of segments: %d" % len(np.unique(segments)))

# View the segments via Python
plt.imshow(segments)

### Get raster metrics for coordinate info
##myRaster = arcpy.sa.Raster(river)
##
### Lower left coordinate of block (in map units)
##mx = myRaster.extent.XMin
##my = myRaster.extent.YMin
##sr = myRaster.spatialReference
##
### Note the use of arcpy to convert numpy array to raster
##seg = arcpy.NumPyArrayToRaster(segments, arcpy.Point(mx, my),
示例#52
0
first_image_final = np.copy(first_image)


#first_image_edges = filter.canny(first_image, sigma=5)

#X = np.reshape(first_image, (-1, 1))
#connectivity = grid_to_graph(*first_image.shape)

###############################################################################
# Compute clustering
print("Compute structured hierarchical clustering...")
st = time.time()

#first_label = felzenszwalb(pil_image, scale=100, sigma=0.5, min_size=50)
#first_label = slic(pil_image, ratio=10, n_segments=250, sigma=1)
first_label = quickshift(pil_image, kernel_size=10, max_dist=80, ratio=0.1)
#ward = Ward(n_clusters=n_clusters, connectivity=connectivity, compute_full_tree=False).fit(X)

fig, ax = plt.subplots(1, 3)
fig.set_size_inches(8, 3, forward=True)
plt.subplots_adjust(0.05, 0.05, 0.95, 0.95, 0.05, 0.05)

ax[0].imshow(mark_boundaries(first_image_final, first_label))
ax[0].set_title("1st Image")


first_image_cluster_number = len(np.unique(first_label))

first_image = pl.mean(first_image,2)

first_label = np.reshape(first_label, first_image.shape)
示例#53
0
if len(images) < 1:
    raise IOError("No supported file formats found")


trainingSet = []
trainingSetClasses = []

for filePath in images:
    print "++++++++++++++++++++++++++++++++++++++++++++++++++++++"
    print "Loading ", filePath
    img = misc.imread(trainDir + "\\" + filePath)[:,:,:3]
    print "Image loaded. ", img.shape[0], " x ", img.shape[1]
    print "Segmenting..."
    t1 = datetime.now()
    segments = quickshift(img, kernel_size=qs_kernel_size, max_dist=qs_max_dist, ratio=qs_ratio)
    t2 = datetime.now()
    delta = t2 - t1
    seconds = delta.total_seconds()
    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)
    print "Segmentation complete in %d:%02d:%02d" % (h, m, s)
    print("Quickshift number of segments: %d" % len(np.unique(segments)))
    features = extractSegmentPropertiesRGB(segments,img)
    # Interactively label image
    labels = trainingSamplesMouse(img,segments,maxClasses=5)
    # Create trainingset
    trainingSet_, trainingSetClasses_ = createTrainingSet(labels,features)
    if len(trainingSet) > 0:
        trainingSet = np.row_stack((trainingSet,trainingSet_))
        trainingSetClasses = trainingSetClasses + trainingSetClasses_
示例#54
0
def watershedFunc2(imagePath, superPixMethod, trainingSeg=False):
    start = time.time()
    # image = np.asarray(Image.open('C:\Python34\palstaves2\\2013T482_Lower_Hardres_Canterbury\Axe1\IMG_3517.JPG'))
    image = np.asarray(Image.open(imagePath))

    # image = color.rgb2gray(image) --needed for watershed but not slic
    image = rescale(image, 0.25)  # 125)
    # plt.imshow(image)
    # plt.show()

    denoised = gaussian_filter(image, 1)  # was 2 before
    denoised = color.rgb2gray(denoised)
    # denoise image
    # denoised = rank.median(image, disk(2))
    # plt.imshow(denoised)
    # plt.show()
    # find continuous region (low gradient -
    # where less than 10 for this image) --> markers
    # disk(5) is used here to get a more smooth image
    print (type(denoised))
    # print(denoised)
    denoised -= 0.0000001  # as 1.0 max on denoised was giving errors in the markers
    print (np.max(denoised))
    print (np.min(denoised))
    slicSegments = 200
    if trainingSeg == False:
        markers = rank.gradient(denoised, disk(3)) < 8  # disk was 2 before, thresh was 10

        markers = ndi.label(markers)[0]
        # print(np.max(markers))
        # plt.imshow(gaussian_filter(markers, 4))
        # plt.show()
        # print(np.max(markers))
        # local gradient (disk(2) is used to keep edges thin)
        gradient = rank.gradient(denoised, disk(2))
        # plt.imshow(gradient)
        # plt.show()
        # process the watershed

        if superPixMethod == "combined":
            # print('water start')
            labels = 100000 * watershed(gradient, markers) + 1

            labels += slic(
                image,
                max_iter=3,
                compactness=10,
                enforce_connectivity=True,
                min_size_factor=0.01,
                n_segments=slicSegments,
            )

            # print('SLIC fin')
        elif superPixMethod == "watershed":
            labels = watershed(gradient, markers)
        elif superPixMethod == "SLIC":
            print ("here")
            # image = rescale(image,0.5)
            ##labels = felzenszwalb(image, scale=5, sigma=8, min_size=40)
            ##labels = quickshift(image,sigma = 3, kernel_size=3, max_dist=6, ratio=0.5)#kernel size was 3
            # labels = rescale(labels,2)

            # labels = 100000*watershed(gradient, markers)
            print ("test before errorBBB")
            labels = slic(
                image,
                max_iter=5,
                compactness=10,
                enforce_connectivity=True,
                min_size_factor=0.01,
                n_segments=slicSegments,
            )  # segements 200 was causing crash,compact was 10

            print ("after error")
            # plt.imshow(markers, interpolation='nearest')
            # plt.imshow(labels, interpolation='nearest',cmap="prism")
            # plt.imshow(image, interpolation='nearest', alpha=.8)
            # plt.show()
        elif superPixMethod == "None":
            labels = slic(
                image,
                max_iter=5,
                compactness=10,
                enforce_connectivity=True,
                min_size_factor=0.01,
                n_segments=slicSegments,
            )
        elif superPixMethod == "quickShift":
            labels = quickshift(image, kernel_size=3, max_dist=6, ratio=0.5)
        else:
            assert 1 == 2
    elif trainingSeg == True:
        markers = rank.gradient(denoised, disk(3)) < 8  # was 12 disk # disk was 2 before, thresh was 10

        markers = ndi.label(markers)[0]
        # print(np.max(markers))
        # plt.imshow(gaussian_filter(markers, 4))
        # plt.show()
        # print(np.max(markers))
        # local gradient (disk(2) is used to keep edges thin)
        gradient = rank.gradient(denoised, disk(2))
        # plt.imshow(gradient)
        # plt.show()
        # process the watershed
        if superPixMethod == "combined":
            # print('water start')
            labels = 100000 * watershed(gradient, markers) + 1

            labels += slic(
                image,
                max_iter=3,
                compactness=10,
                enforce_connectivity=True,
                min_size_factor=0.01,
                n_segments=slicSegments,
            )

            # print('SLIC fin')
        elif superPixMethod == "watershed":
            labels = watershed(gradient, markers)
        elif superPixMethod == "SLIC":
            print ("here")
            # image = rescale(image,0.5)
            ##labels = felzenszwalb(image, scale=5, sigma=8, min_size=40)
            ##labels = quickshift(image,sigma = 3, kernel_size=3, max_dist=6, ratio=0.5)#kernel size was 3
            # labels = rescale(labels,2)

            # labels = 100000+watershed(gradient, markers)
            labels = slic(
                image,
                max_iter=5,
                compactness=10,
                enforce_connectivity=True,
                min_size_factor=0.01,
                n_segments=slicSegments,
            )  # segements 200 was causing crash
            print ("here")
            # plt.imshow(markers, interpolation='nearest')
            # plt.imshow(labels, interpolation='nearest',cmap="prism")
            # plt.imshow(image, interpolation='nearest', alpha=.8)
            # plt.show()
        elif superPixMethod == "quickShift":
            labels = quickshift(image, kernel_size=3, max_dist=6, ratio=0.5)
        else:
            assert 1 == 2
    # print(labels.shape)
    # print(np.max(labels))
    labels = label(labels, connectivity=1)
    print ("Total numer of super pixels = " + str(np.max(labels)))

    # print(np.min(labels))
    ###labels = slic(image)
    # plt.imshow(labels)
    # plt.show()
    end = time.time()
    # print(np.max(markers))
    # print( end - start)
    return labels