예제 #1
0
    def __init__(self, batch_size, num_threads=8):
        data = []
        target_shape = (224, 224)

        c = camera()
        c = resize(c.astype(np.float64), target_shape, 1, anti_aliasing=False, clip=True, mode='reflect').astype(np.float32)
        data.append(c[None])

        c = checkerboard()
        c = resize(c.astype(np.float64), target_shape, 1, anti_aliasing=False, clip=True, mode='reflect').astype(np.float32)
        data.append(c[None])

        c = astronaut().mean(-1)
        c = resize(c.astype(np.float64), target_shape, 1, anti_aliasing=False, clip=True, mode='reflect').astype(np.float32)
        data.append(c[None])

        c = binary_blobs()
        c = resize(c.astype(np.float64), target_shape, 1, anti_aliasing=False, clip=True, mode='reflect').astype(np.float32)
        data.append(c[None])

        c = coins()
        c = resize(c.astype(np.float64), target_shape, 1, anti_aliasing=False, clip=True, mode='reflect').astype(np.float32)
        data.append(c[None])
        data = np.stack(data)
        super(DummyDL2DImage, self).__init__(data, batch_size, num_threads)
예제 #2
0
def view_rotations(fake=False):
    if fake:
        global I
        I = data.checkerboard()
        p = Piece(42, 0, 0, I.shape[0], I.shape[1])
        p.set_b_angle(True)
        p.set_angle(10.0)
        Pieces[(42, 0)] = p
    for label, bbox in labelinfo.items():
        (y1, x1, y2, x2) = bbox
        P = copy.copy(I[y1:y2 + 1, x1:x2 + 1])
        LP = label_image[y1:y2 + 1, x1:x2 + 1]
        P[LP != label] = 0
        #for piece in Pieces.values():
        piece = Pieces[(label, 0)]
        #print piece.label, piece.dst_angle
        if True:  #not piece.dst_b_angle:
            fig, ax = plt.subplots(1, 3, figsize=(14, 7))
            IX = copy.copy(P)
            IX = transform.rotate(IX,
                                  piece.dst_result,
                                  resize=True,
                                  mode='constant',
                                  cval=0)
            ax[0].imshow(P)
            ax[1].imshow(IX)
            ax[2].axis('off')
            plt.show()
예제 #3
0
def test_swirl():
    image = img_as_float(data.checkerboard())

    swirl_params = {'radius': 80, 'rotation': 0, 'order': 2, 'mode': 'reflect'}
    swirled = tf.swirl(image, strength=10, **swirl_params)
    unswirled = tf.swirl(swirled, strength=-10, **swirl_params)

    assert np.mean(np.abs(image - unswirled)) < 0.01
예제 #4
0
def test_probabilistic_hough_seed():
    # Load image that is likely to give a randomly varying number of lines
    image = data.checkerboard()

    # Use constant seed to ensure a deterministic output
    lines = transform.probabilistic_hough_line(image, threshold=50,
                                               line_length=50, line_gap=1,
                                               seed=1234)
    assert len(lines) == 65
예제 #5
0
def test_probabilistic_hough_seed():
    # Load image that is likely to give a randomly varying number of lines
    image = data.checkerboard()

    # Use constant seed to ensure a deterministic output
    lines = transform.probabilistic_hough_line(image, threshold=50,
                                               line_length=50, line_gap=1,
                                               seed=1234)
    assert len(lines) == 65
def test_swirl():
    image = img_as_float(data.checkerboard())

    swirl_params = {'radius': 80, 'rotation': 0, 'order': 2, 'mode': 'reflect'}

    with expected_warnings(['Bi-quadratic.*bug']):
        swirled = tf.swirl(image, strength=10, **swirl_params)
        unswirled = tf.swirl(swirled, strength=-10, **swirl_params)

    assert np.mean(np.abs(image - unswirled)) < 0.01
예제 #7
0
def test_swirl():
    image = img_as_float(data.checkerboard())

    swirl_params = {'radius': 80, 'rotation': 0, 'order': 2, 'mode': 'reflect'}

    with expected_warnings(['Bi-quadratic.*bug']):
        swirled = tf.swirl(image, strength=10, **swirl_params)
        unswirled = tf.swirl(swirled, strength=-10, **swirl_params)

    assert np.mean(np.abs(image - unswirled)) < 0.01
예제 #8
0
def main():
    """Load image, calculate harris scores (window functions: matrix of ones, gauss)
    and plot the results."""
    img = data.checkerboard()
    score_window = harris_ones(img, 7)
    score_gauss = harris_gauss(img)
    util.plot_images_grayscale(
        [img, score_window, score_gauss, feature.corner_harris(img)],
        ["Image", "Harris-Score (ones)", "Harris-Score (gauss)", "Harris-Score (ground truth)"]
    )
예제 #9
0
def main():
    """Load image, calculate harris scores (window functions: matrix of ones, gauss)
    and plot the results."""
    img = data.checkerboard()
    score_window = harris_ones(img, 7)
    score_gauss = harris_gauss(img)
    util.plot_images_grayscale(
        [img, score_window, score_gauss,
         feature.corner_harris(img)], [
             "Image", "Harris-Score (ones)", "Harris-Score (gauss)",
             "Harris-Score (ground truth)"
         ])
예제 #10
0
def update_frame(i):
    c_ax.cla()
    tform = AffineTransform(
        scale=(1.3 + i / 20, 1.1 - i / 20),
        rotation=-i / 10,
        shear=i / 20,
        translation=(0, 0),
    )
    image = warp(data.checkerboard(), tform.inverse, output_shape=(200, 200))
    c_ax.imshow(image)
    peak_coords = corner_peaks(corner_harris(image))
    c_ax.plot(peak_coords[:, 1], peak_coords[:, 0], "rs")
예제 #11
0
def main():
    """Apply several gaussian filters one by one and plot the results each time."""
    img = data.checkerboard()
    shapes = [(5, 5), (7, 7), (11, 11), (17, 17), (31, 31)]
    sigmas = [0.5, 1.0, 2.0, 4.0, 8.0]
    smoothed = []
    for shape, sigma in zip(shapes, sigmas):
        smoothed = apply_gauss(img, gaussian_kernel(shape, sigma=sigma))
        ground_truth = filters.gaussian_filter(img, sigma)
        util.plot_images_grayscale(
            [img, smoothed, ground_truth],
            ["Image", "After gauss (sigma=%.1f)" % (sigma), "Ground Truth (scipy)"]
        )
예제 #12
0
def main():
    """Apply several gaussian filters one by one and plot the results each time."""
    img = data.checkerboard()
    shapes = [(5, 5), (7, 7), (11, 11), (17, 17), (31, 31)]
    sigmas = [0.5, 1.0, 2.0, 4.0, 8.0]
    smoothed = []
    for shape, sigma in zip(shapes, sigmas):
        smoothed = apply_gauss(img, gaussian_kernel(shape, sigma=sigma))
        ground_truth = filters.gaussian_filter(img, sigma)
        util.plot_images_grayscale([img, smoothed, ground_truth], [
            "Image",
            "After gauss (sigma=%.1f)" % (sigma), "Ground Truth (scipy)"
        ])
예제 #13
0
def generate_dataset(img_shape,
                     n=100,
                     video_path=None,
                     image_path=None,
                     image_type=None,
                     output_type="images",
                     output_folder="dataset/images/dots/",
                     partial=False,
                     mask=None):
    frames = []
    if mask is not None:
        mask = cv2.imread(mask, 0)
        mask = cv2.resize(mask, img_shape, interpolation=cv2.INTER_AREA)
    if video_path is not None:
        images, _ = get_video(video_path, n)
        x, z = get_dataset_from_video(images, n)
    elif image_path is not None:
        image = cv2.imread(image_path, 0)
        image = cv2.resize(image, img_shape, interpolation=cv2.INTER_AREA)
        x, z = get_dataset_from_image(image / 255,
                                      n,
                                      radius=[18, 22],
                                      partial=partial,
                                      mask=mask,
                                      pose=[[10, 10], [100, 100]],
                                      n_circles=2,
                                      v=[[1, 2], [2, 1]])
    elif image_type == "dots":
        image = generate_image(0.01)
        x, z = get_dataset_from_image(image,
                                      n,
                                      radius=[18, 22],
                                      partial=partial,
                                      mask=mask,
                                      pose=[[10, 10], [100, 100]],
                                      n_circles=2,
                                      v=[[1, 2], [2, 1]])
    elif image_type == "checkers":
        image = np.array(data.checkerboard()).astype(np.float64)
        image = cv2.resize(image, img_shape, interpolation=cv2.INTER_AREA)
        x, z = get_dataset_from_image(image / 255,
                                      n,
                                      radius=[18, 22],
                                      partial=partial,
                                      mask=mask,
                                      pose=[[10, 10], [100, 100]],
                                      n_circles=2,
                                      v=[[1, 2], [2, 1]])

    return x, z
예제 #14
0
    def test_blur(self):

        # 200x200 image and spatially-invariant psf
        im = data.checkerboard()
        psf = np.ones((5, 5)) / 5**2

        # Use the operator to convolve
        blur_operator = blur_matrix(im.shape[0], im.shape[1], psf)
        im_blurred = blur_operator * im.flat
        im_blurred = np.reshape(im_blurred, (200, 200))

        # Get the actual zero boundary convolution
        actual = convolve2d(im, psf, 'same', boundary='fill', fillvalue=0)

        npt.assert_equal(np.rint(im_blurred), np.rint(actual))
예제 #15
0
def swirled_with_checkerboard():
    image = data.checkerboard()
    swirled = transform.swirl(image, rotation=0, strength=10, radius=120)

    fig, (ax0, ax1) = plt.subplots(nrows=1,
                                   ncols=2,
                                   figsize=(8, 3),
                                   sharex=True,
                                   sharey=True)

    ax0.imshow(image, cmap=plt.cm.gray)
    ax0.axis('off')
    ax1.imshow(swirled, cmap=plt.cm.gray)
    ax1.axis('off')

    plt.show()
예제 #16
0
def process_selection(img_selected):
    if img_selected == "ASTRONAUT":
        return data.astronaut()
    if img_selected == "CHECKER":
        return data.checkerboard()
    if img_selected == "COINS":
        return data.coins()
    if img_selected == "HUBBLE":
        return data.hubble_deep_field()
    if img_selected == "HORSE":
        return data.horse()
    if img_selected == "CAMERA":
        return data.camera()
    if img_selected == "COFFEE":
        return data.coffee()
    else:
        return data.astronaut()
예제 #17
0
def test_swirl():
    image = img_as_float(cp.asarray(checkerboard()))

    swirl_params = {"radius": 80, "rotation": 0, "order": 2, "mode": "reflect"}

    # with expected_warnings(["Bi-quadratic.*bug"]):
    swirled = swirl(image, strength=10, **swirl_params)
    unswirled = swirl(swirled, strength=-10, **swirl_params)

    assert cp.mean(cp.abs(image - unswirled)) < 0.01

    swirl_params.pop("mode")

    # with expected_warnings(["Bi-quadratic.*bug"]):
    swirled = swirl(image, strength=10, **swirl_params)
    unswirled = swirl(swirled, strength=-10, **swirl_params)

    assert cp.mean(cp.abs(image[1:-1, 1:-1] - unswirled[1:-1, 1:-1])) < 0.01
예제 #18
0
def test_swirl():
    image = img_as_float(cp.array(checkerboard()))

    swirl_params = {'radius': 80, 'rotation': 0, 'order': 2, 'mode': 'reflect'}

    # with expected_warnings(["Bi-quadratic.*bug"]):
    swirled = swirl(image, strength=10, **swirl_params)
    unswirled = swirl(swirled, strength=-10, **swirl_params)

    assert cp.mean(cp.abs(image - unswirled)) < 0.01

    swirl_params.pop('mode')

    # with expected_warnings(["Bi-quadratic.*bug"]):
    swirled = swirl(image, strength=10, **swirl_params)
    unswirled = swirl(swirled, strength=-10, **swirl_params)

    assert cp.mean(cp.abs(image[1:-1, 1:-1] - unswirled[1:-1, 1:-1])) < 0.01
예제 #19
0
    def __init__(self):

        N = 50
        self.test_images = {}
        self.reader = SHGReader()

        "Make ringed test image"
        image_grid = np.mgrid[:N, :N]
        for i in range(2):
            image_grid[i] -= N * np.array(2 * image_grid[i] / N, dtype=int)
        image_grid = np.fft.fftshift(np.sqrt(np.sum(image_grid**2, axis=0)))
        self.test_images['test_image_rings'] = (
            np.sin(10 * np.pi * image_grid / N) *
            np.cos(10 * np.pi * image_grid / N))

        "Make circular test image"
        image_grid = np.mgrid[:N, :N]
        for i in range(2):
            image_grid[i] -= N * np.array(2 * image_grid[i] / N, dtype=int)
        image_grid = np.fft.fftshift(np.sqrt(np.sum(image_grid**2, axis=0)))
        self.test_images['test_image_circle'] = (
            1 - gaussian_filter(image_grid, N / 4, 5))

        "Make linear test image"
        test_image = np.zeros((N, N))
        for i in range(4):
            test_image += np.eye(N, N, k=5 - i)
        self.test_images['test_image_line'] = test_image

        "Make crossed test image"
        test_image = np.zeros((N, N))
        for i in range(4):
            test_image += np.eye(N, N, k=5 - i)
        for i in range(4):
            test_image += np.rot90(np.eye(N, N, k=5 - i))
        self.test_images['test_image_cross'] = np.where(test_image != 0, 1, 0)

        "Make noisy test image"
        self.test_images['test_image_noise'] = np.random.random((N, N))

        "Make checkered test image"
        self.test_images['test_image_checker'] = data.checkerboard()
예제 #20
0
def main():
    from matplotlib import pyplot as plt

    from skimage import data
    from skimage.transform import warp, AffineTransform
    from skimage.draw import ellipse

    # Sheared checkerboard
    tform = AffineTransform(scale=(1.3, 1.1),
                            rotation=1,
                            shear=0.7,
                            translation=(110, 30))
    image = warp(data.checkerboard()[:90, :90],
                 tform.inverse,
                 output_shape=(200, 310))
    # Ellipse
    rr, cc = ellipse(160, 175, 10, 100)
    image[rr, cc] = 1
    # Two squares
    image[30:80, 200:250] = 1
    image[80:130, 250:300] = 1
    image = plt.imread('price_center20.jpeg')
    image = color.rgb2gray(image)

    fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(8, 6))
    ax[0, 0].imshow(image, cmap='gray')
    ax[0, 0].set_title('Original image')

    ax[0, 1].imshow(corner_kitchen_rosenfeld(image), cmap='magma')
    ax[0, 1].set_title('Kitchen')

    ax[1, 0].imshow(corner_harris(image), cmap='magma')
    ax[1, 0].set_title('Harris')

    ax[1, 1].imshow(corner_shi_tomasi(image), cmap='magma')
    ax[1, 1].set_title('Shi-Tomasi')
    for a in ax.ravel():
        a.axis('off')

    plt.tight_layout()
    plt.show()
예제 #21
0
def test_swirl(dtype):
    image = img_as_float(checkerboard()).astype(dtype, copy=False)
    float_dtype = _supported_float_type(dtype)

    swirl_params = {'radius': 80, 'rotation': 0, 'order': 2, 'mode': 'reflect'}

    with expected_warnings(['Bi-quadratic.*bug']):
        swirled = swirl(image, strength=10, **swirl_params)
        unswirled = swirl(swirled, strength=-10, **swirl_params)
        assert swirled.dtype == unswirled.dtype == float_dtype

    assert np.mean(np.abs(image - unswirled)) < 0.01

    swirl_params.pop('mode')

    with expected_warnings(['Bi-quadratic.*bug']):
        swirled = swirl(image, strength=10, **swirl_params)
        unswirled = swirl(swirled, strength=-10, **swirl_params)
        assert swirled.dtype == unswirled.dtype == float_dtype

    assert np.mean(np.abs(image[1:-1, 1:-1] - unswirled[1:-1, 1:-1])) < 0.01
예제 #22
0
파일: features.py 프로젝트: adamgreig/iib
def profile():
    import time
    from iib.simulation import CLContext
    from skimage import io, data, transform
    gs, wgs = 256, 16

    # Load some test data
    r = transform.resize
    sigs = np.empty((gs, gs, 4), np.float32)
    sigs[:, :, 0] = r(data.coins().astype(np.float32) / 255.0, (gs, gs))
    sigs[:, :, 1] = r(data.camera().astype(np.float32) / 255.0, (gs, gs))
    sigs[:, :, 2] = r(data.text().astype(np.float32) / 255.0, (gs, gs))
    sigs[:, :, 3] = r(data.checkerboard().astype(np.float32) / 255.0, (gs, gs))
    sigs[:, :, 2] = r(io.imread("../scoring/corpus/rds/turing_001.png",
                                as_grey=True), (gs, gs))
    sigs[:, :, 3] = io.imread("../scoring/corpus/synthetic/blobs.png",
                              as_grey=True)
    sigs = sigs.reshape(gs*gs*4)

    # Set up OpenCL
    ctx = cl.create_some_context(interactive=False)
    queue = cl.CommandQueue(ctx)
    mf = cl.mem_flags
    ifmt_f = cl.ImageFormat(cl.channel_order.RGBA, cl.channel_type.FLOAT)
    bufi = cl.Image(ctx, mf.READ_ONLY, ifmt_f, (gs, gs))
    cl.enqueue_copy(queue, bufi, sigs, origin=(0, 0), region=(gs, gs))
    clctx = CLContext(ctx, queue, ifmt_f, gs, wgs)

    # Compile the kernels
    feats = cl.Program(ctx, features_cl()).build()
    rdctn = cl.Program(ctx, reduction.reduction_sum_cl()).build()
    blur2 = cl.Program(ctx, convolution.gaussian_cl([np.sqrt(2.0)]*4)).build()
    blur4 = cl.Program(ctx, convolution.gaussian_cl([np.sqrt(4.0)]*4)).build()

    iters = 500
    t0 = time.time()
    for i in range(iters):
        get_features(clctx, feats, rdctn, blur2, blur4, bufi)
    print((time.time() - t0)/iters)
예제 #23
0
def experiment2():
    import matplotlib.pyplot as plt

    from skimage import data
    from skimage.transform import swirl

    image = data.checkerboard()
    swirled = swirl(image, rotation=0, strength=0.5, radius=180)

    fig, (ax0, ax1) = plt.subplots(nrows=1,
                                   ncols=2,
                                   figsize=(8, 3),
                                   sharex=True,
                                   sharey=True,
                                   subplot_kw={'adjustable': 'box-forced'})

    ax0.imshow(image, cmap=plt.cm.gray, interpolation='none')
    ax0.axis('off')
    ax1.imshow(swirled, cmap=plt.cm.gray, interpolation='none')
    ax1.axis('off')

    plt.show()
예제 #24
0
    PYWAVELET_ND_INDEXING_WARNING = None

try:
    import dask
except ImportError:
    DASK_NOT_INSTALLED_WARNING = 'The optional dask dependency is not installed'
else:
    DASK_NOT_INSTALLED_WARNING = None


np.random.seed(1234)


astro = img_as_float(data.astronaut()[:128, :128])
astro_gray = color.rgb2gray(astro)
checkerboard_gray = img_as_float(data.checkerboard())
checkerboard = color.gray2rgb(checkerboard_gray)


def test_denoise_tv_chambolle_2d():
    # astronaut image
    img = astro_gray.copy()
    # add noise to astronaut
    img += 0.5 * img.std() * np.random.rand(*img.shape)
    # clip noise so that it does not exceed allowed range for float images.
    img = np.clip(img, 0, 1)
    # denoise
    denoised_astro = restoration.denoise_tv_chambolle(img, weight=0.1)
    # which dtype?
    assert_(denoised_astro.dtype in [np.float, np.float32, np.float64])
    from scipy import ndimage as ndi
예제 #25
0
hist = 4
img_shape = (128, 128)
noise_rate = 0.2
n = 600
n_test = 300
n_train = n - n_test
# ---- Get the dataset ---- #

z, x = generate_dataset(img_shape, n=n, image_type="checkers")
x_test = x[:n_train]
z_test = z[:n_train]
x_train = x[n_train:]
z_train = z[n_train:]

# ---- initialize particle filter ---- #
ref_img = np.array(data.checkerboard()).astype(np.float64)
ref_img = cv2.resize(ref_img, img_shape, interpolation=cv2.INTER_AREA)

pf = ParticleFilter_inverse(Np=300,
                            No=1,
                            ref_img=ref_img,
                            radiuses=[20],
                            initial_pose=[[10, 10]],
                            beta=60)

# ---- Test and viualize ---- #
x_old = x_test[:hist, ...].copy()
frames = []
obs_frames = []
state_frames = []
pf_frames = []
예제 #26
0
파일: test.py 프로젝트: asmeurer/numba-test
arg1 = sys.argv[1]

if int(arg1):
    print "using autojit"

autojit = autojit if int(arg1) else lambda: (lambda x: x)
jit = jit if int(arg1) else lambda x: (lambda x: x)

print autojit

print "generating checkerboard"
t = time.time()
tform = AffineTransform(scale=(1.3, 1.1), rotation=1, shear=0.7,
                            translation=(210, 50))
image = warp(data.checkerboard(), tform.inverse, output_shape=(5000, 5000))
# rr, cc = ellipse(310, 175, 100, 100)
#
# image[rr, cc] = 1
print "took", time.time() - t

print "generating squares"

@jit('void()')
def generate_squares_niave():
    for i in range(0, 5*50, 50):
        for j in range(180 + i, 230 + i):
            for k in range(10 + i, 60 + i):
                image[j, k] = 1
        for j in range(230 + i, 280 + i):
            for k in range(60 + i, 110 + i):
예제 #27
0
파일: features.py 프로젝트: adamgreig/iib
def test():
    import matplotlib.pyplot as plt
    from skimage import io, data, transform
    from iib.simulation import CLContext

    gs, wgs = 256, 16

    # Load some test data
    r = transform.resize
    sigs = np.empty((gs, gs, 4), np.float32)
    sigs[:, :, 0] = r(data.coins().astype(np.float32) / 255.0, (gs, gs))
    sigs[:, :, 1] = r(data.camera().astype(np.float32) / 255.0, (gs, gs))
    sigs[:, :, 2] = r(data.text().astype(np.float32) / 255.0, (gs, gs))
    sigs[:, :, 3] = r(data.checkerboard().astype(np.float32) / 255.0, (gs, gs))
    sigs[:, :, 2] = r(io.imread("../scoring/corpus/rds/turing_001.png",
                                as_grey=True), (gs, gs))
    sigs[:, :, 3] = io.imread("../scoring/corpus/synthetic/blobs.png",
                              as_grey=True)
    #sq = np.arange(256).astype(np.float32).reshape((16, 16)) / 255.0
    #sigs[:, :, 0] = np.tile(sq, (16, 16))
    sigs = sigs.reshape(gs*gs*4)

    # Set up OpenCL
    ctx = cl.create_some_context(interactive=False)
    queue = cl.CommandQueue(ctx)
    mf = cl.mem_flags
    ifmt_f = cl.ImageFormat(cl.channel_order.RGBA, cl.channel_type.FLOAT)
    bufi = cl.Image(ctx, mf.READ_ONLY, ifmt_f, (gs, gs))
    cl.enqueue_copy(queue, bufi, sigs, origin=(0, 0), region=(gs, gs))
    clctx = CLContext(ctx, queue, ifmt_f, gs, wgs)

    # Compile the kernels
    feats = cl.Program(ctx, features_cl()).build()
    rdctn = cl.Program(ctx, reduction.reduction_sum_cl()).build()
    blur2 = cl.Program(ctx, convolution.gaussian_cl([np.sqrt(2.0)]*4)).build()
    blur4 = cl.Program(ctx, convolution.gaussian_cl([np.sqrt(4.0)]*4)).build()

    entropy = get_entropy(clctx, feats, rdctn, bufi)
    print("Average entropy:", entropy)

    variance = get_variance(clctx, feats, rdctn, bufi)
    print("Variance:", variance)

    edges = get_edges(clctx, feats, rdctn, blur4, bufi, summarise=False)
    edge_counts = get_edges(clctx, feats, rdctn, blur4, bufi)
    print("Edge pixel counts:", edge_counts)

    blobs = get_blobs(clctx, feats, rdctn, blur2, bufi, summarise=False)

    features = get_features(clctx, feats, rdctn, blur2, blur4, bufi)
    print("Feature vector:")
    print(features)

    # Plot the edges and blobs
    for i in range(4):
        plt.subplot(4, 3, i*3+1)
        img = sigs.reshape((gs, gs, 4))[:, :, i]
        plt.imshow(img, cmap="gray")
        plt.xticks([])
        plt.yticks([])

        plt.subplot(4, 3, i*3+2)
        img = edges.reshape((gs, gs, 4))[:, :, i]
        plt.imshow(img, cmap="gray")
        plt.xticks([])
        plt.yticks([])

        ax = plt.subplot(4, 3, i*3+3)
        img = sigs.reshape((gs, gs, 4))[:, :, i]
        plt.imshow(img, cmap="gray")
        plt.xticks([])
        plt.yticks([])
        for j in range(len(blobs)):
            sblobs = blobs[j]
            s = 2**(j+1)
            r = np.sqrt(2.0) * s
            im = sblobs[:, :, i]
            posns = np.transpose(im.nonzero()) * 2**(j+1)
            for xy in posns:
                circ = plt.Circle((xy[1], xy[0]), r, color="green", fill=False)
                ax.add_patch(circ)
    plt.show()
예제 #28
0
def test_checkerboard():
    """ Test that "checkerboard" image can be loaded. """
    data.checkerboard()
예제 #29
0
.. [1] https://en.wikipedia.org/wiki/Flood_fill

Basic example
-------------

First, a basic example where we will change a checkerboard square from white
to mid-gray.
"""

import numpy as np
import matplotlib.pyplot as plt
from skimage import data, filters, color, morphology
from skimage.segmentation import flood, flood_fill


checkers = data.checkerboard()

# Fill a square near the middle with value 127, starting at index (76, 76)
filled_checkers = flood_fill(checkers, (76, 76), 127)

fig, ax = plt.subplots(ncols=2, figsize=(10, 5))

ax[0].imshow(checkers, cmap=plt.cm.gray)
ax[0].set_title('Original')

ax[1].imshow(filled_checkers, cmap=plt.cm.gray)
ax[1].plot(76, 76, 'wo')  # seed point
ax[1].set_title('After flood fill')

plt.show()
예제 #30
0
def test_checkerboard():
    """ Test that checkerboard image can be loaded. """
    checkerboard = data.checkerboard()
예제 #31
0
.. [1] https://en.wikipedia.org/wiki/Corner_detection
.. [2] https://en.wikipedia.org/wiki/Interest_point_detection

"""
from matplotlib import pyplot as plt

from skimage import data
from skimage.feature import corner_harris, corner_subpix, corner_peaks
from skimage.transform import warp, AffineTransform
from skimage.draw import ellipse


tform = AffineTransform(scale=(1.3, 1.1), rotation=1, shear=0.7,
                        translation=(210, 50))
image = warp(data.checkerboard(), tform.inverse, output_shape=(350, 350))
rr, cc = ellipse(310, 175, 10, 100)
image[rr, cc] = 1
image[180:230, 10:60] = 1
image[230:280, 60:110] = 1

coords = corner_peaks(corner_harris(image), min_distance=5)
coords_subpix = corner_subpix(image, coords, window_size=13)

fig, ax = plt.subplots()
ax.imshow(image, interpolation='nearest', cmap=plt.cm.gray)
ax.plot(coords[:, 1], coords[:, 0], '.b', markersize=3)
ax.plot(coords_subpix[:, 1], coords_subpix[:, 0], '+r', markersize=15)
ax.axis((0, 350, 350, 0))
plt.show()
예제 #32
0
.. [1] https://en.wikipedia.org/wiki/Corner_detection
.. [2] https://en.wikipedia.org/wiki/Interest_point_detection

"""
from matplotlib import pyplot as plt

from skimage import data
from skimage.feature import corner_harris, corner_subpix, corner_peaks
from skimage.transform import warp, AffineTransform
from skimage.draw import ellipse

# Sheared checkerboard
tform = AffineTransform(scale=(1.3, 1.1), rotation=1, shear=0.7,
                        translation=(110, 30))
image = warp(data.checkerboard()[:90, :90], tform.inverse,
             output_shape=(200, 310))
# Ellipse
rr, cc = ellipse(160, 175, 10, 100)
image[rr, cc] = 1
# Two squares
image[30:80, 200:250] = 1
image[80:130, 250:300] = 1

coords = corner_peaks(corner_harris(image), min_distance=5, threshold_rel=0.02)
coords_subpix = corner_subpix(image, coords, window_size=13)

fig, ax = plt.subplots()
ax.imshow(image, cmap=plt.cm.gray)
ax.plot(coords[:, 1], coords[:, 0], color='cyan', marker='o',
        linestyle='None', markersize=6)
예제 #33
0
def checkerboard(size):
    img = data.checkerboard()
    img3d = np.tile(img[..., np.newaxis], (1, 1, 3))
    return ia.imresize_single_image(img3d, size)
예제 #34
0
from skimage import morphology
from skimage import io, data
# http://scikit-image.org/docs/dev/api/skimage.data.html

img = data.checkerboard()
dilated_img = morphology.binary_dilation(img)

io.imshow(dilated_img)
io.show()
예제 #35
0
from __future__ import print_function

import numpy as np
from matplotlib import pyplot as plt

from skimage import data
from skimage.util import img_as_float
from skimage.feature import (corner_harris, corner_subpix, corner_peaks,
                             plot_matches)
from skimage.transform import warp, AffineTransform
from skimage.exposure import rescale_intensity
from skimage.color import rgb2gray
from skimage.measure import ransac

# generate synthetic checkerboard image and add gradient for the later matching
checkerboard = img_as_float(data.checkerboard())
img_orig = np.zeros(list(checkerboard.shape) + [3])
img_orig[..., 0] = checkerboard
gradient_r, gradient_c = (np.mgrid[0:img_orig.shape[0], 0:img_orig.shape[1]] /
                          float(img_orig.shape[0]))
img_orig[..., 1] = gradient_r
img_orig[..., 2] = gradient_c
img_orig = rescale_intensity(img_orig)
img_orig_gray = rgb2gray(img_orig)

# warp synthetic image
tform = AffineTransform(scale=(0.9, 0.9), rotation=0.2, translation=(20, -10))
img_warped = warp(img_orig, tform.inverse, output_shape=(200, 200))
img_warped_gray = rgb2gray(img_warped)

# extract corners using Harris' corner measure
예제 #36
0
.. [2] https://en.wikipedia.org/wiki/Interest_point_detection

"""
from matplotlib import pyplot as plt

from skimage import data
from skimage.feature import corner_harris, corner_subpix, corner_peaks
from skimage.transform import warp, AffineTransform
from skimage.draw import ellipse

# Sheared checkerboard
tform = AffineTransform(scale=(1.3, 1.1),
                        rotation=1,
                        shear=0.7,
                        translation=(110, 30))
image = warp(data.checkerboard()[:90, :90],
             tform.inverse,
             output_shape=(200, 310))
# Ellipse
rr, cc = ellipse(160, 175, 10, 100)
image[rr, cc] = 1
# Two squares
image[30:80, 200:250] = 1
image[80:130, 250:300] = 1

coords = corner_peaks(corner_harris(image), min_distance=5)
coords_subpix = corner_subpix(image, coords, window_size=13)

fig, ax = plt.subplots()
ax.imshow(image, cmap=plt.cm.gray)
ax.plot(coords[:, 1],
예제 #37
0
    PYWAVELET_ND_INDEXING_WARNING = 'Using a non-tuple sequence'
else:
    PYWAVELET_ND_INDEXING_WARNING = None

try:
    import dask
except ImportError:
    DASK_NOT_INSTALLED_WARNING = 'The optional dask dependency is not installed'
else:
    DASK_NOT_INSTALLED_WARNING = None

np.random.seed(1234)

astro = img_as_float(data.astronaut()[:128, :128])
astro_gray = color.rgb2gray(astro)
checkerboard_gray = img_as_float(data.checkerboard())
checkerboard = color.gray2rgb(checkerboard_gray)
# versions with one odd-sized dimension
astro_gray_odd = astro_gray[:, :-1]
astro_odd = astro[:, :-1]


def test_denoise_tv_chambolle_2d():
    # astronaut image
    img = astro_gray.copy()
    # add noise to astronaut
    img += 0.5 * img.std() * np.random.rand(*img.shape)
    # clip noise so that it does not exceed allowed range for float images.
    img = np.clip(img, 0, 1)
    # denoise
    denoised_astro = restoration.denoise_tv_chambolle(img, weight=0.1)
예제 #38
0
def checkerboard(size):
    img = data.checkerboard()
    img3d = np.tile(img[..., np.newaxis], (1, 1, 3))
    return misc.imresize(img3d, size)
예제 #39
0
to robustly estimate the parameter set by detecting outliers.

"""
import numpy as np
from matplotlib import pyplot as plt

from skimage import data
from skimage.feature import corner_harris, corner_subpix, corner_peaks
from skimage.transform import warp, AffineTransform
from skimage.exposure import rescale_intensity
from skimage.color import rgb2gray
from skimage.measure import ransac


# generate synthetic checkerboard image and add gradient for the later matching
checkerboard = data.checkerboard()
img_orig = np.zeros(list(checkerboard.shape) + [3])
img_orig[..., 0] = checkerboard
gradient_r, gradient_c = np.mgrid[0:img_orig.shape[0], 0:img_orig.shape[1]]
img_orig[..., 1] = gradient_r
img_orig[..., 2] = gradient_c
img_orig = rescale_intensity(img_orig)
img_orig_gray = rgb2gray(img_orig)

# warp synthetic image
tform = AffineTransform(scale=(0.9, 0.9), rotation=0.2, translation=(20, -10))
img_warped = warp(img_orig, tform.inverse, output_shape=(200, 200))
img_warped_gray = rgb2gray(img_warped)

# extract corners using Harris' corner measure
coords_orig = corner_peaks(corner_harris(img_orig_gray), threshold_rel=0.001,
예제 #40
0
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 21 13:10:04 2015

@author: prassanna
"""

###FILTERS AND BLURRING############

from skimage import filter,io,data,color,feature,img_as_float
from matplotlib import pyplot as plt
import numpy as np

img = img_as_float(data.checkerboard());
print img.shape
io.imshow(img)

##Gaussian
noisy = img + 0.6 * img.std() * np.random.random(img.shape)
noisy = np.clip(noisy, 0, 1)
blurred = filter.gaussian_filter(noisy, 2);
#blurred_int = np.uint8(blurred*255)
#print np.amax(blurred_int)
bla = np.vstack((img,noisy,blurred))
io.imshow(bla)


#2nd Gaussian
from math import sqrt
img_2  = data.hubble_deep_field()
img_2  = img_2 [0:500,0:500]
예제 #41
0
    \phi = \mathtt{rotation}

    s = \mathtt{strength}

    \\theta' = \phi + s \, e^{-\\rho / r + \\theta}

where ``strength`` is a parameter for the amount of swirl, ``radius`` indicates
the swirl extent in pixels, and ``rotation`` adds a rotation angle.  The
transformation of ``radius`` into :math:`r` is to ensure that the
transformation decays to :math:`\\approx 1/1000^{\mathsf{th}}` within the
specified radius.

"""
import matplotlib.pyplot as plt

from skimage import data
from skimage.transform import swirl


image = data.checkerboard()
swirled = swirl(image, rotation=0, strength=10, radius=120, order=2)

fig, (ax0, ax1) = plt.subplots(1, 2, figsize=(8, 3), sharex=True, sharey=True, subplot_kw={'adjustable':'box-forced'})

ax0.imshow(image, cmap=plt.cm.gray, interpolation='none')
ax0.axis('off')
ax1.imshow(swirled, cmap=plt.cm.gray, interpolation='none')
ax1.axis('off')

plt.show()
"""
Affine transform
=================

Warping and affine transforms of images.
"""

from matplotlib import pyplot as plt

from skimage import data
from skimage.feature import corner_harris, corner_subpix, corner_peaks
from skimage.transform import warp, AffineTransform


tform = AffineTransform(scale=(1.3, 1.1), rotation=1, shear=0.7,
                        translation=(210, 50))
image = warp(data.checkerboard(), tform.inverse, output_shape=(350, 350))

coords = corner_peaks(corner_harris(image), min_distance=5)
coords_subpix = corner_subpix(image, coords, window_size=13)

plt.gray()
plt.imshow(image, interpolation='nearest')
plt.plot(coords_subpix[:, 1], coords_subpix[:, 0], '+r', markersize=15, mew=5)
plt.plot(coords[:, 1], coords[:, 0], '.b', markersize=7)
plt.axis('off')
plt.show()