Python skimage.feature() Examples

The following are 18 code examples of skimage.feature(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module skimage , or try the search function .
Example #1
Source File: blob.py    From eo-learn with MIT License 5 votes vote down vote up
def __init__(self, feature, *, num_sigma=10, log_scale=False, min_sigma=1, max_sigma=30, threshold=0.1, overlap=0.5,
                 **kwargs):
        super().__init__(feature, skimage.feature.blob_log, num_sigma=num_sigma, log_scale=log_scale,
                         min_sigma=min_sigma, max_sigma=max_sigma, threshold=threshold, overlap=overlap, **kwargs) 
Example #2
Source File: imgproc.py    From rps-cv with MIT License 5 votes vote down vote up
def getGray(img, hueValue=63, threshold=0):
    """Returns the grayscale of the source image with its background
    removed as a 1D feature vector."""

    img = removeBackground(img, hueValue, threshold)

    img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY).astype(np.float32) / 255

    return img.ravel() 
Example #3
Source File: haralick.py    From eo-learn with MIT License 5 votes vote down vote up
def execute(self, eopatch):

        for feature_type, feature_name, new_feature_name in self.feature:
            eopatch[feature_type][new_feature_name] = self._calculate_haralick(eopatch[feature_type][feature_name])

        return eopatch 
Example #4
Source File: haralick.py    From eo-learn with MIT License 5 votes vote down vote up
def _calculate_haralick(self, data):
        result = np.empty(data.shape, dtype=np.float)
        # For each date and each band
        for time in range(data.shape[0]):
            for band in range(data.shape[3]):
                image = data[time, :, :, band]
                image_min, image_max = np.min(image), np.max(image)
                coef = (image_max - image_min) / self.levels
                digitized_image = np.digitize(image, np.array([image_min + k * coef for k in range(self.levels - 1)]))

                # Padding the image to handle borders
                pad = self.window_size // 2
                digitized_image = np.pad(digitized_image, ((pad, pad), (pad, pad)), 'edge')
                # Sliding window
                for i in range(0, image.shape[0], self.stride):
                    for j in range(0, image.shape[1], self.stride):
                        window = digitized_image[i: i + self.window_size, j: j + self.window_size]
                        glcm = skimage.feature.greycomatrix(window, [self.distance], [self.angle], levels=self.levels,
                                                            normed=True, symmetric=True)

                        if self.texture_feature in self.AVAILABLE_TEXTURES_SKIMAGE:
                            res = skimage.feature.greycoprops(glcm, self.texture_feature)[0][0]
                        else:
                            res = self._custom_texture(glcm[:, :, 0, 0])

                        result[time, i, j, band] = res
        return result 
Example #5
Source File: local_binary_pattern.py    From eo-learn with MIT License 5 votes vote down vote up
def execute(self, eopatch):
        """ Execute computation of local binary patterns on input eopatch

            :param eopatch: Input eopatch
            :type eopatch: eolearn.core.EOPatch
            :return: EOPatch instance with new key holding the LBP image.
            :rtype: eolearn.core.EOPatch
        """
        for feature_type, feature_name, new_feature_name in self.feature:
            eopatch[feature_type][new_feature_name] = self._compute_lbp(eopatch[feature_type][feature_name])

        return eopatch 
Example #6
Source File: local_binary_pattern.py    From eo-learn with MIT License 5 votes vote down vote up
def _compute_lbp(self, data):
        result = np.empty(data.shape, dtype=np.float)
        for time in range(data.shape[0]):
            for band in range(data.shape[-1]):
                image = data[time, :, :, band]
                result[time, :, :, band] = skimage.feature.local_binary_pattern(image, self.nb_points, self.radius,
                                                                                method='uniform')
        return result 
Example #7
Source File: local_binary_pattern.py    From eo-learn with MIT License 5 votes vote down vote up
def __init__(self, feature, nb_points=24, radius=3):

        self.feature = self._parse_features(feature, default_feature_type=FeatureType.DATA, new_names=True,
                                            rename_function='{}_LBP'.format)

        self.nb_points = nb_points
        self.radius = radius
        if nb_points < 1 or radius < 1:
            raise ValueError('Local binary pattern task parameters must be positives') 
Example #8
Source File: hog.py    From eo-learn with MIT License 5 votes vote down vote up
def execute(self, eopatch):
        """ Execute computation of HoG features on input eopatch

            :param eopatch: Input eopatch
            :type eopatch: eolearn.core.EOPatch
            :return: EOPatch instance with new keys holding the HoG features and HoG image for visualisation.
            :rtype: eolearn.core.EOPatch
        """
        for feature_type, feature_name, new_feature_name in self.feature:
            result = self._compute_hog(eopatch[feature_type][feature_name])
            eopatch[feature_type][new_feature_name] = result[0]
            if self.visualize:
                eopatch[feature_type][self.visualize_name] = result[1]

        return eopatch 
Example #9
Source File: hog.py    From eo-learn with MIT License 5 votes vote down vote up
def _compute_hog(self, data):
        results_im = np.empty((data.shape[0],
                               (int(data.shape[1] // self.pixels_per_cell[0]) - self.cells_per_block[0] + 1) *
                               self.cells_per_block[0],
                               (int(data.shape[2] // self.pixels_per_cell[1]) - self.cells_per_block[1] + 1) *
                               self.cells_per_block[1], self.n_orientations), dtype=np.float)
        if self.visualize:
            im_visu = np.empty(data.shape[0:3] + (1,))
        for time in range(data.shape[0]):
            multi_channel = data.shape[-1] != 1
            image = data[time] if multi_channel else data[time, :, :, 0]
            res, image = skimage.feature.hog(image, orientations=self.n_orientations,
                                             pixels_per_cell=self.pixels_per_cell, visualize=self.visualize,
                                             cells_per_block=self.cells_per_block, block_norm=self.block_norm,
                                             feature_vector=self.hog_feature_vector, multichannel=multi_channel)
            if self.visualize:
                im_visu[time, :, :, 0] = image
            for block_row in range(res.shape[0]):
                for block_col in range(res.shape[1]):
                    for cell_row in range(res.shape[2]):
                        for cell_col in range(res.shape[3]):
                            row = block_row * self.cells_per_block[0] + cell_row
                            col = block_col * self.cells_per_block[1] + cell_col
                            for angle in range(res.shape[4]):
                                results_im[time, row, col, angle] = res[block_row, block_col, cell_row, cell_col, angle]
        return results_im, im_visu 
Example #10
Source File: blob.py    From eo-learn with MIT License 5 votes vote down vote up
def __init__(self, feature, *, num_sigma=10, log_scale=False, min_sigma=1, max_sigma=30, threshold=0.1, overlap=0.5,
                 **kwargs):
        super().__init__(feature, skimage.feature.blob_doh, num_sigma=num_sigma, log_scale=log_scale,
                         min_sigma=min_sigma, max_sigma=max_sigma, threshold=threshold, overlap=overlap, **kwargs) 
Example #11
Source File: blob.py    From eo-learn with MIT License 5 votes vote down vote up
def __init__(self, feature, *, sigma_ratio=1.6, min_sigma=1, max_sigma=30, threshold=0.1, overlap=0.5, **kwargs):
        super().__init__(feature, skimage.feature.blob_dog, sigma_ratio=sigma_ratio, min_sigma=min_sigma,
                         max_sigma=max_sigma, threshold=threshold, overlap=overlap, **kwargs) 
Example #12
Source File: blob.py    From eo-learn with MIT License 5 votes vote down vote up
def execute(self, eopatch):
        """ Execute computation of blobs on input eopatch

        :param eopatch: Input eopatch
        :type eopatch: eolearn.core.EOPatch
        :return: EOPatch instance with new key holding the blob image.
        :rtype: eolearn.core.EOPatch
        """
        for feature_type, feature_name, new_feature_name in self.feature:
            eopatch[feature_type][new_feature_name] = self._compute_blob(
                eopatch[feature_type][feature_name].astype(np.float64)).astype(np.float32)

        return eopatch 
Example #13
Source File: blob.py    From eo-learn with MIT License 5 votes vote down vote up
def __init__(self, feature, blob_object, **blob_parameters):
        self.feature = self._parse_features(feature, default_feature_type=FeatureType.DATA, new_names=True,
                                            rename_function='{}_BLOB'.format)

        self.blob_object = blob_object
        self.blob_parameters = blob_parameters 
Example #14
Source File: cub_utils.py    From omgh with MIT License 5 votes vote down vote up
def _calculate(self):
        instance = np.zeros((self.dataset_size, self.HOG_DIM))
        for i, info in enumerate(self.dataset.get_all_images(cropped=True)):
            img = caffe.io.load_image(info['img_file'])
            img_g = skimage.color.rgb2gray(img)
            img_r = skimage.transform.resize(img_g, self.HOG_RESIZE)

            instance[i, :] = skimage.feature.hog(img_r, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(2, 2))
        return instance 
Example #15
Source File: core_annots.py    From ibeis with Apache License 2.0 5 votes vote down vote up
def compute_hog(depc, cid_list, config=None):
    """
    Doctest:
        >>> from ibeis.core_annots import *  # NOQA
        >>> ibs, depc, aid_list = testdata_core()
        >>> chip_config = {}
        >>> config = HOGConfig()
        >>> cid_list = depc.get_rowids('chips', aid_list, config=chip_config)
        >>> hoggen = compute_hog(depc, cid_list, config)
        >>> hog = list(hoggen)[0]
        >>> ut.quit_if_noshow()
        >>> import plottool_ibeis as pt
        >>> hog_image = make_hog_block_image(hog, config)
        >>> ut.show_if_requested()
    """
    import skimage.feature
    orientations = config['orientations']

    ut.assert_all_not_None(cid_list, 'cid_list')
    chip_fpath_list = depc.get_native(
        'chips', cid_list, 'img', read_extern=False)

    for chip_fpath in chip_fpath_list:
        chip = vt.imread(chip_fpath, grayscale=True) / 255.0
        hog = skimage.feature.hog(chip, feature_vector=False,
                                  orientations=orientations,
                                  pixels_per_cell=(16, 16), cells_per_block=(1, 1))
        yield (hog,) 
Example #16
Source File: seed.py    From ffn with Apache License 2.0 4 votes vote down vote up
def _init_coords(self):
    logging.info('peaks: starting')

    # Edge detection.
    edges = ndimage.generic_gradient_magnitude(
        self.canvas.image.astype(np.float32),
        ndimage.sobel)

    # Adaptive thresholding.
    sigma = 49.0 / 6.0
    thresh_image = np.zeros(edges.shape, dtype=np.float32)
    ndimage.gaussian_filter(edges, sigma, output=thresh_image, mode='reflect')
    filt_edges = edges > thresh_image

    del edges, thresh_image

    # This prevents a border effect where the large amount of masked area
    # screws up the distance transform below.
    if (self.canvas.restrictor is not None and
        self.canvas.restrictor.mask is not None):
      filt_edges[self.canvas.restrictor.mask] = 1

    logging.info('peaks: filtering done')
    dt = ndimage.distance_transform_edt(1 - filt_edges).astype(np.float32)
    logging.info('peaks: edt done')

    # Use a specifc seed for the noise so that results are reproducible
    # regardless of what happens before the policy is called.
    state = np.random.get_state()
    np.random.seed(42)
    idxs = skimage.feature.peak_local_max(
        dt + np.random.random(dt.shape) * 1e-4,
        indices=True, min_distance=3, threshold_abs=0, threshold_rel=0)
    np.random.set_state(state)

    # After skimage upgrade to 0.13.0 peak_local_max returns peaks in
    # descending order, versus ascending order previously.  Sort ascending to
    # maintain historic behavior.
    idxs = np.array(sorted((z, y, x) for z, y, x in idxs))

    logging.info('peaks: found %d local maxima', idxs.shape[0])
    self.coords = idxs 
Example #17
Source File: core_annots.py    From ibeis with Apache License 2.0 4 votes vote down vote up
def make_hog_block_image(hog, config=None):
    """
    References:
        https://github.com/scikit-image/scikit-image/blob/master/skimage/feature/_hog.py
    """
    from skimage import draw

    if config is None:
        config = HOGConfig()

    cx, cy = config['pixels_per_cell']

    normalised_blocks = hog
    (n_blocksy, n_blocksx, by, bx, orientations) = normalised_blocks.shape

    n_cellsx = (n_blocksx - 1) + bx
    n_cellsy = (n_blocksy - 1) + by

    # Undo the normalization step
    orientation_histogram = np.zeros((n_cellsy, n_cellsx, orientations))

    for x in range(n_blocksx):
        for y in range(n_blocksy):
            norm_block = normalised_blocks[y, x, :]
            # hack, this only works right for block sizes of 1
            orientation_histogram[y:y + by, x:x + bx, :] = norm_block

    sx = n_cellsx * cx
    sy = n_cellsy * cy

    radius = min(cx, cy) // 2 - 1
    orientations_arr = np.arange(orientations)
    dx_arr = radius * np.cos(orientations_arr / orientations * np.pi)
    dy_arr = radius * np.sin(orientations_arr / orientations * np.pi)
    hog_image = np.zeros((sy, sx), dtype=float)
    for x in range(n_cellsx):
        for y in range(n_cellsy):
            for o, dx, dy in zip(orientations_arr, dx_arr, dy_arr):
                centre = tuple([y * cy + cy // 2, x * cx + cx // 2])
                rr, cc = draw.line(int(centre[0] - dx),
                                   int(centre[1] + dy),
                                   int(centre[0] + dx),
                                   int(centre[1] - dy))
                hog_image[rr, cc] += orientation_histogram[y, x, o]
    return hog_image 
Example #18
Source File: seed.py    From ffn with Apache License 2.0 4 votes vote down vote up
def _init_coords(self):
    logging.info('2d peaks: starting')

    # Loop over 2d slices.
    for z in range(self.canvas.image.shape[0]):
      image_2d = (self.canvas.image[z, :, :]).astype(np.float32)

      # Edge detection.
      edges = ndimage.generic_gradient_magnitude(
          image_2d, ndimage.sobel)

      # Adaptive thresholding.
      sigma = 49.0 / 6.0
      thresh_image = np.zeros(edges.shape, dtype=np.float32)
      ndimage.gaussian_filter(edges, sigma, output=thresh_image, mode='reflect')
      filt_edges = edges > thresh_image

      del edges, thresh_image

      # Prevent border effect
      if (self.canvas.restrictor is not None and
          self.canvas.restrictor.mask is not None):
        filt_edges[self.canvas.restrictor.mask[z, :, :]] = 1

      # Distance transform
      dt = ndimage.distance_transform_edt(1 - filt_edges).astype(np.float32)

      # Use a specifc seed for the noise so that results are reproducible
      # regardless of what happens before the policy is called.
      state = np.random.get_state()
      np.random.seed(42)
      idxs = skimage.feature.peak_local_max(
          dt + np.random.random(dt.shape) * 1e-4,
          indices=True, min_distance=3, threshold_abs=0, threshold_rel=0)
      zs = np.full((idxs.shape[0], 1), z, dtype=np.int64)
      idxs = np.concatenate((zs, idxs), axis=1)
      np.random.set_state(state)

      # Update self.coords with indices found at this z index
      logging.info('2d peaks: found %d local maxima at z index %d',
                   idxs.shape[0], z)
      self.coords = np.concatenate((self.coords, idxs)) if z != 0 else idxs

    self.coords = np.array(
        sorted([(z, y, x) for z, y, x in self.coords], reverse=self.sort_reverse))

    logging.info('2d peaks: found %d total local maxima', self.coords.shape[0])