Ejemplo n.º 1
0
def test_adapthist_grayscale_Nd():
    """
    Test for n-dimensional consistency with float images
    Note: Currently if img.ndim == 3, img.shape[2] > 4 must hold for the image
    not to be interpreted as a color image by @adapt_rgb
    """
    # take 2d image, subsample and stack it
    img = util.img_as_float(cp.array(data.astronaut()))
    img = rgb2gray(img)
    a = 15
    img2d = util.img_as_float(img[0:-1:a, 0:-1:a])
    img3d = cp.stack([img2d] * (img.shape[0] // a), axis=0)

    # apply CLAHE
    adapted2d = exposure.equalize_adapthist(img2d,
                                            kernel_size=5,
                                            clip_limit=0.05)
    adapted3d = exposure.equalize_adapthist(img3d,
                                            kernel_size=5,
                                            clip_limit=0.05)

    # check that dimensions of input and output match
    assert img2d.shape == adapted2d.shape
    assert img3d.shape == adapted3d.shape

    # check that the result from the stack of 2d images is similar
    # to the underlying 2d image
    assert cp.mean(
        cp.abs(adapted2d - adapted3d[adapted3d.shape[0] // 2])) < 0.02
Ejemplo n.º 2
0
def test_bimodal_multiotsu_hist():
    for name in ['camera', 'moon', 'coins', 'text', 'clock', 'page']:
        img = cp.array(getattr(data, name)())
        assert threshold_otsu(img) == threshold_multiotsu(img, 2)

    for name in ['chelsea', 'coffee', 'astronaut', 'rocket']:
        img = rgb2gray(cp.array(getattr(data, name)()))
        assert threshold_otsu(img) == threshold_multiotsu(img, 2)
Ejemplo n.º 3
0
def norm_brightness_err(img1, img2):
    """Normalized Absolute Mean Brightness Error between two images

    Parameters
    ----------
    img1 : array-like
    img2 : array-like

    Returns
    -------
    norm_brightness_error : float
        Normalized absolute mean brightness error
    """
    if img1.ndim == 3:
        img1, img2 = rgb2gray(img1), rgb2gray(img2)
    ambe = cp.abs(img1.mean() - img2.mean())
    nbe = ambe / dtype_range[img1.dtype.type][1]
    return nbe
Ejemplo n.º 4
0
def peak_snr(img1, img2):
    """Peak signal to noise ratio of two images

    Parameters
    ----------
    img1 : array-like
    img2 : array-like

    Returns
    -------
    peak_snr : float
        Peak signal to noise ratio
    """
    if img1.ndim == 3:
        img1, img2 = rgb2gray(img1.copy()), rgb2gray(img2.copy())
    img1 = util.img_as_float(img1)
    img2 = util.img_as_float(img2)
    mse = 1.0 / img1.size * cp.square(img1 - img2).sum()
    _, max_ = dtype_range[img1.dtype.type]
    return 20 * cp.log(max_ / mse)
Ejemplo n.º 5
0
def test_adapthist_grayscale():
    """Test a grayscale float image"""
    img = util.img_as_float(cp.array(data.astronaut()))
    img = rgb2gray(img)
    img = cp.dstack((img, img, img))
    adapted = exposure.equalize_adapthist(img,
                                          kernel_size=(57, 51),
                                          clip_limit=0.01,
                                          nbins=128)
    assert img.shape == adapted.shape
    assert_almost_equal(float(peak_snr(img, adapted)), 100.140, 3)
    assert_almost_equal(float(norm_brightness_err(img, adapted)), 0.0529, 3)
Ejemplo n.º 6
0
def test_num_peaks():
    """For a bunch of different values of num_peaks, check that
    peak_local_max returns exactly the right amount of peaks. Test
    is run on the astronaut image in order to produce a sufficient number of
    corners
    """

    img_corners = corner_harris(rgb2gray(cp.asarray(data.astronaut())))

    for i in range(20):
        n = cp.random.randint(1, 21)
        results = peak_local_max(img_corners,
                                 min_distance=10,
                                 threshold_rel=0,
                                 num_peaks=n)
        assert results.shape[0] == n
Ejemplo n.º 7
0
    def _build_expected_output(self):
        funcs = (grey.erosion, grey.dilation, grey.opening, grey.closing,
                 grey.white_tophat, grey.black_tophat)
        selems_2D = (selem.square, selem.diamond, selem.disk, selem.star)

        image = img_as_ubyte(
            transform.downscale_local_mean(
                color.rgb2gray(cp.array(data.coffee())), (20, 20)))

        output = {}
        for n in range(1, 4):
            for strel in selems_2D:
                for func in funcs:
                    key = '{0}_{1}_{2}'.format(strel.__name__, n,
                                               func.__name__)
                    output[key] = func(image, strel(n))

        return output
Ejemplo n.º 8
0
def test_adapthist_borders():
    """Test border processing
    """
    img = rgb2gray(util.img_as_float(cp.array(data.astronaut())))

    # maximize difference between orig and processed img
    img /= 100.0
    img[img.shape[0] // 2, img.shape[1] // 2] = 1.0

    # check borders are processed for different kernel sizes
    border_index = -1
    for kernel_size in range(51, 71, 2):
        adapted = exposure.equalize_adapthist(img, kernel_size, clip_limit=0.5)
        # Check last columns are processed
        assert norm_brightness_err(adapted[:, border_index],
                                   img[:, border_index]) > 0.1
        # Check last rows are processed
        assert norm_brightness_err(adapted[border_index, :],
                                   img[border_index, :]) > 0.1
Ejemplo n.º 9
0
def test_border_management(func, tol):
    img = rgb2gray(cp.array(retina()[300:500, 700:900]))
    out = func(img, sigmas=[1], mode='mirror')

    full_std = out.std()
    full_mean = out.mean()
    inside_std = out[4:-4, 4:-4].std()
    inside_mean = out[4:-4, 4:-4].mean()
    border_std = cp.stack([out[:4, :], out[-4:, :],
                           out[:, :4].T, out[:, -4:].T]).std()
    border_mean = cp.stack([out[:4, :], out[-4:, :],
                            out[:, :4].T, out[:, -4:].T]).mean()

    assert abs(full_std - inside_std) < tol
    assert abs(full_std - border_std) < tol
    assert abs(inside_std - border_std) < tol
    assert abs(full_mean - inside_mean) < tol
    assert abs(full_mean - border_mean) < tol
    assert abs(inside_mean - border_mean) < tol
Ejemplo n.º 10
0
def test_richardson_lucy_filtered(dtype_image, dtype_psf):
    if dtype_image == np.float64:
        atol = 1e-8
    else:
        atol = 1e-4

    test_img_astro = rgb2gray(astronaut())

    psf = cp.ones((5, 5), dtype=dtype_psf) / 25
    data = cp.array(signal.convolve2d(cp.asnumpy(test_img_astro),
                                      cp.asnumpy(psf), 'same'),
                    dtype=dtype_image)
    deconvolved = restoration.richardson_lucy(data,
                                              psf,
                                              5,
                                              filter_epsilon=1e-6)
    assert deconvolved.dtype == data.dtype

    path = fetch('restoration/tests/astronaut_rl.npy')
    cp.testing.assert_allclose(deconvolved,
                               np.load(path),
                               rtol=1e-3,
                               atol=atol)
Ejemplo n.º 11
0
    def test_rgb2gray_dtype(self):
        img = cp.random.rand(10, 10, 3).astype('float64')
        img32 = img.astype('float32')

        assert rgb2gray(img).dtype == img.dtype
        assert rgb2gray(img32).dtype == img32.dtype
Ejemplo n.º 12
0
 def test_rgb2gray_on_gray(self):
     with expected_warnings(['The behavior of rgb2gray will change']):
         rgb2gray(cp.random.rand(5, 5))
Ejemplo n.º 13
0
 def test_rgb2gray_alpha(self):
     x = cp.random.rand(10, 10, 4)
     with expected_warnings(['Non RGB image conversion']):
         assert rgb2gray(x).ndim == 2
Ejemplo n.º 14
0
 def test_rgb2gray_contiguous(self):
     x = cp.random.rand(10, 10, 3)
     assert rgb2gray(x).flags["C_CONTIGUOUS"]
     assert rgb2gray(x[:5, :5]).flags["C_CONTIGUOUS"]
Ejemplo n.º 15
0
    def test_rgb2gray(self):
        x = cp.asarray([1, 1, 1]).reshape((1, 1, 3)).astype(float)
        g = rgb2gray(x)
        assert_array_almost_equal(g, 1)

        assert_array_equal(g.shape, (1, 1))
Ejemplo n.º 16
0
import cupy as cp
import numpy as np
import pytest
from cupy import testing
from cupyx.scipy import ndimage as ndi
from skimage import data

from cucim.skimage import color
from cucim.skimage.morphology import binary, grey, selem
from cucim.skimage.util import img_as_bool

img = color.rgb2gray(cp.array(data.astronaut()))
bw_img = img > 100 / 255.0


def test_non_square_image():
    strel = selem.square(3)
    binary_res = binary.binary_erosion(bw_img[:100, :200], strel)
    grey_res = img_as_bool(grey.erosion(bw_img[:100, :200], strel))
    testing.assert_array_equal(binary_res, grey_res)


def test_binary_erosion():
    strel = selem.square(3)
    binary_res = binary.binary_erosion(bw_img, strel)
    grey_res = img_as_bool(grey.erosion(bw_img, strel))
    testing.assert_array_equal(binary_res, grey_res)


def test_binary_dilation():
    strel = selem.square(3)
Ejemplo n.º 17
0
def test_border_warning(func):
    img = rgb2gray(cp.array(retina()[300:500, 700:900]))

    with expected_warnings(["implicitly used 'constant' as the border mode"]):
        func(img, sigmas=[1])
Ejemplo n.º 18
0
def test_output_dtype(func, dtype):
    img = rgb2gray(cp.array(retina()[300:500, 700:900], dtype=dtype))

    out = func(img, sigmas=[1], mode='reflect')
    assert out.dtype == dtype