Exemple #1
0
def main():
    """Load image, apply histogram stretching and cumulative histogram
    equalization. Plot the results."""
    img = data.text()

    height, width = img.shape
    nb_pixels = height * width

    # apply histogram stretching
    gray_min = np.min(img)
    gray_max = np.max(img)
    img_hist_stretched = (img - gray_min) * (255 / (gray_max - gray_min))
    img_hist_stretched = img_hist_stretched.astype(np.uint8)

    # apply cumulative histogram equalization
    img_cumulative = np.zeros(img.shape, dtype=np.uint8)
    hist_cumulative = [0] * 256
    running_sum = 0
    hist, edges = np.histogram(img, 256, (0, 255))
    for i in range(256):
        count = hist[i]
        running_sum += count
        hist_cumulative[i] = running_sum / nb_pixels

    for i in range(256):
        img_cumulative[img == i] = int(256 * hist_cumulative[i])

    # plot
    plot_images_grayscale([img, img_hist_stretched, img_cumulative], [
        "Image", "Histogram stretched to 0-255",
        "Cumulative Histogram Equalization"
    ])
def test_RGB(dtype):
    img = gaussian(data.text(), 1)
    imgR = np.zeros((img.shape[0], img.shape[1], 3), dtype=dtype)
    imgG = np.zeros((img.shape[0], img.shape[1], 3), dtype=dtype)
    imgRGB = np.zeros((img.shape[0], img.shape[1], 3), dtype=dtype)
    imgR[:, :, 0] = img
    imgG[:, :, 1] = img
    imgRGB[:, :, :] = img[:, :, None]
    r = np.linspace(136, 50, 100)
    c = np.linspace(5, 424, 100)
    init = np.array([r, c]).T
    snake = active_contour(imgR, init, boundary_condition='fixed',
                           alpha=0.1, beta=1.0, w_line=-5, w_edge=0, gamma=0.1)
    float_dtype = _supported_float_type(dtype)
    assert snake.dtype == float_dtype
    refr = [136, 135, 134, 133, 132, 131, 129, 128, 127, 125]
    refc = [5, 9, 13, 17, 21, 25, 30, 34, 38, 42]
    assert_equal(np.array(snake[:10, 0], dtype=np.int32), refr)
    assert_equal(np.array(snake[:10, 1], dtype=np.int32), refc)
    snake = active_contour(imgG, init, boundary_condition='fixed',
                           alpha=0.1, beta=1.0, w_line=-5, w_edge=0, gamma=0.1)
    assert snake.dtype == float_dtype
    assert_equal(np.array(snake[:10, 0], dtype=np.int32), refr)
    assert_equal(np.array(snake[:10, 1], dtype=np.int32), refc)
    snake = active_contour(imgRGB, init, boundary_condition='fixed',
                           alpha=0.1, beta=1.0, w_line=-5/3., w_edge=0,
                           gamma=0.1)
    assert snake.dtype == float_dtype
    assert_equal(np.array(snake[:10, 0], dtype=np.int32), refr)
    assert_equal(np.array(snake[:10, 1], dtype=np.int32), refc)
def test_RGB():
    img = gaussian(data.text(), 1)
    imgR = np.zeros((img.shape[0], img.shape[1], 3))
    imgG = np.zeros((img.shape[0], img.shape[1], 3))
    imgRGB = np.zeros((img.shape[0], img.shape[1], 3))
    imgR[:, :, 0] = img
    imgG[:, :, 1] = img
    imgRGB[:, :, :] = img[:, :, None]
    x = np.linspace(5, 424, 100)
    y = np.linspace(136, 50, 100)
    init = np.array([x, y]).T
    snake = active_contour(imgR, init, bc='fixed',
            alpha=0.1, beta=1.0, w_line=-5, w_edge=0, gamma=0.1)
    refx = [5, 9, 13, 17, 21, 25, 30, 34, 38, 42]
    refy = [136, 135, 134, 133, 132, 131, 129, 128, 127, 125]
    assert_equal(np.array(snake[:10, 0], dtype=np.int32), refx)
    assert_equal(np.array(snake[:10, 1], dtype=np.int32), refy)
    snake = active_contour(imgG, init, bc='fixed',
            alpha=0.1, beta=1.0, w_line=-5, w_edge=0, gamma=0.1)
    assert_equal(np.array(snake[:10, 0], dtype=np.int32), refx)
    assert_equal(np.array(snake[:10, 1], dtype=np.int32), refy)
    snake = active_contour(imgRGB, init, bc='fixed',
            alpha=0.1, beta=1.0, w_line=-5/3., w_edge=0, gamma=0.1)
    assert_equal(np.array(snake[:10, 0], dtype=np.int32), refx)
    assert_equal(np.array(snake[:10, 1], dtype=np.int32), refy)
def main():
    """Load image, apply histogram stretching and cumulative histogram
    equalization. Plot the results."""
    img = data.text()

    height, width = img.shape
    nb_pixels = height * width

    # apply histogram stretching
    gray_min = np.min(img)
    gray_max = np.max(img)
    img_hist_stretched = (img - gray_min) * (255 / (gray_max - gray_min))
    img_hist_stretched = img_hist_stretched.astype(np.uint8)

    # apply cumulative histogram equalization
    img_cumulative = np.zeros(img.shape, dtype=np.uint8)
    hist_cumulative = [0] * 256
    running_sum = 0
    hist, edges = np.histogram(img, 256, (0, 255))
    for i in range(256):
        count = hist[i]
        running_sum += count
        hist_cumulative[i] = running_sum / nb_pixels

    for i in range(256):
        img_cumulative[img == i] = int(256 * hist_cumulative[i])

    # plot
    plot_images_grayscale(
        [img, img_hist_stretched, img_cumulative],
        ["Image", "Histogram stretched to 0-255", "Cumulative Histogram Equalization"]
    )
def test_RGB():
    img = gaussian(data.text(), 1)
    imgR = np.zeros((img.shape[0], img.shape[1], 3))
    imgG = np.zeros((img.shape[0], img.shape[1], 3))
    imgRGB = np.zeros((img.shape[0], img.shape[1], 3))
    imgR[:, :, 0] = img
    imgG[:, :, 1] = img
    imgRGB[:, :, :] = img[:, :, None]
    x = np.linspace(5, 424, 100)
    y = np.linspace(136, 50, 100)
    init = np.array([x, y]).T
    snake = active_contour(imgR, init, bc='fixed',
            alpha=0.1, beta=1.0, w_line=-5, w_edge=0, gamma=0.1)
    refx = [5, 9, 13, 17, 21, 25, 30, 34, 38, 42]
    refy = [136, 135, 134, 133, 132, 131, 129, 128, 127, 125]
    assert_equal(np.array(snake[:10, 0], dtype=np.int32), refx)
    assert_equal(np.array(snake[:10, 1], dtype=np.int32), refy)
    snake = active_contour(imgG, init, bc='fixed',
            alpha=0.1, beta=1.0, w_line=-5, w_edge=0, gamma=0.1)
    assert_equal(np.array(snake[:10, 0], dtype=np.int32), refx)
    assert_equal(np.array(snake[:10, 1], dtype=np.int32), refy)
    snake = active_contour(imgRGB, init, bc='fixed',
            alpha=0.1, beta=1.0, w_line=-5/3., w_edge=0, gamma=0.1)
    assert_equal(np.array(snake[:10, 0], dtype=np.int32), refx)
    assert_equal(np.array(snake[:10, 1], dtype=np.int32), refy)
def test_free_reference():
    img = data.text()
    x = np.linspace(5, 424, 100)
    y = np.linspace(70, 40, 100)
    init = np.array([x, y]).T
    snake = active_contour(gaussian(img, 3), init, bc='free',
            alpha=0.1, beta=1.0, w_line=-5, w_edge=0, gamma=0.1)
    refx = [10, 13, 16, 19, 23, 26, 29, 32, 36, 39]
    refy = [76, 76, 75, 74, 73, 72, 71, 70, 69, 69]
    assert_equal(np.array(snake[:10, 0], dtype=np.int32), refx)
    assert_equal(np.array(snake[:10, 1], dtype=np.int32), refy)
def test_fixed_reference():
    img = data.text()
    x = np.linspace(5, 424, 100)
    y = np.linspace(136, 50, 100)
    init = np.array([x, y]).T
    snake = active_contour(gaussian(img, 1), init, bc='fixed',
            alpha=0.1, beta=1.0, w_line=-5, w_edge=0, gamma=0.1)
    refx = [5, 9, 13, 17, 21, 25, 30, 34, 38, 42]
    refy = [136, 135, 134, 133, 132, 131, 129, 128, 127, 125]
    assert_equal(np.array(snake[:10, 0], dtype=np.int32), refx)
    assert_equal(np.array(snake[:10, 1], dtype=np.int32), refy)
def test_free_reference():
    img = data.text()
    x = np.linspace(5, 424, 100)
    y = np.linspace(70, 40, 100)
    init = np.array([x, y]).T
    snake = active_contour(gaussian(img, 3), init, bc='free',
            alpha=0.1, beta=1.0, w_line=-5, w_edge=0, gamma=0.1)
    refx = [10, 13, 16, 19, 23, 26, 29, 32, 36, 39]
    refy = [76, 76, 75, 74, 73, 72, 71, 70, 69, 69]
    assert_equal(np.array(snake[:10, 0], dtype=np.int32), refx)
    assert_equal(np.array(snake[:10, 1], dtype=np.int32), refy)
def test_fixed_reference():
    img = data.text()
    x = np.linspace(5, 424, 100)
    y = np.linspace(136, 50, 100)
    init = np.array([x, y]).T
    snake = active_contour(gaussian(img, 1), init, bc='fixed',
            alpha=0.1, beta=1.0, w_line=-5, w_edge=0, gamma=0.1)
    refx = [5, 9, 13, 17, 21, 25, 30, 34, 38, 42]
    refy = [136, 135, 134, 133, 132, 131, 129, 128, 127, 125]
    assert_equal(np.array(snake[:10, 0], dtype=np.int32), refx)
    assert_equal(np.array(snake[:10, 1], dtype=np.int32), refy)
def test_triangle_float_images():
    text = data.text()
    int_bins = text.max() - text.min() + 1
    # Set nbins to match the uint case and threshold as float.
    assert(round(threshold_triangle(
        text.astype(np.float), nbins=int_bins)) == 104)
    # Check that rescaling image to floats in unit interval is equivalent.
    assert(round(threshold_triangle(text / 255., nbins=int_bins) * 255) == 104)
    # Repeat for inverted image.
    assert(round(threshold_triangle(
        np.invert(text).astype(np.float), nbins=int_bins)) == 151)
    assert (round(threshold_triangle(
        np.invert(text) / 255., nbins=int_bins) * 255) == 151)
def test_free_reference(dtype):
    img = data.text()
    r = np.linspace(70, 40, 100)
    c = np.linspace(5, 424, 100)
    init = np.array([r, c]).T
    img_smooth = gaussian(img, 3).astype(dtype, copy=False)
    snake = active_contour(img_smooth, init, boundary_condition='free',
                           alpha=0.1, beta=1.0, w_line=-5, w_edge=0, gamma=0.1)
    assert snake.dtype == _supported_float_type(dtype)
    refr = [76, 76, 75, 74, 73, 72, 71, 70, 69, 69]
    refc = [10, 13, 16, 19, 23, 26, 29, 32, 36, 39]
    assert_equal(np.array(snake[:10, 0], dtype=np.int32), refr)
    assert_equal(np.array(snake[:10, 1], dtype=np.int32), refc)
def test_fixed_reference(dtype):
    img = data.text()
    r = np.linspace(136, 50, 100)
    c = np.linspace(5, 424, 100)
    init = np.array([r, c]).T
    image_smooth = gaussian(img, 1).astype(dtype, copy=False)
    snake = active_contour(image_smooth, init, boundary_condition='fixed',
                           alpha=0.1, beta=1.0, w_line=-5, w_edge=0, gamma=0.1)
    assert snake.dtype == _supported_float_type(dtype)
    refr = [136, 135, 134, 133, 132, 131, 129, 128, 127, 125]
    refc = [5, 9, 13, 17, 21, 25, 30, 34, 38, 42]
    assert_equal(np.array(snake[:10, 0], dtype=np.int32), refr)
    assert_equal(np.array(snake[:10, 1], dtype=np.int32), refc)
def test_triangle_float_images():
    text = data.text()
    int_bins = text.max() - text.min() + 1
    # Set nbins to match the uint case and threshold as float.
    assert(round(threshold_triangle(
        text.astype(np.float), nbins=int_bins)) == 104)
    # Check that rescaling image to floats in unit interval is equivalent.
    assert(round(threshold_triangle(text / 255., nbins=int_bins) * 255) == 104)
    # Repeat for inverted image.
    assert(round(threshold_triangle(
        np.invert(text).astype(np.float), nbins=int_bins)) == 151)
    assert (round(threshold_triangle(
        np.invert(text) / 255., nbins=int_bins) * 255) == 151)
Exemple #14
0
def active_contour_example():
    img = data.astronaut()
    img = rgb2gray(img)

    s = np.linspace(0, 2 * np.pi, 400)
    x = 220 + 100 * np.cos(s)
    y = 100 + 100 * np.sin(s)
    init = np.array([x, y]).T

    snake = active_contour(gaussian(img, 3),
                           init,
                           alpha=0.015,
                           beta=10,
                           gamma=0.001)

    fig, ax = plt.subplots(figsize=(7, 7))
    ax.imshow(img, cmap=plt.cm.gray)
    ax.plot(init[:, 0], init[:, 1], '--r', lw=3)
    ax.plot(snake[:, 0], snake[:, 1], '-b', lw=3)
    ax.set_xticks([]), ax.set_yticks([])
    ax.axis([0, img.shape[1], img.shape[0], 0])

    #--------------------
    img = data.text()

    x = np.linspace(5, 424, 100)
    y = np.linspace(136, 50, 100)
    init = np.array([x, y]).T

    snake = active_contour(gaussian(img, 1),
                           init,
                           bc='fixed',
                           alpha=0.1,
                           beta=1.0,
                           w_line=-5,
                           w_edge=0,
                           gamma=0.1)

    fig, ax = plt.subplots(figsize=(9, 5))
    ax.imshow(img, cmap=plt.cm.gray)
    ax.plot(init[:, 0], init[:, 1], '--r', lw=3)
    ax.plot(snake[:, 0], snake[:, 1], '-b', lw=3)
    ax.set_xticks([]), ax.set_yticks([])
    ax.axis([0, img.shape[1], img.shape[0], 0])

    plt.show()
Exemple #15
0
def line_detect():
    im = data.text()
    seg = im < 100
    r = transform.radon(seg)
    rho, theta = np.unravel_index(np.argmax(r), r.shape)
    rho = rho - r.shape[0] / 2
    x = np.int(rho * np.cos((theta + 90) * np.pi / 180) + im.shape[0] / 2)
    y = np.int(rho * np.sin((theta + 90) * np.pi / 180) + im.shape[1] / 2)
    dx = np.cos((theta) * np.pi / 180)
    dy = np.sin((theta) * np.pi / 180)

    l = 1000
    res = im.copy()
    cv2.line(res, (np.int(y - dy * l), np.int(x - dx * l)),
             (np.int(y + dy * l), np.int(x + dx * l)), 255, 2)

    io.imsave('text.png', im)
    io.imsave('text-line.png', res)
Exemple #16
0
def test_fixed_reference():
    img = data.text()
    r = np.linspace(136, 50, 100)
    c = np.linspace(5, 424, 100)
    init = np.array([r, c]).T
    snake = active_contour(gaussian(img, 1),
                           init,
                           boundary_condition='fixed',
                           alpha=0.1,
                           beta=1.0,
                           w_line=-5,
                           w_edge=0,
                           gamma=0.1,
                           coordinates='rc')
    refr = [136, 135, 134, 133, 132, 131, 129, 128, 127, 125]
    refc = [5, 9, 13, 17, 21, 25, 30, 34, 38, 42]
    assert_equal(np.array(snake[:10, 0], dtype=np.int32), refr)
    assert_equal(np.array(snake[:10, 1], dtype=np.int32), refc)
Exemple #17
0
def test_free_reference():
    img = data.text()
    r = np.linspace(70, 40, 100)
    c = np.linspace(5, 424, 100)
    init = np.array([r, c]).T
    snake = active_contour(gaussian(img, 3),
                           init,
                           boundary_condition='free',
                           alpha=0.1,
                           beta=1.0,
                           w_line=-5,
                           w_edge=0,
                           gamma=0.1,
                           coordinates='rc')
    refr = [76, 76, 75, 74, 73, 72, 71, 70, 69, 69]
    refc = [10, 13, 16, 19, 23, 26, 29, 32, 36, 39]
    assert_equal(np.array(snake[:10, 0], dtype=np.int32), refr)
    assert_equal(np.array(snake[:10, 1], dtype=np.int32), refc)
Exemple #18
0
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)
        imageio.imwrite(str(method_path) + '_out.png', output)

        return self

elements = {
    'disk(5)': morphology.disk(5),
}
defaults = {
    'disk': morphology.disk(5),
    'image_name': 'text_inverted',
    'geometry': (0, 0, 90, 160), # row, col, rows, columns
}

# Alias some image names
data.blank = lambda: numpy.zeros(geo[2:4])
data.text_inverted = lambda: util.invert(data.text())
data.text_bw = lambda: data.bw_text()
data.text_bw_inverted = lambda: util.invert(data.bw_text())

with open('_data/categories.yaml') as stream:
    try:
        categories = yaml.safe_load(stream)
    except yaml.YAMLError as exc:
        print(exc)

def my_import (components):
    the_module = __import__('.'.join(components))
    for comp in components[1:]:
        the_module = getattr(the_module, comp)
    return the_module
Exemple #20
0
# 线性拉伸对比度的例子
# http://scikit-image.org/docs/dev/user_guide/transforming_image_data.html#contrast-and-exposure
#
# Jianjiang Feng
# 2018.7.8

from skimage import data
from skimage import exposure
import matplotlib.pyplot as plt
import numpy as np

I = data.text()
#I = data.moon() # moon的极值是0和255
print('I: Min %d, Max %d' % (I.min(), I.max()))

I2 = exposure.rescale_intensity(I)
print('I2: Min %d, Max %d' % (I2.min(), I2.max()))

v_min, v_max = np.percentile(I, (0.2, 99.8))
print('I: PMin %d, PMax %d' % (v_min, v_max))

I3 = exposure.rescale_intensity(I, in_range=(v_min, v_max))
print('I3: Min %d, Max %d' % (I3.min(), I3.max()))

plt.figure(1)
plt.subplot(1, 3, 1)
plt.imshow(I, cmap='gray')
plt.subplot(1, 3, 2)
plt.imshow(I2, cmap='gray')
plt.subplot(1, 3, 3)
plt.imshow(I3, cmap='gray')
    fig = plt.figure(figsize=(7, 7))
    ax = fig.add_subplot(111)
    plt.gray()
    ax.imshow(img)
    ax.plot(init[:, 0], init[:, 1], '--r', lw=3)
    ax.plot(snake[:, 0], snake[:, 1], '-b', lw=3)
    ax.set_xticks([]), ax.set_yticks([])
    ax.axis([0, img.shape[1], img.shape[0], 0])

######################################################################
# Here we initialize a straight line between two points, `(5, 136)` and
# `(424, 50)`, and require that the spline has its end points there by giving
# the boundary condition `bc='fixed'`. We furthermore make the algorithm
# search for dark lines by giving a negative `w_line` value.

img = data.text()

x = np.linspace(5, 424, 100)
y = np.linspace(136, 50, 100)
init = np.array([x, y]).T

if new_scipy:
    snake = active_contour(gaussian(img, 1), init, bc='fixed',
                           alpha=0.1, beta=1.0, w_line=-5, w_edge=0, gamma=0.1)

    fig = plt.figure(figsize=(9, 5))
    ax = fig.add_subplot(111)
    plt.gray()
    ax.imshow(img)
    ax.plot(init[:, 0], init[:, 1], '--r', lw=3)
    ax.plot(snake[:, 0], snake[:, 1], '-b', lw=3)
Exemple #22
0
def test_triangle_uint_images():
    text = cp.array(data.text())
    assert threshold_triangle(cp.invert(text)) == 151
    assert threshold_triangle(text) == 104
    assert threshold_triangle(coinsd) == 80
    assert threshold_triangle(cp.invert(coinsd)) == 175
"""
This example illustrates the use of the horizontal Sobel filter, to compute
horizontal gradients.
"""

from skimage import data, filter
import matplotlib.pyplot as plt

text = data.text()
hsobel_text = filter.hsobel(text)

plt.figure(figsize=(12, 3))

plt.subplot(121)
plt.imshow(text, cmap='gray', interpolation='nearest')
plt.axis('off')
plt.subplot(122)
plt.imshow(hsobel_text, cmap='jet', interpolation='nearest')
plt.axis('off')
plt.tight_layout()
plt.show()
from skimage import data, transform

import numpy as np
import matplotlib.pyplot as plt


image = data.text()

plt.imshow(image, cmap=plt.cm.gray)

target = np.array(plt.ginput(4))
source = np.array([(0, 0), (0, 50), (300, 50), (300, 0)])

plt.close()

pt = transform.ProjectiveTransform()
pt.estimate(source, target)

warped = transform.warp(image, pt, output_shape=(50, 300))


f, (ax0, ax1) = plt.subplots(1, 2)
ax0.imshow(image, cmap=plt.cm.gray)
ax1.imshow(warped, cmap=plt.cm.gray)
plt.show()
# Фильтер Собеля для детектирования горизонтальных линий
import numpy as np
from skimage import morphology
from skimage import exposure
from matplotlib import pyplot as plt
from skimage import data
from skimage import filters

text = data.text()
hsobel_text = filters.sobel_h(text)

plt.figure()
plt.imshow(text, cmap='gray')
plt.show()

plt.figure()
plt.imshow(hsobel_text, cmap='gray')
plt.show()

# Нелокальные фильтры используют все изображение или
# его часть для изменения интенсивности в одном пикселе.
# В примере показано изменение контрастности в областях.

camera = data.camera()
camera_equalized = exposure.equalize_hist(camera)  # выравнивание гистограммы
plt.figure()
plt.imshow(camera, cmap='gray')
plt.show()

plt.figure()
plt.imshow(camera_equalized, cmap='gray')
Exemple #26
0
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()
from matplotlib import pyplot as plt

from skimage import data, img_as_float
from skimage.feature import harris


def plot_harris_points(image, filtered_coords):
    """ plots corners found in image"""

    plt.imshow(image)
    y, x = np.transpose(filtered_coords)
    plt.plot(x, y, 'b.')
    plt.axis('off')

# display results
plt.figure(figsize=(8, 3))
im_lena = img_as_float(data.lena())
im_text = img_as_float(data.text())

filtered_coords = harris(im_lena, min_distance=4)

plt.axes([0, 0, 0.3, 0.95])
plot_harris_points(im_lena, filtered_coords)

filtered_coords = harris(im_text, min_distance=4)

plt.axes([0.2, 0, 0.77, 1])
plot_harris_points(im_text, filtered_coords)

plt.show()
Exemple #28
0
def normalize_img(img):
    img /= np.max(img)
    img = np.ceil(img * 255)
    return img


def exponential_trans(img):
    for row in range(img.shape[0]):
        for column in range(img.shape[1]):
            img[row][column] = math.exp(img[row][column])

    return img


image_teste = data.text().astype(float)
exp_image = exponential_trans(image_teste.copy())
plt.imshow(exp_image, cmap='gray')


def potential_trans(img, gamma):
    for row in range(img.shape[0]):
        for column in range(img.shape[1]):
            img[row][column] = img[row][column]**gamma

    return normalize_img(img)


image2 = data.coins()
pot_image = potential_trans(image2.copy(), 0.2)
plt.imshow(pot_image, cmap='gray')
==================================

Demo of a CollectionViewer for viewing collections of images with the
`autolevel` rank filter connected as a plugin.

"""
from skimage import data
from skimage.filters import rank
from skimage.morphology import disk

from skimage.viewer import CollectionViewer
from skimage.viewer.widgets import Slider
from skimage.viewer.plugins.base import Plugin


# Wrap autolevel function to make the disk size a filter argument.
def autolevel(image, disk_size):
    return rank.autolevel(image, disk(disk_size))


img_collection = [data.camera(), data.coins(), data.text()]

plugin = Plugin(image_filter=autolevel)
plugin += Slider('disk_size', 2, 8, value_type='int')
plugin.name = "Autolevel"

viewer = CollectionViewer(img_collection)
viewer += plugin

viewer.show()
Exemple #30
0
#Program to get default images in scikit-image

from skimage import data
from skimage import io

#Get the camera image
img_camera = data.camera()

#Get an image with handwritten text
img_text = data.text()

io.show(img_text)
'''
 File "skimage_data.py", line 12, in <module>
    io.show(img_text)
TypeError: show() takes 0 positional arguments but 1 was given
'''
Exemple #31
0
from skimage import data, img_as_float
from skimage.feature import harris


def plot_harris_points(image, filtered_coords):
    """ plots corners found in image"""

    plt.imshow(image)
    y, x = np.transpose(filtered_coords)
    plt.plot(x, y, 'b.')
    plt.axis('off')


# display results
plt.figure(figsize=(8, 3))
im_lena = img_as_float(data.lena())
im_text = img_as_float(data.text())

filtered_coords = harris(im_lena, min_distance=4)

plt.axes([0, 0, 0.3, 0.95])
plot_harris_points(im_lena, filtered_coords)

filtered_coords = harris(im_text, min_distance=4)

plt.axes([0.2, 0, 0.77, 1])
plot_harris_points(im_text, filtered_coords)

plt.show()
Exemple #32
0
        canny_kwargs = dict([(k, kwargs.pop(k)) for k in canny_keys])
        hough_kwargs = kwargs
        edges = canny(image, **canny_kwargs)
        lines = probabilistic_hough(edges, **hough_kwargs)
        self._lines = lines
        return edges

    def display_filtered_image(self, edges):
        self.overlay = edges
        if hasattr(self, '_hough_lines'):
            self.image_viewer.ax.collections.remove(self._hough_lines)
        self._hough_lines = mcoll.LineCollection(self._lines, colors='r')
        self.image_viewer.ax.add_collection(self._hough_lines)
        self.image_viewer.redraw()

image = data.text()

# Note: ImageViewer must be called before Plugin b/c it starts the event loop.
viewer = ImageViewer(image)
# You can create a UI for a filter just by passing a filter function...
plugin = HoughPlugin()
plugin += Slider('sigma', 0, 5, value=1, update_on='release')
plugin += Slider('low threshold', 0, 255, update_on='release')
plugin += Slider('high threshold', 0, 255, update_on='release')
plugin += Slider('threshold', 0, 255, update_on='release')
plugin += Slider('line length', 0, 100, update_on='release')
plugin += Slider('line gap', 0, 20, update_on='release')
# Finally, attach the plugin to the image viewer.
viewer += plugin
viewer.show()
@author: jsaavedr
Adaptive Threhsolding
'''

import matplotlib.pyplot as plt
import skimage.filters as filters
import skimage.data as images
import numpy as np
import utils
import pai_io

if __name__ == '__main__' :
    
    #filename = '../images/gray/car_1.png'
    #image=pai_io.imread(filename, as_gray = True)
    image = images.text()    
    print(image.shape)    
    #th_otsu = basis.get_threshold_otsu(image)
    th_adaptive = filters.threshold_local(image, block_size = 21, offset = 15)
    th_niblack = filters.threshold_niblack(image, window_size = 21, k=0.2)
    th_sauvola = filters.threshold_sauvola(image, window_size = 21, k=0.2)
    #bin_image_otsu = basis.threshold(image, th_otsu)
    bin_image_adaptive = np.uint8(image > th_adaptive)
    bin_image_niblack = np.uint8(image > th_niblack)
    bin_image_sauvola = np.uint8(image > th_sauvola)
    fig, xs = plt.subplots(1,3)
    for i in range(3):
        xs[i].set_axis_off()
    xs[0].imshow(bin_image_adaptive*255, cmap = 'gray', vmin = 0, vmax = 255)
    xs[0].set_title('Local')
    xs[1].imshow(bin_image_niblack*255, cmap = 'gray', vmin = 0, vmax = 255)
Exemple #34
0
def test_triangle_uint_images():
    assert (threshold_triangle(np.invert(data.text())) == 151)
    assert (threshold_triangle(data.text()) == 104)
    assert (threshold_triangle(data.coins()) == 80)
    assert (threshold_triangle(np.invert(data.coins())) == 175)
==================================

Demo of a CollectionViewer for viewing collections of images with the
`autolevel` rank filter connected as a plugin.

"""
from skimage import data
from skimage.filter import rank
from skimage.morphology import disk

from skimage.viewer import CollectionViewer
from skimage.viewer.widgets import Slider
from skimage.viewer.plugins.base import Plugin


# Wrap autolevel function to make the disk size a filter argument.
def autolevel(image, disk_size):
    return rank.autolevel(image, disk(disk_size))


img_collection = [data.camera(), data.coins(), data.text()]

plugin = Plugin(image_filter=autolevel)
plugin += Slider("disk_size", 2, 8, value_type="int")
plugin.name = "Autolevel"

viewer = CollectionViewer(img_collection)
viewer += plugin

viewer.show()
def test_triangle_uint_images():
    assert(threshold_triangle(np.invert(data.text())) == 151)
    assert(threshold_triangle(data.text()) == 104)
    assert(threshold_triangle(data.coins()) == 80)
    assert(threshold_triangle(np.invert(data.coins())) == 175)
Created on Mon Aug 27 17:00:10 2018
Last Updated on Tue Aug 28 16:01:10 2018

@author: bhavani
"""

from skimage import io
img = io.imread("image.png")
io.imshow("image.png")
#io.show()
""" Writing or Saving an Image"""
io.imsave("new_image.png", img)
""" Data Module provides some standard test images """
from skimage import data
io.imshow(data.camera())
io.imshow(data.text())
io.show()
"""COlor module Contains methods to convert image from One to another color"""

from skimage import color
img = io.imread("BusinessCard.JPEG")
io.imshow("BusinessCard.JPEG")
gray = color.rgb2gray(img)
io.imshow(gray)
io.show()
io.imsave("Gray_BusinessCard.png", gray)

#Convert RGB to HSV
img = data.astronaut()
img_hsv = color.rgb2hsv(img)
io.imshow(img_hsv)
Exemple #38
0
def test_text():
    """ Test that "text" image can be loaded. """
    data.text()
def test_triangle_images():
    assert threshold_triangle(np.invert(data.text())) == 151
    assert threshold_triangle(data.text()) == 104
    assert threshold_triangle(data.coins()) == 80
    assert threshold_triangle(np.invert(data.coins())) == 175