Ejemplo n.º 1
0
 def _median(self, x):
     xm = np.zeros_like(x)
     xm[0, ..., 0] = median(x[0, ..., 0])
     xm[0, ..., 1] = median(x[0, ..., 1])
     xm[0, ..., 2] = median(x[0, ..., 2])
     xm[0, ..., 3] = median(x[0, ..., 3])
     return xm
Ejemplo n.º 2
0
def _median(image, radius):
    if image.shape[0] == 1:
        shape = image.shape
        median_image = median(image[0], disk(radius))
        return median_image.reshape(shape)
    else:
        return median(image, ball(radius))
Ejemplo n.º 3
0
    def process_alignment_data(self, data, threshold, radius, microns):
        '''
		Applies a median filter twice to the data which is used for alignment

		Ensures than any noise in the structural data does not interfere with alignment

		:param array data: Raw data imported by the function :py:func:`brain.read_data`
		:param float threshold: Value between 0 and 1 to use as a cutoff for minimum pixel value
		:param int radius: Integer that determines the radius of the circle used for the median filter
		:param array microns: Array with three values representing the x,y,z micron dimensions of the voxel
		:returns: Dataframe containing data processed with the median filter and threshold
		'''

        #Iterate over each plane and apply median filter twice
        out = np.zeros(data.shape)
        for z in range(data.shape[0]):
            out[z] = median(median(data[z], disk(radius)), disk(radius))

        outdf = self.create_dataframe(out, microns)

        # Changed 7/5/18
        # Skimage filter changes datatype to 0-255 range from 0-1
        # Modification to threshold allows consistent use of threshold based on 0-1 range
        thresh = outdf[outdf.value < 255 * (1 - threshold)]
        return (thresh)
Ejemplo n.º 4
0
def test_median_warning(image, mode, cval, behavior, warning_type):

    if warning_type:
        with pytest.warns(warning_type):
            median(image, mode=mode, behavior=behavior)
    else:
        median(image, mode=mode, behavior=behavior)
Ejemplo n.º 5
0
def noiseReduction(image):
    image = filters.median(image, np.ones((3, 3)))
    noise = np.random.random(image.shape)
    image[noise > 0.99] = 255
    image[noise < 0.01] = 0
    image = median(image, disk(1))
    return image
Ejemplo n.º 6
0
    def readimg(self, path_s1, path_s2):
        s1 = io.imread(path_s1)
        s2 = io.imread(path_s2)[:, :, [1, 2, 3, 4, 5, 6, 7, 8, 11, 12]]
        if config.use_denoise:
            s1[:, :, 0] = filters.median(s1[:, :, 0], disk(5))
            s1[:, :, 1] = filters.median(s1[:, :, 1], disk(5))

        if config.input_band == 2:
            img = s1
        elif config.input_band == 10:
            img = s2
        elif config.input_band == 12:
            img = numpy.zeros(
                (s1.shape[0], s1.shape[1], s1.shape[2] + s2.shape[2]))
            img[:, :, :2] = s1
            img[:, :, 2:] = s2
        elif config.input_band == 13:
            img = numpy.zeros(
                (s1.shape[0], s1.shape[1], s1.shape[2] + s2.shape[2] + 1))
            img[:, :, :2] = s1
            img[:, :, 2:-1] = s2
            t = (s2[:, :, 6] - s2[:, :, 1]) / (s2[:, :, 6] + s2[:, :, 1])
            t[numpy.isnan(t)] = 0
            t[numpy.isinf(t)] = 0
            img[:, :, -1] = t

        return img.astype(numpy.float32)
Ejemplo n.º 7
0
def test_median_warning(image, mode, cval, behavior, n_warning, warning_type):

    with pytest.warns(None) as records:
        median(image, mode=mode, behavior=behavior)

    assert len(records) == n_warning
    for rec in records:
        assert isinstance(rec.message, warning_type)
Ejemplo n.º 8
0
def add_median_filter(x):
    """Adds median filter"""
    if len(x) > 20:
        for i in range(len(x)):
            x[i] = filters.median(x[i])
    else:
        x = filters.median(x)
    return x
Ejemplo n.º 9
0
 def apply_to_img2d(self, img, *args, **kwargs):
     if self.bg is not None:
         med = median(img, self.region, mask=(img != self.bg))
     else:
         med = median(img, self.region)
     res = med / med.max()  # Median is in [0, 255]
     if self.bg is not None:
         res[img == self.bg] = self.bg
     return res
Ejemplo n.º 10
0
def preprocess(img):
    struct_median = square(5)
    test = img[..., 0]
    first_image = median(test, struct_median)
    for i in range(1, img.shape[2]):
        test = img[..., i]
        test = median(test, struct_median)
        first_image = np.dstack((first_image, test))
    return first_image
Ejemplo n.º 11
0
def fill_spots(img, size=5):
    med = flt.median(img, selem=np.ones([size, 1]))
    med = flt.median(med, selem=np.ones([1, size]))
    fm = img.copy()
    fm[1:-2, 1:-2] = med[1:-2, 1:-2]
    fm = np.maximum(fm, img)

    res = rec.reconstruction(fm, img, method='erosion')

    return res
    def strange_method(self, _idx, img0, msk0, lbl0, x0, y0):
        input_shape = self.input_shape
        good4copy = self.all_good4copy[_idx]

        img = img0[y0:y0 + input_shape[0], x0:x0 + input_shape[1], :]
        msk = msk0[y0:y0 + input_shape[0], x0:x0 + input_shape[1], :]

        if len(good4copy) > 0 and random.random() > 0.75:
            num_copy = random.randrange(1, min(6, len(good4copy) + 1))
            lbl_max = lbl0.max()
            for i in range(num_copy):
                lbl_max += 1
                l_id = random.choice(good4copy)
                lbl_msk = self.all_labels[_idx] == l_id
                row, col = np.where(lbl_msk)
                y1, x1 = np.min(np.where(lbl_msk), axis=1)
                y2, x2 = np.max(np.where(lbl_msk), axis=1)
                lbl_msk = lbl_msk[y1:y2 + 1, x1:x2 + 1]
                lbl_img = img0[y1:y2 + 1, x1:x2 + 1, :]
                if random.random() > 0.5:
                    lbl_msk = lbl_msk[:, ::-1, ...]
                    lbl_img = lbl_img[:, ::-1, ...]
                rot = random.randrange(4)
                if rot > 0:
                    lbl_msk = np.rot90(lbl_msk, k=rot)
                    lbl_img = np.rot90(lbl_img, k=rot)
                x1 = random.randint(
                    max(0, x0 - lbl_msk.shape[1] // 2),
                    min(img0.shape[1] - lbl_msk.shape[1],
                        x0 + input_shape[1] - lbl_msk.shape[1] // 2))
                y1 = random.randint(
                    max(0, y0 - lbl_msk.shape[0] // 2),
                    min(img0.shape[0] - lbl_msk.shape[0],
                        y0 + input_shape[0] - lbl_msk.shape[0] // 2))
                tmp = erosion(lbl_msk, square(5))
                lbl_msk_dif = lbl_msk ^ tmp
                tmp = dilation(lbl_msk, square(5))
                lbl_msk_dif = lbl_msk_dif | (tmp ^ lbl_msk)
                lbl0[y1:y1 + lbl_msk.shape[0],
                     x1:x1 + lbl_msk.shape[1]][lbl_msk] = lbl_max
                img0[y1:y1 + lbl_msk.shape[0],
                     x1:x1 + lbl_msk.shape[1]][lbl_msk] = lbl_img[lbl_msk]
                full_diff_mask = np.zeros_like(img0[..., 0], dtype='bool')
                full_diff_mask[y1:y1 + lbl_msk.shape[0],
                               x1:x1 + lbl_msk.shape[1]] = lbl_msk_dif
                img0[..., 0][full_diff_mask] = median(
                    img0[..., 0], mask=full_diff_mask)[full_diff_mask]
                img0[..., 1][full_diff_mask] = median(
                    img0[..., 1], mask=full_diff_mask)[full_diff_mask]
                img0[..., 2][full_diff_mask] = median(
                    img0[..., 2], mask=full_diff_mask)[full_diff_mask]
            img = img0[y0:y0 + input_shape[0], x0:x0 + input_shape[1], :]
            lbl = lbl0[y0:y0 + input_shape[0], x0:x0 + input_shape[1]]
            msk = self.create_mask(lbl)
        return img, msk
Ejemplo n.º 13
0
def process_image(img, channel, filter_window, gamma, pixel_size,
                  rolling_ball_size):
    """
  Process a raw TIFF into something suitable for segmentation by MATLAB
  
  Arguments:
    img numpy.array The image as a 2- or 3-D array
    channel int The channel to extract
    filter_window int The radius of the median filter window (px)
    gamma float The gamma to set the image to
    pixel_size float The pixels / micron for this iamge
    rolling_ball_size int The radius of the disk used for filtering out the background (um). (Not actually rolling ball subtraction; I am faking it with a median filter)

  Return:
    numpy.array The processed, grayscale 8-bit image
  """
    # Get the signal channel
    if len(img.shape) == 3:
        # channel is 1-indexed, python is 0-indexed
        img = img[:, :, (channel - 1)]

    # Map signal to entire 16-bit range
    if img.dtype == np.uint16 or img.dtype == "uint16":
        img = exposure.rescale_intensity(img, in_range='image')

    # Convert to 8-bit grayscale
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        img = img_as_ubyte(img)

    filtered_img = np.copy(img)

    # Perform median filtering
    filtered_img = filters.median(filtered_img,
                                  selem=np.ones(
                                      (filter_window, filter_window)),
                                  behavior='rank')

    # Perform gamma correction
    filtered_img = exposure.adjust_gamma(filtered_img, gamma)

    # Rolling ball background subtraction
    # cv2_rolling_ball.subtract_background_rolling_ball is ridonculously slow
    # Gonna fake it
    bg = filters.median(filtered_img,
                        selem=morphology.disk(rolling_ball_size * pixel_size))
    filtered_img = filtered_img.astype(np.int16)
    filtered_img = filtered_img - bg
    filtered_img[filtered_img < 0] = 0
    filtered_img = filtered_img.astype(np.uint8)
    filtered_img = exposure.rescale_intensity(filtered_img)
    # img = subtract_background_rolling_ball(img, rolling_ball_size*pixel_size, light_background=False, use_paraboloid=False, do_presmooth=False)

    return (img, filtered_img)
Ejemplo n.º 14
0
def test_median_warning(image, mask, shift_x, shift_y, mode, cval, behavior,
                        n_warning, warning_type):
    if mask:
        mask = np.ones((image.shape), dtype=np.bool_)

    with pytest.warns(None) as records:
        median(image, mask=mask, shift_x=shift_x, shift_y=shift_y, mode=mode,
               behavior=behavior)

    assert len(records) == n_warning
    for rec in records:
        assert isinstance(rec.message, warning_type)
Ejemplo n.º 15
0
def robust_binarize(base_image,
                    _dilation=0,
                    heterogeity_size=10,
                    feature_size=50):
    """
    Robust binarization algorithm based off random walker clustering

    :param base_image:
    :param _dilation: if set to anything other than 0, would perform a morphological dilation using this parameter value as size
    :param heterogeity_size: size of the feature (px) that the method will try to eliminate by smoothing
    :param feature_size: size of the feature (px) that the method will try to segment out
    :return: binary_labels
    """
    if np.percentile(base_image, 99) < 0.20:
        if np.percentile(base_image, 99) > 0:
            mult = 0.20 / np.percentile(
                base_image, 99)  # poissonean background assumptions
        else:
            mult = 1000. / np.sum(base_image)
        base_image = base_image * mult
        base_image[base_image > 1] = 1

    clustering_markers = np.zeros(base_image.shape, dtype=np.uint8)

    selem = disk(heterogeity_size)
    smooth = gaussian_filter(base_image, heterogeity_size, mode='constant')
    smooth_median = median(smooth, selem)
    uniform_median = median(base_image, selem)

    selem2 = disk(feature_size)
    local_otsu = rank.otsu(smooth_median, selem2)
    uniform_median_otsu = rank.otsu(uniform_median, selem2)

    clustering_markers[smooth_median < local_otsu * 0.9] = 1
    clustering_markers[smooth_median > local_otsu * 1.1] = 2

    # dbg.random_walker_debug(smooth_median, clustering_markers)
    # dbg.robust_binarize_debug(base_image, smooth_median, smooth_median, local_otsu, clustering_markers,
    #                           0, uniform_median, uniform_median_otsu)

    binary_labels = random_walker(
        smooth_median, clustering_markers, beta=10, mode='bf') - 1

    if _dilation:
        selem = disk(_dilation)
        binary_labels = dilation(binary_labels, selem)

    # dbg.robust_binarize_debug(binary_labels, base_image)
    # dbg.voronoi_debug(binary_labels, local_maxi, dist, segmented_cells_labels)
    # dbg.Kristen_robust_binarize(binary_labels, base_image)
    return binary_labels
Ejemplo n.º 16
0
def hybridMedian(img):
    # applying the 3 * 3 hybrid filter
    # define filter shapes for different spatial directions
    img_grayscale = np.copy(img)
    img_grayscale = img_grayscale.astype(np.uint8)
    cross_filter = np.array([[1, 0, 1], [0, 1, 0], [1, 0, 1]])
    plus_filter = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])
    fil_cross = median(img_grayscale, cross_filter)
    fil_plus = median(img_grayscale, plus_filter)

    # calculate the median of the three images for each pixel
    combined_images = np.array([fil_cross, fil_plus, img_grayscale])
    filtered_img_hybrid = np.median(combined_images, axis=0)
    return filtered_img_hybrid
Ejemplo n.º 17
0
def test_median_warning(image, mask, shift_x, shift_y, mode, cval, behavior,
                        n_warning, warning_type):
    if mask:
        mask = np.ones((image.shape), dtype=np.bool_)

    with pytest.warns(None) as records:
        median(image,
               mask=mask,
               shift_x=shift_x,
               shift_y=shift_y,
               mode=mode,
               behavior=behavior)

    assert len(records) == n_warning
    for rec in records:
        assert isinstance(rec.message, warning_type)
Ejemplo n.º 18
0
def fill_gaps(image, closing_radius=0, min_hole_size=0, median_radius=0.6):
    """
    This function closes small gaps between and within objects and smooths edges. It is a
    'finishing' step before skeletonization, and improves the quality of the skeleton by removing
    gaps and minimizing bumps. It also enables removing close, parallel objects such as appear under
    the microscope as a single, long, clear object with sharp, parallel edges. These spurrious objects would
    otherwise pass earlier filters but are, in fact, spurrious. The function itself is a wrapper for
    `skimage.morphology.binary_closing`, `skimage.morphology.remove_small_holes`, and `skimage.filters.median`
    on a binary image.

    Parameters
    ----------
    image : ndarray
        Binary image of candidate objects
    closing_radius : ndarray
        Binary structure to perform binary closing. Defaults to 0 (skips).
    min_hole_size : int
        Holes with areas smaller than this (in pixels) are removed. Defaults to 0 (skips).
    median_radius : ndarray
        Binary structure to use for a median filter. Defaults at 0.6, giving square connectivity of 1
        (manhattan = 1). 0 to skip.

    Returns
    -------
    ndarray : Binary image of candidate objects.

    """
    closing_structure = _disk(closing_radius)
    median_structure = _disk(median_radius)

    out = morphology.binary_closing(image, closing_structure)
    out = morphology.remove_small_holes(out, min_size=min_hole_size)
    out = filters.median(out, selem=median_structure)

    return(out)
Ejemplo n.º 19
0
def thresh_series_mask(imgray):
    """
    Generates a mask to be used on original image to crop out the thumb region.
    
    Params: imgray: 2D numpy array.  B&W image in question
    
    Output: 2D numpy array.  Binary mask for B&W image in question
    """
    # first equilize the histogram to emphasize the area around the thumb
    imgray_eq = ske.equalize_hist(imgray)

    # median filter to perserve the edges while removing spatial frequency
    median_img = skfill.median(imgray_eq, selem=skmorph.disk(21))

    # some blocks sizes work better than others for different images,
    # we try a wide range of them to get the best qualities of each
    block_sizes = [21, 41, 51, 61, 81]
    masks = []
    for block_size in block_sizes:

        # some larger some smaller threshold blocks
        local_thresh = skfill.threshold_local(median_img, block_size)
        binary_local = median_img > local_thresh

        # detect regions
        labels = skmeasure.label(binary_local)
        hight_freq_img = high_freq_detection(imgray)

        # take 15 largest area regions detected in our thumb
        label_props = skmeasure.regionprops(labels)
        areas = [label_props[i]["area"] for i in range(len(label_props))]
        max_areas = heapq.nlargest(15, areas)
        max_indicies = [
            areas.index(max_areas[i]) + 1 for i in range(len(max_areas))
        ]

        # find the largest/highest frequency region
        max_i = 0
        max_count = 0
        for i in range(len(max_indicies)):
            label_vals = labels == max_indicies[i]

            # finding our region using our high_freq_detection() output
            current_count = (label_vals.astype(int) * hight_freq_img).sum()
            if current_count > max_count:
                max_count = current_count
                max_i = max_indicies[i]

        mask = labels == max_i
        masks.append(mask)

    mask = np.zeros(masks[0].shape).astype(bool)

    # combine all masks from each of our thresholds with bitwise or
    for m in masks:
        mask = mask | m

    # clean up the mask
    mask = skmorph.binary_closing(mask, selem=skmorph.disk(30))
    return skmorph.binary_erosion(mask, selem=skmorph.disk(10))
Ejemplo n.º 20
0
def get_regions(img):
    denoised=restoration.denoise_bilateral(img.astype('uint16'), 
#                                            sigma_range=0.01, 
                                           sigma_spatial=15,
                                          multichannel=False)
    smoothened = filters.median(denoised,np.ones((4,4)))
    markers = np.zeros(smoothened.shape, dtype=np.uint)
# otsu works only for only for multi-channel images     
#     markers[smoothened < filters.threshold_otsu(smoothened)] = 1
#     markers[smoothened > filters.threshold_otsu(smoothened)] = 2
    markers[smoothened < filters.median(smoothened)] = 1
    markers[smoothened > filters.median(smoothened)] = 2

    labels = random_walker(smoothened, markers, beta=10, mode='bf')
    regions= measure.label(labels)
    return regions, denoised, smoothened,markers
Ejemplo n.º 21
0
def compute_binary_mask_lasseck(spectrogram, threshold):
    # normalize to [0, 1)
    norm_spectrogram = normalize(spectrogram)

    # median clipping
    binary_image = median_clipping(norm_spectrogram, threshold)

    # closing binary image (dilation followed by erosion)
    binary_image = morphology.binary_closing(binary_image,
                                             selem=np.ones((4, 4)))

    # dialate binary image
    #binary_image = morphology.binary_dilation(binary_image, selem=np.ones((4, 4)))

    #apply erosion to binary image
    binary_image = morphology.binary_erosion(binary_image,
                                             selem=np.ones((4, 4)))

    # apply median filter
    binary_image = filters.median(binary_image, selem=np.ones((2, 2)))

    # remove small objects
    binary_image = morphology.remove_small_objects(binary_image,
                                                   min_size=32,
                                                   connectivity=1)

    mask = np.array([np.max(col) for col in binary_image.T])
    mask = smooth_mask(mask)

    return mask
Ejemplo n.º 22
0
def get_noise(patch):
    '''
    Input expects an RGBY patch.
    DWT is used to compute a noise mask on each color plane as: noise = input - DWT_denoise(input).
    That's the output.
    '''
    _, _, channels = patch.shape
    denoised_patch = np.zeros(patch.shape)

    for c in range(channels):
        denoised_patch[:, :, c] = median(patch[:, :, c].astype(np.uint8),
                                         selem=None)

    # I'm gonna normalise this in the gaussian case
    denoised_patch = (patch - denoised_patch)

    #denoised_patch -= np.min(denoised_patch, axis=(0, 1))   # min across planes
    #denoised_patch /= np.max(denoised_patch, axis=(0, 1))   # max across planes

    if np.min(denoised_patch) < 0 or np.max(denoised_patch) > 255:
        print(
            'denoised_patch outside 8-bit image range (min, max) = (%f, %f), Renormalising.'
            % (np.min(denoised_patch), np.max(denoised_patch)))

        denoised_patch -= np.min(denoised_patch.astype(np.float64),
                                 axis=(0, 1))  # min across planes
        denoised_patch /= np.max(denoised_patch,
                                 axis=(0, 1))  # max across planes
        denoised_patch = 255 * denoised_patch

    return denoised_patch.astype(int)
Ejemplo n.º 23
0
def preview_small_pores_detection_full(img2d_gray,
                                       percentile=2.5,
                                       min_large_contour_length=2000,
                                       window_size=200):

    img_without_large_contours = remove_large_contours(
        img2d_gray, min_large_contour_length=min_large_contour_length)
    global_thresh = np.percentile(img_without_large_contours.ravel(),
                                  percentile)

    #TODO: make image sampling more flexible
    count_of_center_points = np.min(img2d_gray.shape) // window_size

    frame_for_new_approach_img = np.zeros(
        [count_of_center_points * window_size] * 2, dtype=int)

    for x in np.arange(count_of_center_points) + 0.5:
        for y in np.arange(count_of_center_points) + 0.5:
            center_coords = np.ceil(np.asarray([x, y]) *
                                    window_size).astype(int)
            img_without_contours_frag = crop(img_without_large_contours,
                                             (window_size, window_size),
                                             center_coords)

            # new approach
            img_without_contours_frag = median(img_without_contours_frag)

            min_brightness = np.min(img_without_contours_frag)
            max_brightness = np.max(img_without_contours_frag)

            local_thresh = min_brightness + (max_brightness -
                                             min_brightness) * 0.5
            if local_thresh > global_thresh:
                local_thresh = global_thresh

            bin_cropped_fragment = img_without_contours_frag > local_thresh
            paste(frame_for_new_approach_img, bin_cropped_fragment,
                  center_coords)

    # fig, axes = plt.subplots(ncols=2, figsize=(14, 7), constrained_layout=True)
    # [ax.axis("off") for ax in axes]
    # [ax.imshow(img2d_gray, cmap=plt.cm.gray) for ax in axes]

    # mask_new = np.ma.masked_where(frame_for_new_approach_img, frame_for_new_approach_img)

    # axes[0].set_title("исходное изображение", fontsize=25)

    # axes[1].imshow(mask_new, cmap='hsv', interpolation='none')
    # axes[1].set_title("новый метод", fontsize=25)

    fig, ax = plt.subplots(figsize=(20, 20), constrained_layout=True)
    ax.axis("off")
    ax.imshow(img2d_gray, cmap=plt.cm.gray)

    mask_new = np.ma.masked_where(frame_for_new_approach_img,
                                  frame_for_new_approach_img)
    ax.imshow(mask_new, cmap='hsv', alpha=0.2, interpolation='none')
    ax.set_title("новый метод", fontsize=25)

    return fig
def noise_reduction_filters(cassava_leaves):
    gaussian_filter_leaves = filters.gaussian(cassava_leaves, sigma=2)
    med_filter_leaves = filters.median(cassava_leaves, np.ones((3, 3)))
    tv_filter_leaves = restoration.denoise_tv_chambolle(cassava_leaves,
                                                        weight=0.1)

    plt.figure(figsize=(16, 4))
    plt.subplot(141)
    plt.imshow(cassava_leaves, cmap='gray', interpolation='nearest')
    plt.axis('off')
    plt.title('Image')

    plt.subplot(142)
    plt.imshow(gaussian_filter_leaves, cmap='gray', interpolation='nearest')
    plt.axis('off')
    plt.title('Gaussian filter')

    plt.subplot(143)
    plt.imshow(med_filter_leaves, cmap='gray', interpolation='nearest')
    plt.axis('off')
    plt.title('Median filter')

    plt.subplot(144)
    plt.imshow(tv_filter_leaves, cmap='gray', interpolation='nearest')
    plt.axis('off')
    plt.title('TV filter')

    plt.show()
Ejemplo n.º 25
0
def resizeDataArrays(image_data_array,
                     mask_data_array,
                     output_height=512,
                     output_width=512):
    # Create temporary arrays
    resized_image_array = np.ndarray(shape=(image_data_array.shape[0], 512,
                                            512, 1),
                                     dtype='float32')
    resized_mask_array = np.ndarray(shape=(mask_data_array.shape[0], 512, 512,
                                           1),
                                    dtype='float32')

    for i in range(image_data_array.shape[0]):
        # Resize to 512 x 512
        resized_image_array[i, :, :, 0] = transform.resize(
            image_data_array[i, :, :, 0], (output_height, output_width),
            anti_aliasing=True)
        resized_mask_array[i, :, :,
                           0] = transform.resize(mask_data_array[i, :, :, 0],
                                                 (output_height, output_width),
                                                 anti_aliasing=True)

        # Median filter to clean up images
        resized_image_array[i, :, :,
                            0] = filters.median(resized_image_array[i, :, :,
                                                                    0])

    return resized_image_array, resized_mask_array
Ejemplo n.º 26
0
def preprocess(kernel_size=7):
    """
    Filter all images in the specified folder using median filter

    :param kernel_size: size of squared kernel used in median filter
    :return:
    """

    # path to original data
    PATH_ORIG = '/Users/mikhail/projects/edu/research/denoising/data/origin/noisy/'
    PATH_CLEAN = '/Users/mikhail/projects/edu/research/denoising/data/origin/clean/'

    images_names = os.listdir(PATH_ORIG)

    for i, image_name in enumerate(images_names):
        #img = cv2.imread(PATH_ORIG + image_name)
        # img_clean = cv2.medianBlur(img, 7)
        # cv2.imwrite(PATH_CLEAN + new_name, img_clean)

        img = skimage.io.imread(PATH_ORIG + image_name, as_gray=True)
        # filter image using median filter

        img_clean = median(img, selem=rectangle(kernel_size, kernel_size))

        # save image in another folder with different name
        new_name = 'F' + image_name[1:]
        skimage.io.imsave(PATH_CLEAN + new_name, img_clean)

        if (i % 200 == 0) and (i != 0):
            print(f'{i} images have been filtered')
Ejemplo n.º 27
0
def compare(left_im, right_im, w, h):
    x, y = left_im.shape
    from_around_px_x = -(w - 1) // 2
    to_around_px_x = ((w - 1) // 2) + 1
    from_around_px_y = -(h - 1) // 2
    to_around_px_y = ((h - 1) // 2) + 1
    res_img = np.zeros((x, y))
    for i in range(x):
        for j in range(y - 1):
            min_s = 1000000
            window_center_r = -1
            for r in range(j + 1, y):
                s = 0
                for k in range(from_around_px_x, to_around_px_x):
                    for l in range(from_around_px_y, to_around_px_y):
                        if 0 > i + k or i + k >= x or 0 > j + l or j + l >= y or r + k < 0 or r + l >= y:
                            continue
                        # S = ( L(r,q) - R(r,q) )^2
                        s += (float(left_im[i + k, j + l]) -
                              float(right_im[i + k, r + l]))**2

                if min_s > s:
                    min_s = s
                    window_center_r = r
            if window_center_r != -1:
                disparity = window_center_r - j
                depth = 1.0 - (1.0 / disparity)
                res_img[i, j] = depth
    # apply median filter
    final_img = filters.median(res_img, np.ones((9, 9)))
    return final_img
Ejemplo n.º 28
0
def compare(left_im, right_im, w, h):
    x, y = left_im.shape
    from_around_px_x = -(w - 1) // 2
    to_around_px_x = ((w - 1) // 2) + 1
    from_around_px_y = -(h - 1) // 2
    to_around_px_y = ((h - 1) // 2) + 1
    res_img = np.zeros((x, y))
    for i in range(x):
        for j in range(y - 1):
            min_s = 1000000
            window_center_r = -1
            for r in range(j + 1, y):
                s = 0
                for k in range(from_around_px_x, to_around_px_x):
                    for l in range(from_around_px_y, to_around_px_y):
                        if 0 > i + k or i + k >= x or 0 > j + l or j + l >= y or r + k < 0 or r + l >= y:
                            continue
                        # S = ( L(r,q) - R(r,q) )^2
                        s += (float(left_im[i + k, j + l]) - float(right_im[i + k, r + l])) ** 2

                if min_s > s:
                    min_s = s
                    window_center_r = r
            if window_center_r != -1:
                disparity = window_center_r - j
                depth = 1.0 - (1.0 / disparity)
                res_img[i, j] = depth
    # apply median filter
    final_img = filters.median(res_img, np.ones((9, 9)))
    return final_img
Ejemplo n.º 29
0
def arr_list2regions(arr_list, time_increment):
    pre_bleach = arr_list[0]
    denoised = restoration.denoise_bilateral(pre_bleach.astype('uint16'),
                                             sigma_range=0.01,
                                             sigma_spatial=15)
    smoothened = filters.median(denoised, np.ones((4, 4)))
    markers = np.zeros(smoothened.shape, dtype=np.uint)
    markers[smoothened < filters.threshold_otsu(smoothened)] = 1
    markers[smoothened > filters.threshold_otsu(smoothened)] = 2
    labels = random_walker(smoothened, markers, beta=10, mode='bf')
    regions = measure.label(labels)
    props = measure.regionprops(regions, arr_list[0])  #ref
    regions_areas = np.array([prop.area for prop in props])
    regions_lbls = np.array([prop.label for prop in props])
    regions_means = np.array([prop.mean_intensity for prop in props])
    regions_index_large = np.where((regions_areas < 10000)
                                   & (regions_areas > 200)
                                   & (regions_means > 2000))[0]
    regions_lbls_large = regions_lbls[regions_index_large]
    regions_large = np.zeros((regions.shape), dtype=bool)
    for i in regions_lbls_large:
        booli = (regions == i)
        regions_large = np.logical_or(regions_large, booli)
    kins_mean = pd.DataFrame(columns=regions_lbls_large,
                             index=range(len(arr_list)))
    for i in range(len(arr_list)):
        props = measure.regionprops(regions, arr_list[i])
        means = np.array([prop.mean_intensity for prop in props])
        kins_mean.loc[i, :] = means[regions_index_large]
        del props
    kins_mean = kins_mean.loc[:, ~(kins_mean < 3000).any(axis=0)]  #stitch
    kins_mean['time'] = np.array(range(
        len(arr_list))) * time_increment  #stitch
    return regions_large, kins_mean
Ejemplo n.º 30
0
def get_regions(img):
    denoised=restoration.denoise_bilateral(img.astype('uint16'), 
#                                            sigma_range=0.01, 
                                           sigma_spatial=15,
                                          multichannel=False)
    smoothened = filters.median(denoised,np.ones((4,4)))
    markers = np.zeros(smoothened.shape, dtype=np.uint)
# otsu works only for only for multi-channel images     
#     markers[smoothened < filters.threshold_otsu(smoothened)] = 1
#     markers[smoothened > filters.threshold_otsu(smoothened)] = 2
    markers[smoothened < filters.median(smoothened)] = 1
    markers[smoothened > filters.median(smoothened)] = 2

    labels = random_walker(smoothened, markers, beta=10, mode='bf')
    regions= measure.label(labels)
    return regions, denoised, smoothened,markers
Ejemplo n.º 31
0
def subtract_background_median(z, footprint=19, implementation='scipy'):
    """Remove background using a median filter.

    Parameters
    ----------
    footprint : int
        size of the window that is convoluted with the array to determine
        the median. Should be large enough that it is about 3x as big as the
        size of the peaks.
    implementation: str
        One of 'scipy', 'skimage'. Skimage is much faster, but it messes with
        the data format. The scipy implementation is safer, but slower.

    Returns
    -------
        Pattern with background subtracted as np.array
    """

    if implementation == 'scipy':
        bg_subtracted = z - ndi.median_filter(z, size=footprint)
    elif implementation == 'skimage':
        selem = morphology.square(footprint)
        # skimage only accepts input image as uint16
        bg_subtracted = z - filters.median(z.astype(np.uint16), selem).astype(
            z.dtype)

    return np.maximum(bg_subtracted, 0)
Ejemplo n.º 32
0
def removeBackground_(data, selem=cube(6)):
    img = data
    for i in range(img.shape[0]):
        img[i, :, :] = median(img[i, :, :])
    background = opening(img)
    sansBackground = img - background
    return sansBackground
Ejemplo n.º 33
0
def preprocess(img):

    #Applying otsu method for binarization
    threshold_val = threshold_otsu(img)
    binary_img = img > threshold_val
    med = median(binary_img, disk(2))
    return med
Ejemplo n.º 34
0
    def get_vert_lines(self, sz_filt):

        img = self.CleanedImage

        img -= np.min(img)
        img /= np.max(img)

        # Smooth image
        if sz_filt > 0:
            img = filters.median(img, morphology.disk(sz_filt))

        # Use vertical Sobel filter (since we know the lines are always the same orientation)
        sb = filters.sobel_v(img)

        # Normalize data between 0 and 1
        sb -= np.min(sb)
        sb /= np.max(sb)

        # Find Yen threshold
        thr = filters.threshold_yen(sb)

        thr_img = sb < thr
        if np.sum(thr_img) > np.sum(~thr_img):
            thr_img = ~thr_img

        thr_img = morphology.binary_dilation(thr_img, morphology.square(4))
        thr_img = morphology.binary_erosion(thr_img, morphology.square(4))

        return thr_img
Ejemplo n.º 35
0
def getBlobs(data, zDim, nChan, medFiltSize=7):

  sElem = np.ones((medFiltSize,medFiltSize), dtype=np.uint8)


  blobs = dict.fromkeys (  [(z,c) for z in range(zDim) for c in range(nChan)] )
  for z,c in blobs.keys():
    print z,c
    temp = filters.median( data[z,c,:,:] , sElem)
    blobs[(z,c)]  = blob_dog(temp, max_sigma=30, min_sigma=5, threshold=0.2, sigma_ratio=1.4)


  return blobs
def color_based_crop(test_image):

    median_ = np.median(test_image[:, :, 0], axis=(0, 1))

    test_image_med = median(test_image[:, :, 0], disk(10))
    test_image_treshold = (test_image_med[:, :] > (median_ + 10)) & (test_image[:, :, 0] < 180)
    eroded_thr = erosion(test_image_treshold, rectangle(5, 5))
    regions = list(regionprops(label(1 - eroded_thr)))
    if len(regions) != 0:
        biggest_region = max(regions, key=lambda x: x.area)
        minr, minc, maxr, maxc = biggest_region.bbox
        test_image = test_image[minr:maxr, minc:maxc, :]

    return transform.resize(color.rgb2gray(test_image), (100, 100))
Ejemplo n.º 37
0
def noise_removal(img, radius_1=1, radius_2=2, median_iterations=3):
    """
    Cleans a binary image by separating loosely connected objects, eliminating
    small objects, and finally smoothing edges of the remaining objects.
    The method is ``binary_opening``, ``binary_closing``, and two rounds of
    ``median_filter``.

    Parameters
    ----------
    img : array
    	a boolean ndarray
    radius_1 : int
    	Radius of disk structuring element for opening and closing.
        Default = 1, which gives 3x3 square connectivity (manhattan distance = 1).
        Can also supply own boolean array.
    structure_2 : int
    	Radius of disk structuring element for smoothing with a median filter.
    	Default = 2, which gives a is euclidean distance < 2*sqrt(2).
        Can also supply own boolean array.

    Returns
    -------
    A boolean ndarray of the same dimensions as ``img``.

    See Also
    --------
    In ``scipy.ndimage``, see ``skimage.morphology.binary_opening``,
    ``skimage.morphology.binary_closing``, and ``skimage.filters.median``

    """

    if len(np.array([radius_1]).shape) == 1:
        ELEMENT_1 = _disk(radius=radius_1)
    else:
        ELEMENT_1 = structure_1

    if len(np.array([radius_2]).shape) == 1:
        ELEMENT_2 = _disk(radius=radius_2)
    else:
        ELEMENT_2 = structure_2

    out = morphology.binary_opening(img, selem=ELEMENT_1)
    out = morphology.binary_closing(out, selem=ELEMENT_1)

    i = 0
    while i < median_iterations:
        out = filters.median(out, selem=ELEMENT_2)
        i += 1

    return(out)
Ejemplo n.º 38
0
def test():
    
    image_series = glob.glob('full_dewar/puck*_*in*_200.jpg')
    templates = [n.replace('200', '*') for n in image_series]
    template_empty = imread('template_empty.jpg')
    h, w = template_empty.shape
    
    print 'len(templates)', len(templates)
    fig, axes = plt.subplots(3, 4)
    a = axes.ravel()
    k = 0
    used = []
    while k<12:
    #for template in templates[:12]:
        template = random.choice(templates)
        if template in used:
            pass
        else:
            used.append(template)
            original_image = img_as_float(combine(template, length=200))
            ax = a[k]
            gray_image = color.rgb2gray(original_image)
            img_sharp = unsharp(gray_image)
            edges = canny(img_sharp, sigma=3.0, low_threshold=0.04, high_threshold=0.05)
            med_unsharp = median(img_sharp/img_sharp.max(), selem=disk(4))
            sharp_med_unsharp = unsharp(med_unsharp)
            edges_med = canny(sharp_med_unsharp, sigma=7)
            match = match_template(gaussian(edges_med, 4), template_empty)
            print 'match.max()'
            print match.max()
            peaks = peak_local_max(gaussian(match, 3), threshold_abs=0.3, indices=True)
            print 'template', template
            print '# peaks', len(peaks)
            print peaks
            ax.imshow(original_image) #, cmap='gray')
            #ax.imshow(gaussian(edges_med, 3), cmap='gnuplot')
            for peak in peaks:
                y, x = peak
                rect = plt.Rectangle((x, y), w, h, edgecolor='g', linewidth=2, facecolor='none')
                ax.add_patch(rect)
            #ax[edges] = (0, 1, 0)
            #image = img_as_int(original_image)
            #image[edges==True] = (0, 255, 0)
            ax.set_title(template.replace('full_dewar/', '').replace('_*.jpg', '') + ' detected %s' % (16-len(peaks),))
            k += 1
    plt.show()
Ejemplo n.º 39
0
def filtre2D(img):
    N = 3
    type_bruit = 'AG'

    selem = np.ones([N, N])
    if type_bruit == 'AG':
        bruit = util.random_noise(np.zeros(img.shape), mode='gaussian')
        img_bruitee = util.random_noise(img, mode='gaussian')
    else:
        bruit = util.random_noise(np.zeros(img.shape), mode='s&p')
        img_bruitee = util.random_noise(img, mode='s&p')

    img_bruit_median = filters.median(img_bruitee, selem)
    img_bruit_linear = ndimage.convolve(img_bruitee, selem)

    fig = plt.figure()

    if type_bruit == 'AG':
        bruit_linear = ndimage.convolve(bruit, selem)
        img_linear = ndimage.convolve(img, selem)
        fig.add_subplot(3, 3, 1)
        plt.imshow(img, cmap='gray')
        fig.add_subplot(3, 3, 2)
        plt.imshow(bruit, cmap='gray')
        fig.add_subplot(3, 3, 3)
        plt.imshow(img_bruitee, cmap='gray')
        fig.add_subplot(3, 3, 4)
        plt.imshow(img_linear, cmap='gray')
        fig.add_subplot(3, 3, 5)
        plt.imshow(bruit_linear, cmap='gray')
        fig.add_subplot(3, 3, 6)
        plt.imshow(img_bruit_linear, cmap='gray')
        fig.add_subplot(3, 3, 9)
        plt.imshow(img_bruit_median, cmap='gray')
    else:
        fig.add_subplot(2, 2, 1)
        plt.imshow(img, cmap='gray')
        fig.add_subplot(2, 2, 2)
        plt.imshow(img_bruitee, cmap='gray')
        fig.add_subplot(2, 2, 3)
        plt.imshow(img_bruit_linear, cmap='gray')
        fig.add_subplot(2, 2, 4)
        plt.imshow(img_bruit_median, cmap='gray')
    # fig.tight_layout()
    plt.show()
def image_pre_filter(img):
    """
    对输入的单通道图像进行预处理:
    包括中值滤波,锐化,降噪等操作,办证patch的效果
    :param img:
    :return:
    """

    result = ft.median(img / 255.0, disk(2))
    gs = ft.gaussian_filter(result, 1.)*255.0
    result += (result - gs) * 1.0
    # result[result>255] = 255
    # result[result<0] = 0

    # plt.subplot(121)
    # plt.imshow(img, interpolation="none", cmap=cm.gray)
    # plt.subplot(122)
    # plt.imshow(result, interpolation="none", cmap=cm.gray)
    # plt.show()
    return result
Ejemplo n.º 41
0
def test_median(img, behavior):
    median(img, behavior=behavior)
Ejemplo n.º 42
0
def test_median_error_ndim():
    img = np.random.randint(0, 10, size=(5, 5, 5), dtype=np.uint8)
    with pytest.raises(ValueError):
        median(img, behavior='rank')
Ejemplo n.º 43
0
def test_median_preserve_dtype(image, dtype):
    median_image = median(image.astype(dtype), behavior='ndimage')
    assert median_image.dtype == dtype