示例#1
0
    def execute(input_image, settings):
        size = input_image.size
        size = (int(size[0] / 100), int(size[1] / 100))
        grayscale = input_image.convert('L')
        image_arr = np.array(img_as_ubyte(grayscale))
        denoised = rank.median(image_arr, disk(2))
        markers = rank.gradient(denoised, disk(5)) < 10
        markers = ndi.label(markers)[0]
        gradient = rank.gradient(denoised, disk(2))

        labels = watershed(gradient, markers)

        figure = plt.figure(frameon=False)
        ax = plt.Axes(figure, [0., 0., 1., 1.])
        ax.set_axis_off()
        figure.add_axes(ax)

        figure.set_size_inches(size)
        extent = mpl.transforms.Bbox(((0, 0), size))

        ax.imshow(labels, cmap=plt.cm.spectral, interpolation='nearest')

        buffer = io.BytesIO()
        figure.savefig(buffer, bbox_inches=extent, pad_inches=0, format='png')
        buffer.seek(0)
        return Image.open(buffer)
示例#2
0
    def compute(self, src):
        image = img_as_ubyte(src)

        # denoise image
        denoised = denoise_tv_chambolle(image, weight=0.05)
        denoised_equalize = exposure.equalize_hist(denoised)

        # find continuous region (low gradient) --> markers
        markers = rank.gradient(denoised_equalize, disk(5)) < 10
        markers = ndi.label(markers)[0]

        # local gradient
        gradient = rank.gradient(denoised, disk(2))

        # labels
        labels = watershed(gradient, markers)

        # display results
        fig, axes = plt.subplots(2, 3)
        axes[0, 0].imshow(
            image)  #, cmap=plt.cm.spectral, interpolation='nearest')
        axes[0, 1].imshow(denoised,
                          cmap=plt.cm.spectral,
                          interpolation='nearest')
        axes[0, 2].imshow(markers,
                          cmap=plt.cm.spectral,
                          interpolation='nearest')
        axes[1, 0].imshow(gradient,
                          cmap=plt.cm.spectral,
                          interpolation='nearest')
        axes[1, 1].imshow(labels,
                          cmap=plt.cm.spectral,
                          interpolation='nearest',
                          alpha=.7)
        plt.show()
示例#3
0
def _segment_trans(original_images, trans_args):
    """
    Segmentation of objects
    :param original_images:
    :param transformation:
    :return:
    """
    if len(original_images.shape) == 4:
        nb_images, img_rows, img_cols, nb_channels = original_images.shape
    else:
        nb_images, img_rows, img_cols = original_images.shape
        nb_channels = 1

    segment_trans = trans_args.get('subtype').lower()
    transformed_images = []
    if segment_trans == trans_utils.SEGMENT_TRANSFORMATIONS.GRADIENT.value:
        median_radius = trans_args.get('median_radius', 2)
        gradient_radius = trans_args.get('gradient_radius', 1)
        for img in original_images:
            # denoise image
            if (nb_channels == 3):
                img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
            img = img.reshape(img_rows, img_cols)
            denoised = rank.median(img, disk(median_radius))
            img_trans = rank.gradient(denoised, disk(gradient_radius))
            if (nb_channels == 3):
                img_trans = cv2.cvtColor(img_trans, cv2.COLOR_GRAY2RGB)
            transformed_images.append(img_trans)
    elif segment_trans == trans_utils.SEGMENT_TRANSFORMATIONS.WATERSHED.value:
        median_radius = trans_args.get('median_radius', 2)
        mark_radius = trans_args.get('mark_radius', 5)
        gradient_upper_bound = trans_args.get('gradient_upper_bound', 10)
        gradient_radius = trans_args.get('gradient_radius', 2)

        for img in original_images:
            if (nb_channels == 3):
                img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
            img = img.reshape((img_rows, img_cols))
            # denoise image
            denoised = rank.median(img, disk(median_radius))
            # find continuous region (low gradient -
            # where less than 10 for this image) --> markers
            markers = rank.gradient(denoised,
                                    disk(mark_radius)) < gradient_upper_bound
            markers = ndimage.label(markers)[0]
            # local gradient (disk(2) is used to keep edges thin)
            gradient = rank.gradient(denoised, disk(gradient_radius))
            img = watershed(gradient, markers)
            if (nb_channels == 3):
                img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
            transformed_images.append(img)
    else:
        raise ValueError('{} is not supported.'.format(segment_trans))

    # stack images
    transformed_images = np.stack(transformed_images, axis=0)
    if (nb_channels == 1):
        transformed_images = transformed_images.reshape(
            (nb_images, img_rows, img_cols, nb_channels))
    return np.array(transformed_images)
    def compute(self, src):
        image = img_as_ubyte(src)

        # denoise image
        denoised = denoise_tv_chambolle(image, weight=0.05)
        denoised_equalize= exposure.equalize_hist(denoised)

        # find continuous region (low gradient) --> markers
        markers = rank.gradient(denoised_equalize, disk(5)) < 10
        markers = ndi.label(markers)[0]

        # local gradient
        gradient = rank.gradient(denoised, disk(2))

        # labels
        labels = watershed(gradient, markers)

        # display results
        fig, axes = plt.subplots(2,3)
        axes[0, 0].imshow(image)#, cmap=plt.cm.spectral, interpolation='nearest')
        axes[0, 1].imshow(denoised, cmap=plt.cm.spectral, interpolation='nearest')
        axes[0, 2].imshow(markers, cmap=plt.cm.spectral, interpolation='nearest')
        axes[1, 0].imshow(gradient, cmap=plt.cm.spectral, interpolation='nearest')
        axes[1, 1].imshow(labels, cmap=plt.cm.spectral, interpolation='nearest', alpha=.7)
        plt.show()
 def watershed(self,img,smoothen = 5,extrasmoothen=2,con_grad=10,plot=True):
      smoothImg = rank.median(img, disk(smoothen))
      markers = rank.gradient(smoothImg, disk(smoothen)) < con_grad
      markers = ndi.label(markers)[0]
      gradient = rank.gradient(img, disk(extrasmoothen))
      
      labels = watershed(gradient, markers)
      if plot==True:
      
          fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8, 8),
                                   sharex=True, sharey=True)
          ax = axes.ravel()
          
          ax[0].imshow(img, cmap=plt.cm.gray)
          ax[0].set_title("Original")
          
          ax[1].imshow(gradient, cmap=plt.cm.nipy_spectral)
          ax[1].set_title("Local Gradient")
          
          ax[2].imshow(markers, cmap=plt.cm.nipy_spectral)
          ax[2].set_title("Markers")
          
          ax[3].imshow(img, cmap=plt.cm.gray)
          ax[3].imshow(labels, cmap=plt.cm.nipy_spectral, alpha=.7)
          ax[3].set_title("Segmented")
          
          for a in ax:
              a.axis('off')
          
          fig.tight_layout()
          plt.show()
      return labels
def filter_bank(img, coeff_resolution):
    """
    Calculates the responses of an image to M filters.
    Returns 2-d array of the vectorial responses
    """

    h, w = img.shape

    im = np.reshape(img, (h*w, 1))

    e1 = np.reshape(entropy(img, disk(coeff_resolution*5)), (h*w, 1))
    e2 = np.reshape(entropy(img, disk(coeff_resolution*8)), (h*w, 1))
    e3 = np.reshape(entropy(img, disk(coeff_resolution*10)), (h*w, 1))

    g1 = np.reshape(gradient(img, disk(1)), (h*w, 1))
    g2 = np.reshape(gradient(img, disk(coeff_resolution*3)), (h*w, 1))
    g3 = np.reshape(gradient(img, disk(coeff_resolution*5)), (h*w, 1))

    m1 = np.reshape(ndi.maximum_filter(256-img, size=coeff_resolution*2, mode='constant'), (h*w, 1))
    m2 = np.reshape(ndi.maximum_filter(256-img, size=coeff_resolution*4, mode='constant'), (h*w, 1))
    m3 = np.reshape(ndi.maximum_filter(256-img, size=coeff_resolution*7, mode='constant'), (h*w, 1))

    #c = np.reshape(canny(img), (h*w, 1))
    s = np.reshape(sobel(img), (h*w, 1))

    return np.column_stack((im, e1, e2, e3, g1, g2, g3, m1, m2, m3, s))
示例#7
0
def boundary_refinement_watershed2(X, Y_pred, save_marks_dir=None):
    """Apply watershed to the given predictions with the goal of refine the 
       boundaries of the artifacts. This function was implemented using scikit
       instead of opencv as :meth:`post_processing.boundary_refinement_watershed`.

       Based on https://scikit-image.org/docs/dev/auto_examples/segmentation/plot_watershed.html. 

       Parameters
       ----------
       X : 4D Numpy array
           Original data to guide the watershed. E.g. ``(img_number, x, y, channels)``.

       Y_pred : 4D Numpy array
           Predicted data to refine the boundaries. E.g. ``(img_number, x, y, channels)``.

       save_marks_dir : str, optional
           Directory to save the markers used to make the watershed. Useful for 
           debugging. 

       Returns
       -------
       Array : 4D Numpy array
           Refined boundaries of the predictions. E.g. ``(img_number, x, y, channels)``.
    """

    if save_marks_dir is not None:
        os.makedirs(save_marks_dir, exist_ok=True)

    watershed_predictions = np.zeros(Y_pred.shape[:3], dtype=np.uint8)
    d = len(str(X.shape[0]))

    for i in tqdm(range(X.shape[0])):

        im = (X[i, ..., 0] * 255).astype(np.uint8)
        pred = (Y_pred[i, ..., 0] * 255).astype(np.uint8)

        # find continuous region
        markers = rank.gradient(pred, disk(12)) < 10
        markers = ndi.label(markers)[0]

        # local gradient (disk(2) is used to keep edges thin)
        gradient = rank.gradient(im, disk(2))

        # process the watershed
        labels = watershed(gradient, markers)

        if save_marks_dir is not None:
            f = os.path.join(save_marks_dir,
                             "mark_" + str(i).zfill(d) + ".png")
            cv2.imwrite(f, markers)

        watershed_predictions[i] = labels

    # Label all artifacts into 1 and the background with 0
    watershed_predictions[watershed_predictions == 1] = 0
    watershed_predictions[watershed_predictions > 1] = 1

    return np.expand_dims(watershed_predictions, -1)
示例#8
0
def watershed_segment(data):

    marker = rank.gradient(data, disk(1)) < 10
    marker = ndi.label(marker)[0]

    gradient = rank.gradient(data, disk(1))
    result = watershed(gradient, marker)

    return {'marker': marker, 'gradient': gradient, 'watershed': result}
def watershed_segmentation(img):
    """Takes an image as input
    Returns the segmented image"""
    denoised = rank.median(img, disk(2))
    markers = rank.gradient(denoised, disk(5)) < 10
    markers = ndi.label(markers)[0]
    gradient = rank.gradient(denoised, disk(2))
    labels = watershed(gradient, markers)
    return segmentation.clear_border(labels)
    def transform(self, src):
        denoised = np.array([
            rank.median(np.power(10, (src[0]) / 10.),
                        morphology.disk(self.params['disk_radius'])),
            rank.median(np.power(10, (src[1]) / 10.),
                        morphology.disk(self.params['disk_radius']))
        ])
        # find continuous region (low gradient -
        # where less than 10 for this image) --> markers
        # disk(5) is used here to get a more smooth image
        markers = np.array([
            rank.gradient(denoised[0], disk(5)) < 10,
            rank.gradient(denoised[1], sk.morphology.disk(5)) < 10
        ])
        markers = ndi.label(markers)[0]
        # local gradient (disk(2) is used to keep edges thin)
        gradient = np.array([
            rank.gradient(denoised[0],
                          morphology.disk(self.params['disk_radius'])),
            rank.gradient(denoised[1],
                          morphology.disk(self.params['disk_radius']))
        ])
        # process the watershed
        labels = np.array(morphology.watershed(gradient, markers),
                          dtype='float')
        labels[np.isnan(src)] = np.NaN
        hist0 = np.histogram(labels[0].reshape(-1),
                             bins=[1, 2, 3, 4, 5],
                             normed=True,
                             range=(0, self.params['max_range']))[0]
        hist1 = np.histogram(labels[1].reshape(-1),
                             bins=[1, 2, 3, 4, 5],
                             normed=True,
                             range=(0, self.params['max_range']))[0]

        unique_labels = np.array(sorted(np.unique(labels)))
        unique_labels = unique_labels[~np.isnan(unique_labels)]
        label_means = {label: np.array([0, 0]) for label in range(int(7))}
        label_counts = {label: 0 for label in range(int(7))}
        label_idx = 0
        for label in unique_labels:
            label_means[label_idx] = np.nanmean(src[labels == label].reshape(
                2, -1),
                                                axis=1)
            label_counts[label_idx] = np.sum(~np.isnan(src[labels == label]))
            label_idx += 1
        sorted_labels = sorted(label_counts.items(), key=lambda x: x[1])[::-1]
        label_vals0 = np.array(
            [label_means[label[0]][0] for label in sorted_labels])
        label_vals1 = np.array(
            [label_means[label[0]][1] for label in sorted_labels])
        return [label_vals0, label_vals1]
示例#11
0
    def get_mask(self, img_path):
        imgray = io.imread(imgpath, as_grey=True)
        bw, label_image = self.get_label_image_with_otsu(imgray)

        denoised = rank.median(bw, disk(2))
        markers = rank.gradient(denoised, disk(21)) < 10
        markers = ndi.label(markers)[0]

        gradient = rank.gradient(denoised, disk(5))

        labels = watershed(gradient, markers)
        extracted_square = labels == 54  #Manually extract the label value
        filled_image = ndi.binary_fill_holes(extracted_square)
        return filled_image.astype('uint8') * 255
示例#12
0
    def im_watershed(self, image):
        # denoise image
        denoised = rank.median(image, disk(2))

        # find continuous region (low gradient -
        # where less than 10 for this image) --> markers
        # disk(5) is used here to get a more smooth image
        markers = rank.gradient(denoised, disk(5)) < 10
        markers = ndi.label(markers)[0]

        # local gradient (disk(2) is used to keep edges thin)
        gradient = rank.gradient(denoised, disk(2))

        # process the watershed
        self.labels = watershed(gradient, markers)

        # display results
        fig, axes = plt.subplots(nrows=2,
                                 ncols=2,
                                 figsize=(8, 8),
                                 sharex=True,
                                 sharey=True,
                                 subplot_kw={'adjustable': 'box-forced'})
        ax = axes.ravel()

        ax[0].imshow(image, cmap=plt.cm.gray, interpolation='nearest')
        ax[0].set_title("Original")

        ax[1].imshow(gradient, cmap=plt.cm.spectral, interpolation='nearest')
        ax[1].set_title("Local Gradient")

        ax[2].imshow(markers, cmap=plt.cm.spectral, interpolation='nearest')
        ax[2].set_title("Markers")

        ax[3].imshow(image, cmap=plt.cm.gray, interpolation='nearest')
        ax[3].imshow(labels,
                     cmap=plt.cm.spectral,
                     interpolation='nearest',
                     alpha=.7)
        ax[3].set_title("Segmented")

        for a in ax:
            a.axis('off')

        fig.tight_layout()
        plt.show()

        return labels
示例#13
0
def segmentations(original_images, transformation):
    """
    Segmentation of objects
    :param original_images:
    :param transformation:
    :return:
    """
    nb_images, img_rows, img_cols, nb_channels = original_images.shape
    # TODO: checking number of channels and some customization for datasets
    # TODO: more variations, after testing is done
    transformed_images = []

    if (transformation == TRANSFORMATION.seg_gradient):
        for img in original_images:
            # denoise image
            if (nb_channels == 3):
                img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
            img = img.reshape(img_rows, img_cols)
            denoised = rank.median(img, disk(2))
            img_trans = rank.gradient(denoised, disk(1))
            if (nb_channels == 3):
                img_trans = cv2.cvtColor(img_trans, cv2.COLOR_GRAY2RGB)
            transformed_images.append(img_trans)
    elif (transformation == TRANSFORMATION.seg_watershed):
        for img in original_images:
            img = img.reshape((img_rows, img_cols))
            # denoise image
            denoised = rank.median(img, disk(2))
            # find continuous region (low gradient -
            # where less than 10 for this image) --> markers
            markers = rank.gradient(denoised, disk(5)) < 10
            markers = ndimage.label(markers)[0]
            # local gradient (disk(2) is used to keep edges thin)
            gradient = rank.gradient(denoised, disk(2))
            img_trans = watershed(gradient, markers)
            transformed_images.append(img_trans)
    else:
        raise ValueError('{} is not supported.'.format(transformation))
    """
    stack images
    """
    transformed_images = np.stack(transformed_images, axis=0)

    if (nb_channels == 1):
        transformed_images = transformed_images.reshape(
            (nb_images, img_rows, img_cols, nb_channels))

    return np.array(transformed_images)
示例#14
0
def segm_watershed(input_image,
                   gradient_level=10,
                   denoised_d_radius=10,
                   rank_d_radius=2,
                   compactness=1):
    """Función para generar la segmentación mediante la técnica
    de WaterShed.

    Args:
        input_image ([Numpy Array]): Imagen de entrada sobre la que obtener
                                    la segmentación.
        gradient_level (int, optional): Nivel del gradiente para encontrar regiones
                                        continuas. Defaults to 10.
        denoised_d_radius (int, optional): Radio del elemento morfologico 'diamond'
                                           para obtener una imagen más suave.Defaults to 10.
        rank_d_radius (int, optional): Radio del elemento morfológico 'diamond'
                                       para expresar la vecindad. Defaults to 2.
        compactness (int, optional): A mayor valor, se dan lugar cuencas de forma más regular.
                                     Defaults to 1.

    Returns:
        Tuple (output image, labels, number classes): Tupla con la imagen
                                            segmentada, las etiquetas y el número
                                            total de segmentos encontrados.
    """
    input_image = rgb2gray(input_image)
    # denoise image
    denoised = rank.median(input_image, diamond(denoised_d_radius))

    # find continuous region (low gradient -
    # where less than 10 for this image) --> markers
    # disk(5) is used here to get a more smooth image
    markers = rank.gradient(denoised, diamond(rank_d_radius)) < gradient_level
    markers = ndi.label(markers)[0]

    # local gradient (disk(2) is used to keep edges thin)
    gradient = rank.gradient(denoised, diamond(5))

    # process the watershed
    segments_watershed = watershed(gradient, markers, compactness=compactness)

    output_image = mark_boundaries(input_image, segments_watershed)
    labeled_ws = color.label2rgb(segments_watershed,
                                 input_image,
                                 kind='avg',
                                 bg_label=0)

    return (output_image, labeled_ws, len(np.unique(segments_watershed)))
示例#15
0
def segment(brain_img):
    '''
    Segmenting regions of the brain using watershed function
    '''
    # get the low gradient
    markers = rank.gradient(brain_img, disk(5)) < 20

    markers = ndi.label(markers)[0]

    # get the local gradient
    gradient = rank.gradient(brain_img, disk(1))

    # process the watershed
    labels = watershed(gradient, markers)

    return labels
示例#16
0
    def update_segmentation(self):
        """
        return: 2D array with same dimension (x, y) as input image.

        !!! Implemented is a simple watershed, override for custom algorithm !!!
        """
        gradient = rank.gradient(self.img, disk(2))
        return watershed(gradient, self.mask)
示例#17
0
def freespace_detection(colorframe,scaleDownFactor=4, roadROIStartBelowGivenRowIndex=2):
   
    frame_gray = cv2.cvtColor(colorframe, cv2.COLOR_BGR2GRAY)
    frame_small_gray = cv2.resize(frame_gray, (0,0), fx=1/float(scaleDownFactor), fy=1/float(scaleDownFactor))
    roi_for_road_gray = frame_small_gray[(roadROIStartBelowGivenRowIndex/scaleDownFactor):,:]

    # Median Filter
    denoised = cv2.medianBlur(roi_for_road_gray, 3)
   
    # find continuous region (low gradient -
    # where less than 10 for this image) --> markers
    #disk(5) is used here to get a more smooth image
    # Valuse hardcoded (tuned to test video)
    markers = rank.gradient(denoised, disk(5)) < 27
    markers = ndi.label(markers)[0]
    
    # local gradient (disk(2) is used to keep edges thin)
    gradient = rank.gradient(denoised, disk(2))
    
    # process the watershed
    labels = watershed(gradient, markers)
    
    # Assumption 2: Car will be always on road, so region just in front of car
    # will  be a road segment.
    # Values are hardcoded
    rowStart = (420/scaleDownFactor) - (roadROIStartBelowGivenRowIndex/scaleDownFactor)
    rowEnd = 500/scaleDownFactor
    colStart = 200/scaleDownFactor
    colEnd   = 500/scaleDownFactor
                        
    #road_segment = frame_small[rowStart:rowEnd, colStart:colEnd]
    road_segment_labels = set(np.unique(labels[rowStart:rowEnd, colStart:colEnd]))
                                
    # Road Non-road mask
    road_mask = np.zeros((frame_small_gray.shape[0], frame_small_gray.shape[1],3) , dtype=np.uint8)
    #road_mask = np.zeros(frame_small_color.shape , dtype=np.uint8)
    # Todo: Find pythonic way to do below computaion efficiently
    for i in range(labels.shape[0]):
        for j in range(labels.shape[1]):
            if labels[i,j] in road_segment_labels:
                road_mask[(roadROIStartBelowGivenRowIndex/scaleDownFactor)+i,j, 1] = 255

    road_mask = cv2.resize(road_mask, (0,0), fx=scaleDownFactor, fy=scaleDownFactor)
    detected_road = cv2.addWeighted(colorframe,0.7, road_mask ,0.3,0)
    return (detected_road,road_mask[:,:,1])
示例#18
0
def create_bin_img_watershed(image):

    img = color.rgb2gray(image)
    denoised = rank.median(img, morphology.disk(1))

    markers = rank.gradient(denoised, morphology.disk(4)) < 20
    markers = ndi.label(markers)[0]

    gradient = rank.gradient(denoised, morphology.disk(2))

    labels = morphology.watershed(gradient, markers)
    binary = np.zeros((labels.shape[0], labels.shape[1]), dtype='float64')

    for r in measure.regionprops(labels):
        if r.label != 1:
            rr, cc = zip(*r.coords)
            binary[rr, cc] = 1

    fig, axes = plt.subplots(nrows=2,
                             ncols=2,
                             figsize=(8, 8),
                             sharex=True,
                             sharey=True,
                             subplot_kw={'adjustable': 'box-forced'})
    ax = axes.ravel()

    ax[0].imshow(denoised, cmap='gray', interpolation='nearest')
    ax[0].set_title('Denoised')

    ax[1].imshow(gradient, cmap='spectral', interpolation='nearest')
    ax[1].set_title('Local Gradient')

    ax[2].imshow(markers, cmap='spectral', interpolation='nearest')
    ax[2].set_title('markers')

    ax[3].imshow(img, cmap='gray', interpolation='nearest')
    ax[3].imshow(labels, cmap='spectral', interpolation='nearest', alpha=.7)
    ax[3].set_title("Segmented")

    for a in ax:
        a.axis('off')

    fig.tight_layout()

    return binary, False
def watershed_edges(img,
                    ws_mdisk_size=5,
                    ws_mthreshold=20,
                    ws_gdisk_size=2,
                    ws_glevel_threshold=4):
    image = img.copy()
    image = img_as_ubyte(image)
    markers = rank.gradient(image, disk(ws_mdisk_size)) < ws_mthreshold
    markers = ndi.label(markers)[0]
    gradient = rank.gradient(image, disk(ws_gdisk_size))
    labels = watershed(gradient, markers)
    # show_images([image, labels], ["edges", "edges' labels"])
    labels[labels <= ws_glevel_threshold] = 1
    labels[labels > ws_glevel_threshold] = 0
    labels = np.invert(labels)
    labels[labels == -1] = 1
    labels[labels == -2] = 0
    return labels
示例#20
0
def togray(image):
    image_bw = rgb2gray(image)
    # using the entropy
    #image_e = entropy(image_bw,disk(1))
    #return energy(image_e)

    # using gradient
    image_g = gradient(image_bw, disk(1))
    return image_g
示例#21
0
        def check_all():
            selem = morphology.disk(1)
            refs = np.load(
                os.path.join(skimage.data_dir, "rank_filter_tests.npz"))

            assert_equal(refs["autolevel"], rank.autolevel(self.image, selem))
            assert_equal(refs["autolevel_percentile"],
                         rank.autolevel_percentile(self.image, selem))
            assert_equal(refs["bottomhat"], rank.bottomhat(self.image, selem))
            assert_equal(refs["equalize"], rank.equalize(self.image, selem))
            assert_equal(refs["gradient"], rank.gradient(self.image, selem))
            assert_equal(refs["gradient_percentile"],
                         rank.gradient_percentile(self.image, selem))
            assert_equal(refs["maximum"], rank.maximum(self.image, selem))
            assert_equal(refs["mean"], rank.mean(self.image, selem))
            assert_equal(refs["geometric_mean"],
                         rank.geometric_mean(self.image, selem)),
            assert_equal(refs["mean_percentile"],
                         rank.mean_percentile(self.image, selem))
            assert_equal(refs["mean_bilateral"],
                         rank.mean_bilateral(self.image, selem))
            assert_equal(refs["subtract_mean"],
                         rank.subtract_mean(self.image, selem))
            assert_equal(refs["subtract_mean_percentile"],
                         rank.subtract_mean_percentile(self.image, selem))
            assert_equal(refs["median"], rank.median(self.image, selem))
            assert_equal(refs["minimum"], rank.minimum(self.image, selem))
            assert_equal(refs["modal"], rank.modal(self.image, selem))
            assert_equal(refs["enhance_contrast"],
                         rank.enhance_contrast(self.image, selem))
            assert_equal(refs["enhance_contrast_percentile"],
                         rank.enhance_contrast_percentile(self.image, selem))
            assert_equal(refs["pop"], rank.pop(self.image, selem))
            assert_equal(refs["pop_percentile"],
                         rank.pop_percentile(self.image, selem))
            assert_equal(refs["pop_bilateral"],
                         rank.pop_bilateral(self.image, selem))
            assert_equal(refs["sum"], rank.sum(self.image, selem))
            assert_equal(refs["sum_bilateral"],
                         rank.sum_bilateral(self.image, selem))
            assert_equal(refs["sum_percentile"],
                         rank.sum_percentile(self.image, selem))
            assert_equal(refs["threshold"], rank.threshold(self.image, selem))
            assert_equal(refs["threshold_percentile"],
                         rank.threshold_percentile(self.image, selem))
            assert_equal(refs["tophat"], rank.tophat(self.image, selem))
            assert_equal(refs["noise_filter"],
                         rank.noise_filter(self.image, selem))
            assert_equal(refs["entropy"], rank.entropy(self.image, selem))
            assert_equal(refs["otsu"], rank.otsu(self.image, selem))
            assert_equal(refs["percentile"],
                         rank.percentile(self.image, selem))
            assert_equal(refs["windowed_histogram"],
                         rank.windowed_histogram(self.image, selem))
示例#22
0
def preprocessing(observation):
    observation[(observation == 107)] = 0
    observation[(observation == 142)] = 0
    observation[(observation == 103)] = 0
    observation[(observation == 185)] = 0
    observation[(observation == 117)] = 0
    observation[(observation == 218)] = 0
    observation[(observation == 128)] = 0
    noisy_image = img_as_ubyte(observation)
    # Edge detection
    grad = gradient(noisy_image, disk(5))
    return resize(grad, (80, 80))
示例#23
0
def sharpness(image_paths):
    sharpness = []

    selection_element = disk(5)  # matrix of n pixels with a disk shape

    for path in image_paths:
        img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
        img_sharpness = gradient(img, selection_element)
        img_sharpness_f = np.asarray(img_sharpness).flatten()
        sharpness.append(np.average(img_sharpness_f))
    sharpness = np.transpose([np.array(sharpness)])
    return sharpness
示例#24
0
def create_bin_img_watershed(image, send_func):

    img = color.rgb2gray(image)
    denoised = rank.median(img, morphology.disk(1))

    markers = rank.gradient(denoised, morphology.disk(4)) < 20
    markers = ndi.label(markers)[0]
    send_func(("img", markers), 0.5)

    gradient = rank.gradient(denoised, morphology.disk(2))
    send_func(("img", gradient), 0.5)

    labels = morphology.watershed(gradient, markers)
    send_func(("img", labels), 0.5)
    binary = np.zeros((labels.shape[0], labels.shape[1]), dtype='float64')

    for r in measure.regionprops(labels):
        if r.label != 1:
            rr, cc = zip(*r.coords)
            binary[rr, cc] = 1

    return binary, False
示例#25
0
def water_segmentation(path, hue, d1, d2, v, d3):

    image = img_as_ubyte(hue)
    image_original = sd.imread(path)
    image_gray = img_as_ubyte(sd.imread(path, as_grey=True))

    # denoise image
    denoised = rank.median(image, disk(d1))
    denoised_gray = rank.median(image_gray)

    # find continuous region (low gradient - where less than 10 for this image) --> markers
    # disk(5) is used here to get a more smooth image
    markers = rank.gradient(denoised, disk(d2)) < v
    markers = nd.label(markers)[0]

    # local gradient (disk(2) is used to keep edges thin)
    gradient = rank.gradient(denoised, disk(d3))

    # process the watershed
    labels = watershed(gradient, markers)

    return image, image_original, denoised, markers, gradient, labels
示例#26
0
def watershed_segmentation(image):
    image = img_as_ubyte(image)

    denoised = rank.median(image, disk(2))

    # find continuous region (low gradient -
    # where less than 10 for this image) --> markers
    # disk(5) is used here to get a more smooth image
    markers = rank.gradient(denoised, disk(1)) < 10
    markers = ndi.label(markers)[0]

    # local gradient (disk(2) is used to keep edges thin)
    gradient = rank.gradient(denoised, disk(2))

    thr = filters.threshold_yen(image)
    bw_img = image < thr
    bw_img = skimage.morphology.erosion(bw_img, disk(3))
    # close holes, size check
    label_image = skimage.morphology.remove_small_holes(bw_img,
                                                        area_threshold=625)
    label_image = skimage.morphology.remove_small_objects(label_image,
                                                          min_size=100)
    label_image = measure.label(label_image, background=0)

    markers = skimage.morphology.erosion(label_image, disk(1))
    # process the watershed
    labels = watershed(gradient, label_image)
    counter = 1
    config = '/Users/reganlamoureux/new_watershed_images/watershed_image_set2_{}.png'.format(
        counter)
    while os.path.exists(config):
        counter += 1
        config = '/Users/reganlamoureux/new_watershed_images/watershed_image_set2_{}.png'.format(
            counter)
    plt.imsave(config, labels)

    return labels
示例#27
0
    def preprocess(self,
                   *,
                   values=None,
                   water_ntile=10,
                   lake_flatness=3,
                   vertical_ratio=40):
        """Default preprocessing.

        You can do this yourself, and pass an array directly to plot_map. This
        gathers all nan values, the lowest `water_ntile` percentile of elevations,
        and anything that is flat enough, and sets the values to `nan`, so no line
        is drawn. It also exaggerates the vertical scale, which can be nice for flat
        or mountainy areas.

        Parameters
        ----------
        values : np.ndarray
            An array to process, or fetch the elevation data lazily here.
        water_ntile : float in [0, 100]
            Percentile below which to delete data. Useful for coasts or rivers.
            Set to 0 to not delete any data.
        lake_flatness : int
            How much the elevation can change within 3 squares to delete data.
            Higher values delete more data. Useful for rivers, lakes, oceans.
        vertical_ratio : float > 0
            How much to exaggerate hills. Kind of arbitrary. 40 is reasonable,
            but try bigger and smaller values!

        Returns
        -------
        np.ndarray
            Processed data.
        """

        if values is None:
            values = self.get_elevation_data()
        nan_vals = np.isnan(values)

        values[nan_vals] = np.nanmin(values)
        values = (values - np.min(values)) / (np.max(values) - np.min(values))

        is_water = values < np.percentile(values, water_ntile)
        is_lake = rank.gradient(img_as_ubyte(values),
                                square(3)) < lake_flatness

        values[nan_vals] = np.nan
        values[np.logical_or(is_water, is_lake)] = np.nan
        values = vertical_ratio * values[-1::-1]  # switch north and south
        return values
示例#28
0
def Watershed():
    image = skimage.io.imread('useforwatershed.TIF', as_grey=True)

    # denoise image
    denoised = rank.median(image, disk(10))

    # find continuous region (low gradient) --> markers
    markers = rank.gradient(denoised, disk(5)) < 10
    markers = ndimage.label(markers)[0]

    #local gradient
    gradient = rank.gradient(denoised, disk(2))

    # process the watershed
    labels = watershed(gradient, markers)

    # display results
    fig, axes = plt.subplots(ncols=4, figsize=(8, 2.7))
    ax0, ax1, ax2, ax3 = axes

    ax0.imshow(image, cmap=plt.cm.gray, interpolation='nearest')
    ax1.imshow(gradient, cmap=plt.cm.spectral, interpolation='nearest')
    ax2.imshow(markers, cmap=plt.cm.spectral, interpolation='nearest')
    ax3.imshow(image, cmap=plt.cm.gray, interpolation='nearest')
    ax3.imshow(labels, cmap=plt.cm.spectral, interpolation='nearest', alpha=.7)

    for ax in axes:
        ax.axis('off')

    plt.subplots_adjust(hspace=0.01,
                        wspace=0.01,
                        top=1,
                        bottom=0,
                        left=0,
                        right=1)
    plt.show()
示例#29
0
def watershedSegmentation(frame):
    pram_file = open("watershed.json")
    param = json.load(pram_file)

    im = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    denoised = rank.median(im, disk(2))
    markers = rank.gradient(denoised, disk(5)) < 10
    markers = ndi.label(markers)[0]

    # local gradient (disk(2) is used to keep edges thin)
    gradient = rank.gradient(denoised, disk(2))

    segments = watershed(gradient,
                         markers=param["markers"],
                         connectivity=param["connectivity"],
                         offset=param["offset"],
                         mask=param["mask"],
                         compactness=param["compactness"],
                         watershed_line=param["watershed_line"])
    segment_img_gray = np.array(segments, dtype=np.uint8)
    segment_img_gray = segment_img_gray * (255 // np.max(segments))
    segment_img_color = cv2.applyColorMap(segment_img_gray, cv2.COLORMAP_JET)
    return segment_img_color
示例#30
0
def segmentation(file, model, trPath):

    imgOri = cv2.imread(file, cv2.IMREAD_UNCHANGED)  # read img

    # GaussianBlur
    img = cv2.GaussianBlur(imgOri, (5, 5), 0)  # de-noise

    # Gray
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # go gray

    # gradient
    gradient = rank.gradient(img, disk(2))
    # find markers
    markers = np.zeros_like(img)
    markers[img < np.max(gradient) * gradThrLo] = 1
    markers[img > np.max(gradient) * gradThrHi] = 2

    # fill regions with watershed transform
    segmentation = watershed(gradient, markers)  # 1,2
    #print(gradient[700], markers[700])
    #show2( markers, 'markers', gradient, 'gradient')

    # patch holes 10001
    segmentation = ndi.binary_fill_holes(segmentation - 1,
                                         structure=np.ones(
                                             (patchHoleSize, 1)))  # 0,1
    labeledShip, _ = ndi.label(segmentation)  # 0,3

    # threshold image
    segmentation = segmentation.astype(np.uint8) * 255
    imgMask = np.zeros(segmentation.shape,
                       np.uint8)  # Image to draw the contours
    contours, hierarchy = cv2.findContours(segmentation, cv2.RETR_TREE,
                                           cv2.CHAIN_APPROX_SIMPLE)
    for cnt in contours:
        rect = cv2.minAreaRect(cnt)
        box = cv2.boxPoints(rect)
        box = np.int0(box)
        cv2.drawContours(imgMask, [cnt], 0, (0, 0, 255),
                         2)  # draw contours in green color
        cv2.polylines(imgMask, [box], True, (255, 0, 0),
                      2)  # draw rectangle in blue color

    # fill holes in mask
    imgMask = ndi.binary_fill_holes(imgMask)
    #show2(imgOri, 'Input', imgMask, 'Mask')

    return imgMask
示例#31
0
def pdf_segments(pdf, labels, base=0.1, borders=1, import_borders=False):

    grad = gradient(labels, disk(1))
    edges = peak_local_max(
        grad, min_distance=0, threshold_rel=0, indices=False) * 1
    if import_borders:
        edges = borders
    baseline = pdf.max() * base

    border_pdf = np.zeros(np.shape(edges))
    for i in range(np.shape(edges)[0]):
        for j in range(np.shape(edges)[1]):
            if edges[i, j] != 0:
                edges[i, j] = 1
            else:
                border_pdf[i, j] = pdf[i, j] + baseline

    edges_b = edges.astype(bool)
    edges_b = ndimage.binary_dilation(edges_b, iterations=1)
    return border_pdf, edges, edges_b
示例#32
0
def breaking_segments(skel, dist_trans, threshold = 0.5):
    yskel, xskel = np.where(skel)
    distances = dist_trans[yskel,xskel]
    min_dist, max_dist = distances.min(), distances.max()
    
    kde = KernelDensity(kernel='gaussian', bandwidth=3).fit(distances.reshape(-1,1))
    s = np.linspace(min_dist, max_dist)
    e = kde.score_samples(s.reshape(-1,1))
    
    
    plt.figure(figsize=(6,6))
    plt.hist(distances, bins = 50)
    plt.xlabel('Distance to border in pixels')
    plt.ylabel('Number of pixels')
    plt.title('Histogram of distances to border')
    plt.show()
    
    plt.figure(figsize=(6,6))
    plt.plot(s, e)
    plt.xlabel('Distance to border in pixels')
    plt.ylabel('Density')
    plt.title('Estimated density of distances to border')
    plt.show()
    
    mi = argrelextrema(e, np.less)[0]
    
    if len(mi) < 1:
        return np.zeros(skel.shape)
    
    overlap = np.zeros(skel.shape, np.int)
    overlap += binary_dilation((dist_trans < s[mi[0]]), square(3))
    for i in range(1,len(mi)):
        overlap += binary_dilation((s[mi[i-1]] < dist_trans)*(s[mi[i]] > dist_trans), square(3))
    overlap += binary_dilation((dist_trans > s[mi[-1]]), square(3))
    
    return skel*(overlap > 1)
    
    smooth_dist_trans = gaussian(dist_trans, sigma=10)
    grad = gradient(smooth_dist_trans/smooth_dist_trans.max(), disk(3))
    grad = (skel*grad).astype(np.float32)/(smooth_dist_trans+1)
    return (grad > 0.5)
示例#33
0
def check_all():
    np.random.seed(0)
    image = np.random.rand(25, 25)
    selem = morphology.disk(1)
    refs = np.load(os.path.join(skimage.data_dir, "rank_filter_tests.npz"))

    assert_equal(refs["autolevel"], rank.autolevel(image, selem))
    assert_equal(refs["autolevel_percentile"], rank.autolevel_percentile(image, selem))
    assert_equal(refs["bottomhat"], rank.bottomhat(image, selem))
    assert_equal(refs["equalize"], rank.equalize(image, selem))
    assert_equal(refs["gradient"], rank.gradient(image, selem))
    assert_equal(refs["gradient_percentile"], rank.gradient_percentile(image, selem))
    assert_equal(refs["maximum"], rank.maximum(image, selem))
    assert_equal(refs["mean"], rank.mean(image, selem))
    assert_equal(refs["mean_percentile"], rank.mean_percentile(image, selem))
    assert_equal(refs["mean_bilateral"], rank.mean_bilateral(image, selem))
    assert_equal(refs["subtract_mean"], rank.subtract_mean(image, selem))
    assert_equal(refs["subtract_mean_percentile"], rank.subtract_mean_percentile(image, selem))
    assert_equal(refs["median"], rank.median(image, selem))
    assert_equal(refs["minimum"], rank.minimum(image, selem))
    assert_equal(refs["modal"], rank.modal(image, selem))
    assert_equal(refs["enhance_contrast"], rank.enhance_contrast(image, selem))
    assert_equal(refs["enhance_contrast_percentile"], rank.enhance_contrast_percentile(image, selem))
    assert_equal(refs["pop"], rank.pop(image, selem))
    assert_equal(refs["pop_percentile"], rank.pop_percentile(image, selem))
    assert_equal(refs["pop_bilateral"], rank.pop_bilateral(image, selem))
    assert_equal(refs["sum"], rank.sum(image, selem))
    assert_equal(refs["sum_bilateral"], rank.sum_bilateral(image, selem))
    assert_equal(refs["sum_percentile"], rank.sum_percentile(image, selem))
    assert_equal(refs["threshold"], rank.threshold(image, selem))
    assert_equal(refs["threshold_percentile"], rank.threshold_percentile(image, selem))
    assert_equal(refs["tophat"], rank.tophat(image, selem))
    assert_equal(refs["noise_filter"], rank.noise_filter(image, selem))
    assert_equal(refs["entropy"], rank.entropy(image, selem))
    assert_equal(refs["otsu"], rank.otsu(image, selem))
    assert_equal(refs["percentile"], rank.percentile(image, selem))
    assert_equal(refs["windowed_histogram"], rank.windowed_histogram(image, selem))
示例#34
0
#
# .. note::
#
#     `skimage.dilate` and `skimage.erode` are equivalent filters (see below
#     for comparison).
#
# Here is an example of the classical morphological gray-level filters:
# opening, closing and morphological gradient.

from skimage.filters.rank import maximum, minimum, gradient

noisy_image = img_as_ubyte(data.camera())

closing = maximum(minimum(noisy_image, disk(5)), disk(5))
opening = minimum(maximum(noisy_image, disk(5)), disk(5))
grad = gradient(noisy_image, disk(5))

# display results
fig, ax = plt.subplots(2, 2, figsize=[10, 7], sharex=True, sharey=True)
ax1, ax2, ax3, ax4 = ax.ravel()

ax1.imshow(noisy_image, cmap=plt.cm.gray)
ax1.set_title('Original')

ax2.imshow(closing, cmap=plt.cm.gray)
ax2.set_title('Gray-level closing')

ax3.imshow(opening, cmap=plt.cm.gray)
ax3.set_title('Gray-level opening')

ax4.imshow(grad, cmap=plt.cm.gray)

#%% gradient

import cv2
imgl = cv2.Laplacian(imgs,cv2.CV_64F)

import skimage.filters.rank as rkf
from skimage.morphology import disk

imgn = imgs.copy();
imgn[imgn < 50] = 50;
imgn[imgn > 100] = 100;
imgn = np.array((imgn -50) / 50 * 255, dtype = 'uint16');

imgg = rkf.gradient(imgn, disk(1))


plt.figure(3); plt.clf();
for i,j in enumerate([imgn, imgg]):
  plt.subplot(1,2,i+1);
  plt.imshow(j)



#%% process images

import imageprocessing.contours as cts;

cont = cts.detect_contour(imgs, level = 77 );
from skimage.morphology import watershed, disk
from skimage import data
from skimage.filters import rank
from skimage.util import img_as_ubyte


image = img_as_ubyte(data.camera())

# denoise image
denoised = rank.median(image, disk(2))

# find continuous region (low gradient -
# where less than 10 for this image) --> markers
# disk(5) is used here to get a more smooth image
markers = rank.gradient(denoised, disk(5)) < 10
markers = ndi.label(markers)[0]

# local gradient (disk(2) is used to keep edges thin)
gradient = rank.gradient(denoised, disk(2))

# process the watershed
labels = watershed(gradient, markers)

# display results
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8, 8),
                         sharex=True, sharey=True)
ax = axes.ravel()

ax[0].imshow(image, cmap=plt.cm.gray, interpolation='nearest')
ax[0].set_title("Original")
示例#37
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
示例#38
0
denoised = gaussian_filter(image, 1)
denoisedR = denoised[...,0]
denoisedG = denoised[...,1]
denoisedB = np.asarray(denoised[...,2])
denoisedB -= 0.000000000001
# denoise image
#denoised = rank.median(image, disk(2))

# 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(np.max(denoisedB))
print(np.max(denoisedG))
print(np.max(denoisedR))
c = (rank.gradient(denoisedB, disk(2)))
print(np.max(denoisedB))
print(denoisedG[5,5])
print(np.max(((np.maximum((rank.gradient(denoisedR, disk(2))),(rank.gradient(denoisedG, disk(2))))))))
print(np.max((rank.gradient(denoisedB, disk(2)))))
#markers = (np.maximum(np.maximum((rank.gradient(denoisedR, disk(1))),(rank.gradient(denoisedG, disk(1)))),
#(rank.gradient(denoisedB, disk(1)))) < 10)


# local gradient (disk(2) is used to keep edges thin)
denoised = color.rgb2gray(denoised) # denisoed disk 2
markers = (rank.gradient(denoised, disk(3))<8)#disk(3))<10)#disk(2)) < 18) # disk 4 works well with thresh 8 and guass 2 # try disk 5 <10
markers = ndi.label(markers)[0]
#markers = markers*np.random.rand(markers.shape[0],markers.shape[1])
print('npmax markers')
print(np.max(markers))
示例#39
0
    
fig = plt.figure()

sigma=3
disk_val=3

mypic_rev_small = mypic_rev[120:200,:]
mypic_rev = mypic_rev
mypic_rev_log = np.log10(mypic_rev+ 0.001)
mypic_rev_gauss = sp.ndimage.gaussian_filter(mypic_rev, sigma=sigma)
mypic_rev_log_gauss = sp.ndimage.gaussian_filter(mypic_rev_log, sigma=sigma)
mypic_rev_gauss_bin = mypic_rev_gauss > np.percentile(mypic_rev_gauss, p)
mypic_rev_log_gauss_bin = mypic_rev_log_gauss > np.percentile(mypic_rev_log_gauss,p)
mypic_rev_gauss_bin_close =sp.ndimage.binary_closing( sp.ndimage.binary_opening(mypic_rev_gauss_bin))
mypic_rev_log_gauss_bin_close =sp.ndimage.binary_closing( sp.ndimage.binary_opening(mypic_rev_log_gauss_bin))
mypic_rev_gauss_grad = rank.gradient(pic_to_ubyte(mypic_rev_gauss), disk(disk_val))
mypic_rev_log_gauss_grad = rank.gradient(pic_to_ubyte(mypic_rev_log_gauss), disk(disk_val))
mypic_rev_gauss_grad_bin = mypic_rev_gauss_grad > np.percentile(mypic_rev_gauss_grad,p)
mypic_rev_log_gauss_grad_bin = mypic_rev_log_gauss_grad > np.percentile(mypic_rev_log_gauss_grad,p )
mypic_rev_gauss_grad_bin_close =sp.ndimage.binary_closing( sp.ndimage.binary_opening(mypic_rev_gauss_grad_bin))
mypic_rev_log_gauss_grad_bin_close =sp.ndimage.binary_closing( sp.ndimage.binary_opening(mypic_rev_log_gauss_grad_bin))
bfh = sp.ndimage.binary_fill_holes(mypic_rev_gauss_grad_bin_close)        
bfh_rm = remove_small_objects(bfh, MIN_SEGMENT_SIZE)
log_bfh = sp.ndimage.binary_fill_holes(mypic_rev_log_gauss_grad_bin_close)        
log_bfh_rm = remove_small_objects(log_bfh, MIN_SEGMENT_SIZE)

labeled_segments, num_seg = sp.ndimage.label(bfh_rm)

#plt.subplot(6,2,1)
#plt.imshow(mypic_rev,cmap=plt.cm.afmhot_r)
#plt.axis('off')
示例#40
0
geo = gdal.Open(image_path[0]) 
band1 = geo.GetRasterBand(1)
band2 = geo.GetRasterBand(2)
band3 = geo.GetRasterBand(3)
red = band1.ReadAsArray()
green = band2.ReadAsArray()
blue = band3.ReadAsArray()

dms = (0.299*red + 0.587*green + 0.114*blue)
#normalize
dms=dms/np.amax(dms)
#dms = ma.masked_where(dms<1, dms)
#print '1'
#denoised = rank.median(dms, disk(2))
print '2'
markers = rank.gradient(dms, disk(5)) < 10
# disk(5) is used here to get a more smooth image
print '3'
markers = ndimage.label(markers)[0]
print '4'
#gradient = rank.gradient(dms, disk(2))
print '5'
labels = watershed(dms, markers)
print '6'

trans = geo.GetGeoTransform()
width = geo.RasterXSize
height = geo.RasterYSize

x1 = np.linspace(trans[0], trans[0] + width*trans[1] + height*trans[2], width)
y1 = np.linspace(trans[3], trans[3] + width*trans[4] + height*trans[5], height)