示例#1
0
def test_3d_fallback_white_tophat():
    image = np.zeros((7, 7, 7), dtype=bool)
    image[2, 2:4, 2:4] = 1
    image[3, 2:5, 2:5] = 1
    image[4, 3:5, 3:5] = 1
    new_image = grey.white_tophat(image)
    footprint = ndimage.generate_binary_structure(3,1)
    image_expected = ndimage.white_tophat(image,footprint=footprint)
    testing.assert_array_equal(new_image, image_expected)
示例#2
0
def test_3d_fallback_white_tophat():
    image = np.zeros((7, 7, 7), dtype=bool)
    image[2, 2:4, 2:4] = 1
    image[3, 2:5, 2:5] = 1
    image[4, 3:5, 3:5] = 1

    with expected_warnings(['operator.*deprecated|\A\Z']):
        new_image = grey.white_tophat(image)
    footprint = ndi.generate_binary_structure(3,1)
    with expected_warnings(['operator.*deprecated|\A\Z']):
        image_expected = ndi.white_tophat(image,footprint=footprint)
    testing.assert_array_equal(new_image, image_expected)
示例#3
0
def topHat(data, factor):
    '''
    data -- numpy array
    pntFactor determines how finely the filter is applied to data.
    A point factor of 0.01 is appropriate for the tophat filter of Bruker MALDI mass spectra.
    A smaller number is faster but a trade-off is imposed
    '''
    pntFactor = factor
    struct_pts = int(round(data.size*pntFactor))
    str_el = N.repeat([1], struct_pts)
    tFil = ndimage.white_tophat(data, None, str_el)

    return tFil
示例#4
0
def white_tophat(image, selem=None, out=None):
    """Return white top hat of an image.

    The white top hat of an image is defined as the image minus its
    morphological opening. This operation returns the bright spots of the image
    that are smaller than the structuring element.

    Parameters
    ----------
    image : ndarray
        Image array.
    selem : ndarray, optional
        The neighborhood expressed as an array of 1's and 0's.
        If None, use cross-shaped structuring element (connectivity=1).
    out : ndarray, optional
        The array to store the result of the morphology. If None
        is passed, a new array will be allocated.

    Returns
    -------
    out : array, same shape and type as `image`
        The result of the morphological white top hat.

    Examples
    --------
    >>> # Subtract grey background from bright peak
    >>> import numpy as np
    >>> from skimage.morphology import square
    >>> bright_on_grey = np.array([[2, 3, 3, 3, 2],
    ...                            [3, 4, 5, 4, 3],
    ...                            [3, 5, 9, 5, 3],
    ...                            [3, 4, 5, 4, 3],
    ...                            [2, 3, 3, 3, 2]], dtype=np.uint8)
    >>> white_tophat(bright_on_grey, square(3))
    array([[0, 0, 0, 0, 0],
           [0, 0, 1, 0, 0],
           [0, 1, 5, 1, 0],
           [0, 0, 1, 0, 0],
           [0, 0, 0, 0, 0]], dtype=uint8)

    """
    selem = np.array(selem)
    if out is image:
        opened = opening(image, selem)
        out -= opened
        return out
    elif out is None:
        out = np.empty_like(image)
    out = ndi.white_tophat(image, footprint=selem, output=out)
    return out
示例#5
0
文件: algo2.py 项目: edawine/fatools
def normalize_baseline( raw, medwinsize=399, savgol_size=11, savgol_order=5,
                tophat_factor = 0.01 ):
    """
    params.medwin_size
    params.savgol_order
    params.savgol_size
    """

    median_line = signal.medfilt(raw, [medwinsize])
    baseline = signal.savgol_filter( median_line, medwinsize, savgol_order)
    corrected_baseline = raw - baseline
    np.maximum(corrected_baseline, 0, out=corrected_baseline)
    savgol = signal.savgol_filter(corrected_baseline, savgol_size, savgol_order)
    smooth = ndimage.white_tophat(savgol, None,
                    np.repeat([1], int(round(raw.size * tophat_factor))))

    return NormalizedTrace( signal=smooth, baseline = baseline )
示例#6
0
文件: TopHat.py 项目: jlerman44/pyms
def tophat(ic, struct=None):

    """
    @summary: Top-hat baseline correction on Ion Chromatogram

    @param ic: The input ion chromatogram
    @type ic: pyms.GCMS.Class.IonChromatogram
    @param struct: Top-hat structural element as time string
    @type struct: StringType

    @return: Top-hat corrected ion chromatogram
    @rtype: pyms.IO.Class.IonChromatogram

    @author: Woon Wai Keen
    @author: Vladimir Likic
    """

    if not is_ionchromatogram(ic):
        error("'ic' not an IonChromatogram object")
    else:
        ia = copy.deepcopy(ic.get_intensity_array())

    if struct == None:
        struct_pts = int(round(ia.size * _STRUCT_ELM_FRAC))
    else:
        struct_pts = ic_window_points(ic, struct)

    #    print " -> Top-hat: structural element is %d point(s)" % ( struct_pts )

    str_el = numpy.repeat([1], struct_pts)
    ia = ndimage.white_tophat(ia, None, str_el)

    ic_bc = copy.deepcopy(ic)
    ic_bc.set_intensity_array(ia)

    return ic_bc
示例#7
0
def tophat(ic, struct=None):
    """
    Top-hat baseline correction on Ion Chromatogram

    :param ic: The input ion chromatogram
    :type ic: pyms.IonChromatogram.IonChromatogram
    :param struct: Top-hat structural element as time string
    :type struct: int or str or NoneType, optional

    :return: Top-hat corrected ion chromatogram
    :rtype: pyms.IonChromatogram.IonChromatogram

    :author: Woon Wai Keen
    :author: Vladimir Likic
    :author: Dominic Davis-Foster (type assertions)
    """

    if not isinstance(ic, IonChromatogram):
        raise TypeError("'ic' must be an IonChromatogram object")

    ia = copy.deepcopy(ic.intensity_array)

    if struct:
        struct_pts = ic_window_points(ic, struct)
    else:
        struct_pts = int(round(ia.size * _STRUCT_ELM_FRAC))

    #    print(" -> Top-hat: structural element is %d point(s)" % ( struct_pts ))

    str_el = numpy.repeat([1], struct_pts)
    ia = ndimage.white_tophat(ia, footprint=str_el)

    ic_bc = copy.deepcopy(ic)
    ic_bc.intensity_array = ia

    return ic_bc
示例#8
0
    # images, label = Parallel(n_jobs = num_cores)(delayed(create)(j) for j in range (5))))
    # images_info.append(images)
    # labels_info.app
    for j in range(len(image_list)):
        temp_name = image_list[j]
        info = [index, temp_name]
        info_im.append(info)

        img = Image.open(in_dir + str(i + 1) + '/' + temp_name).convert('L')
        img.save(out_dir + 'COCO_val2014_' + str(index + num)[1:] + '.jpg',
                 'jpeg')

        img = np.array(img)
        print img.shape, 'de: ', temp_name
        # pdb.set_trace()
        tophat = ndi.white_tophat(img, 5)
        otsu = threshold_otsu(tophat)
        mask = (img > otsu).astype(np.uint8)
        im2, contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE,
                                                    cv2.CHAIN_APPROX_SIMPLE)
        cnt = contours[0]
        M = cv2.moments(cnt)

        x, y, w, h = cv2.boundingRect(cnt)
        segmentation = []
        area = cv2.contourArea(contours[0])

        for contour in contours:
            contour = contour.flatten().tolist()
            segmentation.append(contour)
示例#9
0
def white_tophat(image, footprint=None, out=None):
    """Return white top hat of an image.

    The white top hat of an image is defined as the image minus its
    morphological opening. This operation returns the bright spots of the image
    that are smaller than the footprint.

    Parameters
    ----------
    image : ndarray
        Image array.
    footprint : ndarray, optional
        The neighborhood expressed as an array of 1's and 0's.
        If None, use cross-shaped footprint (connectivity=1). This can also
        be a sequence of 2-tuples where the first element of each 2-tuple is a
        footprint and the second element as an integer describing the number of
        times it should be iterated.
    out : ndarray, optional
        The array to store the result of the morphology. If None
        is passed, a new array will be allocated.

    Returns
    -------
    out : array, same shape and type as `image`
        The result of the morphological white top hat.

    See Also
    --------
    black_tophat

    References
    ----------
    .. [1] https://en.wikipedia.org/wiki/Top-hat_transform

    Examples
    --------
    >>> # Subtract gray background from bright peak
    >>> import numpy as np
    >>> from skimage.morphology import square
    >>> bright_on_gray = np.array([[2, 3, 3, 3, 2],
    ...                            [3, 4, 5, 4, 3],
    ...                            [3, 5, 9, 5, 3],
    ...                            [3, 4, 5, 4, 3],
    ...                            [2, 3, 3, 3, 2]], dtype=np.uint8)
    >>> white_tophat(bright_on_gray, square(3))
    array([[0, 0, 0, 0, 0],
           [0, 0, 1, 0, 0],
           [0, 1, 5, 1, 0],
           [0, 0, 1, 0, 0],
           [0, 0, 0, 0, 0]], dtype=uint8)

    """
    if out is image:
        opened = opening(image, footprint)
        if np.issubdtype(opened.dtype, bool):
            np.logical_xor(out, opened, out=out)
        else:
            out -= opened
        return out
    elif out is None:
        out = np.empty_like(image)
    # promote bool to a type that allows arithmetic operations
    if isinstance(image, np.ndarray) and image.dtype == bool:
        image_ = image.view(dtype=np.uint8)
    else:
        image_ = image
    if isinstance(out, np.ndarray) and out.dtype == bool:
        out_ = out.view(dtype=np.uint8)
    else:
        out_ = out
    if _footprint_is_sequence(footprint):
        return _white_tophat_seqence(image_, footprint, out_)
    footprint = np.array(footprint)
    out_ = ndi.white_tophat(image_, footprint=footprint, output=out_)
    return out
output = vc.white_tophat(input_var,
                         make_float32=False,
                         size=None,
                         footprint=None,
                         structure=structure,
                         output=None,
                         mode='reflect',
                         cval=0.0,
                         origin=0)
print("vc white_tophat: ", (t.time() - start_time), " sec")
print("\nwhite_tophat VoxelProcessing Default")
start_time = t.time()
d = ndimage.white_tophat(input_var,
                         size=None,
                         footprint=None,
                         structure=structure,
                         output=None,
                         mode='reflect',
                         cval=0.0,
                         origin=0)
print("scipy white_tophat: ", (t.time() - start_time), " sec")
print("\nresult: ", (d == output).all())

#16.multiply..............
print("\nmultiply VoxelProcessing")
start_time = t.time()
output = vc.multiply(input_var,
                     make_float32=False,
                     no_of_blocks=7,
                     fakeghost=2,
                     scalar=10)
print("vc multiply: ", (t.time() - start_time), " sec")
示例#11
0
文件: traceutils.py 项目: trmznt/msaf
def correct_baseline( signal ):
    """ use tophat morphological transform to correct for baseline """

    return ndimage.white_tophat(signal, None,
                np.repeat([1], int(round(signal.size * _TOPHAT_FACTOR)))
            )
示例#12
0
def y_shift_by_mask_sliding(top_bottom_image, bottom_top_image):
    scores = top_bottom_to_slide_scores(top_bottom_image, bottom_top_image)
    if np.max(scores) < 0:
        return 0
    scores = ndimage.white_tophat(scores, structure=np.ones((6)))
    return np.argmax(scores)
    def __operationTask(self, input):
        D = self.__operationArgumentDic
        #self.M.add_mem()#.....................................................................................................

        if self.__operation == "binary_closing":
            return ndimage.binary_closing(input,
                                          structure=D["structure"],
                                          iterations=D["iterations"],
                                          output=D["output"],
                                          origin=D["origin"],
                                          mask=D["mask"],
                                          border_value=D["border_value"],
                                          brute_force=D["brute_force"])
        elif self.__operation == "binary_dilation":
            return ndimage.binary_dilation(input,
                                           structure=D["structure"],
                                           iterations=D["iterations"],
                                           output=D["output"],
                                           origin=D["origin"],
                                           mask=D["mask"],
                                           border_value=D["border_value"],
                                           brute_force=D["brute_force"])
        elif self.__operation == "binary_erosion":
            return ndimage.binary_erosion(input,
                                          structure=D["structure"],
                                          iterations=D["iterations"],
                                          output=D["output"],
                                          origin=D["origin"],
                                          mask=D["mask"],
                                          border_value=D["border_value"],
                                          brute_force=D["brute_force"])
        elif self.__operation == "binary_fill_holes":
            return ndimage.binary_fill_holes(input,
                                             structure=D["structure"],
                                             output=D["output"],
                                             origin=D["origin"])
        elif self.__operation == "binary_hit_or_miss":
            return ndimage.binary_hit_or_miss(input,
                                              structure1=D["structure1"],
                                              structure2=D["structure2"],
                                              output=D["output"],
                                              origin1=D["origin1"],
                                              origin2=D["origin2"])
        elif self.__operation == "binary_opening":
            return ndimage.binary_opening(input,
                                          structure=D["structure"],
                                          iterations=D["iterations"],
                                          output=D["output"],
                                          origin=D["origin"],
                                          mask=D["mask"],
                                          border_value=D["border_value"],
                                          brute_force=D["brute_force"])
        elif self.__operation == "binary_propagation":
            return ndimage.binary_propagation(input,
                                              structure=D["structure"],
                                              output=D["output"],
                                              origin=D["origin"],
                                              mask=D["mask"],
                                              border_value=D["border_value"])
        elif self.__operation == "black_tophat":
            return ndimage.black_tophat(input,
                                        structure=D["structure"],
                                        size=D["size"],
                                        footprint=D["footprint"],
                                        output=D["output"],
                                        origin=D["origin"],
                                        mode=D["mode"],
                                        cval=D["cval"])
        elif self.__operation == "grey_dilation":
            return ndimage.grey_dilation(input,
                                         structure=D["structure"],
                                         size=D["size"],
                                         footprint=D["footprint"],
                                         output=D["output"],
                                         mode=D["mode"],
                                         cval=D["cval"],
                                         origin=D["origin"])
        elif self.__operation == "grey_closing":
            return ndimage.grey_closing(input,
                                        structure=D["structure"],
                                        size=D["size"],
                                        footprint=D["footprint"],
                                        output=D["output"],
                                        origin=D["origin"],
                                        mode=D["mode"],
                                        cval=D["cval"])
        elif self.__operation == "grey_erosion":
            return ndimage.grey_erosion(input,
                                        structure=D["structure"],
                                        size=D["size"],
                                        footprint=D["footprint"],
                                        output=D["output"],
                                        origin=D["origin"],
                                        mode=D["mode"],
                                        cval=D["cval"])
        elif self.__operation == "grey_opening":
            return ndimage.grey_opening(input,
                                        structure=D["structure"],
                                        size=D["size"],
                                        footprint=D["footprint"],
                                        output=D["output"],
                                        origin=D["origin"],
                                        mode=D["mode"],
                                        cval=D["cval"])
        elif self.__operation == "morphological_gradient":
            return ndimage.morphological_gradient(input,
                                                  structure=D["structure"],
                                                  size=D["size"],
                                                  footprint=D["footprint"],
                                                  output=D["output"],
                                                  origin=D["origin"],
                                                  mode=D["mode"],
                                                  cval=D["cval"])
        elif self.__operation == "morphological_laplace":
            return ndimage.morphological_laplace(input,
                                                 structure=D["structure"],
                                                 size=D["size"],
                                                 footprint=D["footprint"],
                                                 output=D["output"],
                                                 origin=D["origin"],
                                                 mode=D["mode"],
                                                 cval=D["cval"])
        elif self.__operation == "white_tophat":
            return ndimage.white_tophat(input,
                                        structure=D["structure"],
                                        size=D["size"],
                                        footprint=D["footprint"],
                                        output=D["output"],
                                        origin=D["origin"],
                                        mode=D["mode"],
                                        cval=D["cval"])
        elif self.__operation == "intMultiply":
            return input * D["scalar"]

        else:
            return input
示例#14
0
def correct_baseline( signal ):
    """ use tophat morphological transform to correct for baseline """

    return ndimage.white_tophat(signal, None,
                np.repeat([1], int(round(signal.size * _TOPHAT_FACTOR)))
            )
    print("Erosion CPU: " + str(end - start))

    print("Difference: " + str(cp.sum(cp.asnumpy(out) != out_cpu)))
    plt.imshow(cp.asnumpy(out), cmap='gray', vmin=0, vmax=255)
    plt.show()
    plt.imshow(out_cpu, cmap='gray', vmin=0, vmax=255)
    plt.show()

    start = timer()
    out = grey_dilation_cuda(image, p)
    end = timer()
    print("Dilation GPU: " + str(end - start))

    start = timer()
    out_cpu = grey_dilation(cp.asnumpy(image), [p, p])
    end = timer()
    print("Dilation CPU: " + str(end - start))

    print("Difference: " + str(cp.sum(cp.asnumpy(out) != out_cpu)))

    start = timer()
    [NWTH, NBTH] = grey_top_hat_cuda(image, p)
    end = timer()
    print("Top-hat GPU: " + str(end - start))

    start = timer()
    NWTH_cpu = white_tophat(cp.asnumpy(image), structure=np.zeros([p, p]))
    NBTH_cpu = black_tophat(cp.asnumpy(image), structure=np.zeros([p, p]))
    end = timer()
    print("Top-hat CPU: " + str(end - start))
    print("Difference: " + str(cp.sum(cp.asnumpy(out) != out_cpu)))
示例#16
0
 def tophat(self, x, window):
     str_el = np.repeat([1], window)
     return ndimage.white_tophat(x, None, str_el)
示例#17
0
def main():
    structure = np.ones((3, 3, 3))
    #.............test1. dense.......
    filename = 'gyroidUniform.npy'
    input = np.load(filename, mmap_mode="r")

    print(
        "..............................dense.............................................."
    )

    #0.Nothing..............
    print("\n nothing testing...")
    output = vc.nothing(input, blockSize=50, fakeGhost=4, makeFloat32=False)
    print("\nresult: ", (input == output).all())
    print(output.dtype, input.dtype)
    #1.grey_dilation..............
    print("\ngrey_dilation VoxelProcessind")
    output = vc.grey_dilation(input, structure=structure, makeFloat32=False)
    print("\ngrey_dilation Default")
    d = ndimage.grey_dilation(input, structure=structure)
    print("\nresult: ", (d == output).all())
    print(output.dtype, input.dtype)
    #2.grey_erosion..............
    print("\ngrey_erosion VoxelProcessind")
    output = vc.grey_erosion(input,
                             makeFloat32=False,
                             size=None,
                             footprint=None,
                             structure=structure,
                             output=None,
                             mode='reflect',
                             cval=0.0,
                             origin=0)
    print("\ngrey_erosion Default")
    d = ndimage.grey_erosion(input,
                             size=None,
                             footprint=None,
                             structure=structure,
                             output=None,
                             mode='reflect',
                             cval=0.0,
                             origin=0)
    print("\nresult: ", (d == output).all())
    #3.grey_closing..............
    print("\ngrey_closing VoxelProcessind")
    output = vc.grey_closing(input,
                             makeFloat32=False,
                             size=None,
                             footprint=None,
                             structure=structure,
                             output=None,
                             mode='reflect',
                             cval=0.0,
                             origin=0)
    print("\ngrey_closing Default")
    d = ndimage.grey_closing(input,
                             size=None,
                             footprint=None,
                             structure=structure,
                             output=None,
                             mode='reflect',
                             cval=0.0,
                             origin=0)
    print("\nresult: ", (d == output).all())
    print(output.dtype, input.dtype)
    #4.grey_opening..............
    print("\ngrey_opening VoxelProcessind")
    output = vc.grey_opening(input,
                             makeFloat32=False,
                             size=None,
                             footprint=None,
                             structure=structure,
                             output=None,
                             mode='reflect',
                             cval=0.0,
                             origin=0)
    print("\ngrey_opening Default")
    d = ndimage.grey_opening(input,
                             size=None,
                             footprint=None,
                             structure=structure,
                             output=None,
                             mode='reflect',
                             cval=0.0,
                             origin=0)
    print("\nresult: ", (d == output).all())
    #5.binary_closing..............
    print("\nbinary_closing VoxelProcessind")
    output = vc.binary_closing(input,
                               makeFloat32=False,
                               structure=None,
                               iterations=1,
                               output=None,
                               origin=0,
                               mask=None,
                               border_value=0,
                               brute_force=False)
    print("\nbinary_closing Default")
    d = ndimage.binary_closing(input,
                               structure=None,
                               iterations=1,
                               output=None,
                               origin=0,
                               mask=None,
                               border_value=0,
                               brute_force=False)
    print("\nresult: ", (d == output).all())
    print(output[151][151][151])
    #6.binary_opening..............
    print("\nbinary_opening VoxelProcessind")
    output = vc.binary_opening(input,
                               structure=None,
                               iterations=1,
                               output=None,
                               origin=0,
                               mask=None,
                               border_value=0,
                               brute_force=False)
    print("\nbinary_opening Default")
    d = ndimage.binary_opening(input,
                               structure=None,
                               iterations=1,
                               output=None,
                               origin=0,
                               mask=None,
                               border_value=0,
                               brute_force=False)
    print("\nresult: ", (d == output).all())
    #7.binary_dilation..............
    print("\nbinary_dilation VoxelProcessind")
    output = vc.binary_dilation(input,
                                makeFloat32=False,
                                structure=structure,
                                iterations=1,
                                mask=None,
                                output=None,
                                border_value=0,
                                origin=0,
                                brute_force=False)
    print("\nbinary_dilation Default")
    d = ndimage.binary_dilation(input,
                                structure=structure,
                                iterations=1,
                                mask=None,
                                output=None,
                                border_value=0,
                                origin=0,
                                brute_force=False)
    print("\nresult: ", (d == output).all())
    #8.binary_erosion..............
    print("\nbinary_erosion VoxelProcessind")
    output = vc.binary_erosion(input,
                               makeFloat32=False,
                               structure=None,
                               iterations=1,
                               mask=None,
                               output=None,
                               border_value=0,
                               origin=0,
                               brute_force=False)
    print("\nbinary_erosion Default")
    d = ndimage.binary_erosion(input,
                               structure=None,
                               iterations=1,
                               mask=None,
                               output=None,
                               border_value=0,
                               origin=0,
                               brute_force=False)
    print("\nresult: ", (d == output).all())
    #9.binary_fill_holes..............
    print("\nbinary_fill_holes VoxelProcessind")
    output = vc.binary_fill_holes(input,
                                  makeFloat32=False,
                                  structure=None,
                                  output=None,
                                  origin=0)
    print("\nbinary_fill_holes Default")
    d = ndimage.binary_fill_holes(input, structure=None, output=None, origin=0)
    print("\nresult: ", (d == output).all())
    #10.binary_hit_or_miss..............
    print("\nbinary_hit_or_miss VoxelProcessind")
    output = vc.binary_hit_or_miss(input,
                                   makeFloat32=False,
                                   structure1=None,
                                   structure2=None,
                                   output=None,
                                   origin1=0,
                                   origin2=None)
    print("\nbinary_hit_or_miss Default")
    d = ndimage.binary_hit_or_miss(input,
                                   structure1=None,
                                   structure2=None,
                                   output=None,
                                   origin1=0,
                                   origin2=None)
    print("\nresult: ", (d == output).all())
    #11.binary_propagation..............
    print("\nbinary_propagation VoxelProcessind")
    output = vc.binary_propagation(input,
                                   makeFloat32=False,
                                   structure=None,
                                   mask=None,
                                   output=None,
                                   border_value=0,
                                   origin=0)
    print("\nbinary_propagation Default")
    d = ndimage.binary_propagation(input,
                                   structure=None,
                                   mask=None,
                                   output=None,
                                   border_value=0,
                                   origin=0)
    print("\nresult: ", (d == output).all())
    #12.black_tophat..............
    print("\nblack_tophat VoxelProcessind")
    output = vc.black_tophat(input,
                             makeFloat32=False,
                             size=None,
                             footprint=None,
                             structure=structure,
                             output=None,
                             mode='reflect',
                             cval=0.0,
                             origin=0)
    print("\nblack_tophat Default")
    d = ndimage.black_tophat(input,
                             size=None,
                             footprint=None,
                             structure=structure,
                             output=None,
                             mode='reflect',
                             cval=0.0,
                             origin=0)
    print("\nresult: ", (d == output).all())
    #13.morphological_gradient..............
    print("\nmorphological_gradient VoxelProcessind")
    output = vc.morphological_gradient(input,
                                       makeFloat32=False,
                                       size=None,
                                       footprint=None,
                                       structure=structure,
                                       output=None,
                                       mode='reflect',
                                       cval=0.0,
                                       origin=0)
    print("\nmorphological_gradient Default")
    d = ndimage.morphological_gradient(input,
                                       size=None,
                                       footprint=None,
                                       structure=structure,
                                       output=None,
                                       mode='reflect',
                                       cval=0.0,
                                       origin=0)
    print("\nresult: ", (d == output).all())
    #14.morphological_laplace..............
    print("\nmorphological_laplace VoxelProcessind")
    output = vc.morphological_laplace(input,
                                      makeFloat32=False,
                                      size=None,
                                      footprint=None,
                                      structure=structure,
                                      output=None,
                                      mode='reflect',
                                      cval=0.0,
                                      origin=0)
    print("\nmorphological_laplace Default")
    d = ndimage.morphological_laplace(input,
                                      size=None,
                                      footprint=None,
                                      structure=structure,
                                      output=None,
                                      mode='reflect',
                                      cval=0.0,
                                      origin=0)
    print("\nresult: ", (d == output).all())
    #15.white_tophat..............
    print("\nwhite_tophat VoxelProcessind")
    output = vc.white_tophat(input,
                             makeFloat32=False,
                             size=None,
                             footprint=None,
                             structure=structure,
                             output=None,
                             mode='reflect',
                             cval=0.0,
                             origin=0)
    print("\nwhite_tophat VoxelProcessind Default")
    d = ndimage.white_tophat(input,
                             size=None,
                             footprint=None,
                             structure=structure,
                             output=None,
                             mode='reflect',
                             cval=0.0,
                             origin=0)
    print("\nresult: ", (d == output).all())
    #16.intMultiply..............
    print("\nintMultiply VoxelProcessind")
    output = vc.intMultiply(input,
                            makeFloat32=False,
                            blockSize=50,
                            fakeGhost=1,
                            scalar=10)
    print("\nintMultiply Default")
    d = input * 10
    print("\nresult: ", (d == output).all())

    print(
        "..............................Sparse.............................................."
    )

    input = random(400, 80000, density=0.3, dtype="float64")
    input = input.todense()
    input = np.array(input)
    input = np.reshape(input, (400, 200, 400))

    #0.Nothing..............
    print("\n nothing testing...")
    output = vc.nothing(input, makeFloat32=False)
    print("\nresult: ", (input == output).all())
    print(output.dtype, input.dtype)
    #1.grey_dilation..............
    print("\ngrey_dilation VoxelProcessind")
    output = vc.grey_dilation(input, structure=structure, makeFloat32=False)
    print("\ngrey_dilation Default")
    d = ndimage.grey_dilation(input, structure=structure)
    print("\nresult: ", (d == output).all())
    print(output.dtype, input.dtype)
    #2.grey_erosion..............
    print("\ngrey_erosion VoxelProcessind")
    output = vc.grey_erosion(input, makeFloat32=False, structure=structure)
    print("\ngrey_erosion Default")
    d = ndimage.grey_erosion(input, structure=structure)
    print("\nresult: ", (d == output).all())
    #3.grey_closing..............
    print("\ngrey_closing VoxelProcessind")
    output = vc.grey_closing(input, makeFloat32=False, structure=structure)
    print("\ngrey_closing Default")
    d = ndimage.grey_closing(input, structure=structure)
    print("\nresult: ", (d == output).all())
    print(output.dtype, input.dtype)
    #4.grey_opening..............
    print("\ngrey_opening VoxelProcessind")
    output = vc.grey_opening(input, makeFloat32=False, structure=structure)
    print("\ngrey_opening Default")
    d = ndimage.grey_opening(input, structure=structure)
    print("\nresult: ", (d == output).all())
    #5.binary_closing..............
    print("\nbinary_closing VoxelProcessind")
    output = vc.binary_closing(input, makeFloat32=False)
    print("\nbinary_closing Default")
    d = ndimage.binary_closing(input)
    print("\nresult: ", (d == output).all())
    #6.binary_opening..............
    print("\nbinary_opening VoxelProcessind")
    output = vc.binary_opening(input, makeFloat32=False)
    print("\nbinary_opening Default")
    d = ndimage.binary_opening(input)
    print("\nresult: ", (d == output).all())
    #7.binary_dilation..............
    print("\nbinary_dilation VoxelProcessind")
    output = vc.binary_dilation(input, makeFloat32=False, structure=structure)
    print("\nbinary_dilation Default")
    d = ndimage.binary_dilation(input, structure=structure)
    print("\nresult: ", (d == output).all())
    #8.binary_erosion..............
    print("\nbinary_erosion VoxelProcessind")
    output = vc.binary_erosion(input, makeFloat32=False)
    print("\nbinary_erosion Default")
    d = ndimage.binary_erosion(input)
    print("\nresult: ", (d == output).all())
    #9.binary_fill_holes..............
    print("\nbinary_fill_holes VoxelProcessind")
    output = vc.binary_fill_holes(input, makeFloat32=False)
    print("\nbinary_fill_holes Default")
    d = ndimage.binary_fill_holes(input)
    print("\nresult: ", (d == output).all())
    #10.binary_hit_or_miss..............
    print("\nbinary_hit_or_miss VoxelProcessind")
    output = vc.binary_hit_or_miss(input, makeFloat32=False)
    print("\nbinary_hit_or_miss Default")
    d = ndimage.binary_hit_or_miss(input)
    print("\nresult: ", (d == output).all())
    #11.binary_propagation..............
    print("\nbinary_propagation VoxelProcessind")
    output = vc.binary_propagation(input, makeFloat32=False)
    print("\nbinary_propagation Default")
    d = ndimage.binary_propagation(input)
    print("\nresult: ", (d == output).all())
    #12.black_tophat..............
    print("\nblack_tophat VoxelProcessind")
    output = vc.black_tophat(input, makeFloat32=False, structure=structure)
    print("\nblack_tophat Default")
    d = ndimage.black_tophat(input, structure=structure)
    print("\nresult: ", (d == output).all())
    #13.morphological_gradient..............
    print("\nmorphological_gradient VoxelProcessind")
    output = vc.morphological_gradient(
        input,
        structure=structure,
        makeFloat32=False,
    )
    print("\nmorphological_gradient Default")
    d = ndimage.morphological_gradient(input, structure=structure)
    print("\nresult: ", (d == output).all())
    #14.morphological_laplace..............
    print("\nmorphological_laplace VoxelProcessind")
    output = vc.morphological_laplace(input,
                                      structure=structure,
                                      makeFloat32=False)
    print("\nmorphological_laplace Default")
    d = ndimage.morphological_laplace(input, structure=structure)
    print("\nresult: ", (d == output).all())
    #15.white_tophat..............
    print("\nwhite_tophat VoxelProcessind")
    output = vc.white_tophat(input, makeFloat32=False, structure=structure)
    print("\nwhite_tophat VoxelProcessind Default")
    d = ndimage.white_tophat(input, structure=structure)
    print("\nresult: ", (d == output).all())
    #16.intMultiply..............
    print("\nintMultiply VoxelProcessind")
    output = vc.intMultiply(input, makeFloat32=False, scalar=10)
    print("\nintMultiply Default")
    d = input * 10
    print("\nresult: ", (d == output).all())
示例#18
0
def correct_baseline(signal, tophat_factor=.005):
    """ use tophat morphological transform to correct for baseline """
    footprint = np.repeat([1], int(round(signal.size * tophat_factor)))
    return ndimage.white_tophat(signal, None, footprint)
def image_process(I,smudgesize):
    #p1, p2 = np.percentile(img, (perc_min, perc_max))
    result1 = white_tophat(I,smudgesize)
    #result1 = exposure.rescale_intensity(img, in_range=(p1, p2))
    return result1
示例#20
0
def white_tophat(image, selem=None, out=None):
    """Return white top hat of an image.

    The white top hat of an image is defined as the image minus its
    morphological opening. This operation returns the bright spots of the image
    that are smaller than the structuring element.

    Parameters
    ----------
    image : ndarray
        Image array.
    selem : ndarray, optional
        The neighborhood expressed as an array of 1's and 0's.
        If None, use cross-shaped structuring element (connectivity=1).
    out : ndarray, optional
        The array to store the result of the morphology. If None
        is passed, a new array will be allocated.

    Returns
    -------
    out : array, same shape and type as `image`
        The result of the morphological white top hat.

    See Also
    --------
    black_tophat

    References
    ----------
    .. [1] https://en.wikipedia.org/wiki/Top-hat_transform

    Examples
    --------
    >>> # Subtract grey background from bright peak
    >>> import numpy as np
    >>> from skimage.morphology import square
    >>> bright_on_grey = np.array([[2, 3, 3, 3, 2],
    ...                            [3, 4, 5, 4, 3],
    ...                            [3, 5, 9, 5, 3],
    ...                            [3, 4, 5, 4, 3],
    ...                            [2, 3, 3, 3, 2]], dtype=np.uint8)
    >>> white_tophat(bright_on_grey, square(3))
    array([[0, 0, 0, 0, 0],
           [0, 0, 1, 0, 0],
           [0, 1, 5, 1, 0],
           [0, 0, 1, 0, 0],
           [0, 0, 0, 0, 0]], dtype=uint8)

    """
    selem = np.array(selem)
    if out is image:
        opened = opening(image, selem)
        if np.issubdtype(opened.dtype, bool):
            np.logical_xor(out, opened, out=out)
        else:
            out -= opened
        return out
    elif out is None:
        out = np.empty_like(image)
    # work-around for NumPy deprecation warning for arithmetic
    # operations on bool arrays
    if isinstance(image, np.ndarray) and image.dtype == bool:
        image_ = image.view(dtype=np.uint8)
    else:
        image_ = image
    if isinstance(out, np.ndarray) and out.dtype == bool:
        out_ = out.view(dtype=np.uint8)
    else:
        out_ = out
    out_ = ndi.white_tophat(image_, footprint=selem, output=out_)
    return out




#path = 'C:/Users/55116867/Dropbox/codingchallenge/challengeFiles/'
path = 'C:/Users/MuhammadSalman/Dropbox/codingchallenge/challengeFiles/'
tiff_file = 'Wed_morningSession_nup555_647.1528885469405-2'

I = plt.imread(path+tiff_file+'.tif')
I = I/256
fig = plt.figure(figsize=(20,40))
plt.gray()  # show the filtered result in grayscale
ax1 = fig.add_subplot(121)  # left side 
ax2 = fig.add_subplot(122)
result = white_tophat(I,12)
result22 = ndimage.gaussian_laplace(result, sigma=3.4)
result22 = 1-result22
val = filters.threshold_otsu(result22)
result1 = result22>val
result2 = morphology.remove_small_objects(result1, 4)

distance = ndimage.distance_transform_edt(result2)

local_maxi = feature.peak_local_max(distance, indices=False, 
                            labels=result2)
markers = ndimage.label(local_maxi)[0]
labels = morphology.watershed(-distance, markers, mask=result2)
ax1.imshow(I)

ax2.imshow(I)