Snippets Collections
# ----------------------------------------------------------------------------------------------------------------------
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.cdivision(True)
@cython.nonecheck(False)
cpdef object get_boundaries(object data):
    """
    For a given field of pixels, this method returns a black and white mask, by using the "get_row_boundaries" method
    for each row and column.

    This is pretty fast, as it can rely on the power of numpy to do this operation very quickly.
    """
    cdef object rows = data.copy().astype(float)

    # -- row boundaries
    for i in range(len(data)):
        rows[i] = get_row_boundaries(data[i])

    # -- to get the boundary mask of our columns, transpose the image, shifting columns into rows
    cdef object columns = data.copy().T
    cdef object column_data = data.T

    # -- column boundaries
    for i in range(len(column_data)):
        columns[i] = get_row_boundaries(column_data[i])

    # -- having created our column mask, transpose it back.
    columns = columns.T

    # -- now combine both maps.
    return np.maximum(rows, columns)
# ----------------------------------------------------------------------------------------------------------------------
cpdef object get_row_boundaries(object row):
    """
    For a given row of pixels, this method returns a white pixel wherever a transition of values happens. The output is
    pure black and white, and expects an input of pure black and white.

    The way this is achieved, is by shifting the pixels in the row first left, then right, by one pixel. The shifted
    row (missing pixels filled with a value of 0) is then subtracted from the original, resulting in, for the right-
    shifted version, a white pixel where black turned into white, and for the left-shifted version, a white pixel
    where white turned into black.

    Taking the max() value of the combination of both of these gives us our boundary pixels for this row.
    """
    # -- this will give us a white pixel where black turned into white
    rising_diff = row - shift(row, 1, fill_value=0)

    # -- this will give us a white pixel where white turned into black
    decreasing_diff = row - shift(row, -1, fill_value=0)

    # -- this will combine both masks and give us the max() of both combined.
    return np.maximum(rising_diff, decreasing_diff)
star

Mon Feb 13 2023 22:44:08 GMT+0000 (Coordinated Universal Time)

#python #cython
star

Mon Feb 13 2023 22:41:48 GMT+0000 (Coordinated Universal Time)

#python #cython

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension