Exemplo n.º 1
0
def test_i2v():
    """Loads the i2v network and applies it to a test image.
    """
    with tf.Session() as sess:
        net = get_i2v_model()
        tf.import_graph_def(net['graph_def'], name='i2v')
        g = tf.get_default_graph()
        names = [op.name for op in g.get_operations()]
        x = g.get_tensor_by_name(names[0] + ':0')
        softmax = g.get_tensor_by_name(names[-3] + ':0')

        from skimage import data
        img = preprocess(data.coffee())[np.newaxis]
        res = np.squeeze(softmax.eval(feed_dict={x: img}))
        print([(res[idx], net['labels'][idx])
               for idx in res.argsort()[-5:][::-1]])

        """Let's visualize the network's gradient activation
        when backpropagated to the original input image.  This
        is effectively telling us which pixels contribute to the
        predicted class or given neuron"""
        pools = [name for name in names if 'pool' in name.split('/')[-1]]
        fig, axs = plt.subplots(1, len(pools))
        for pool_i, poolname in enumerate(pools):
            pool = g.get_tensor_by_name(poolname + ':0')
            pool.get_shape()
            neuron = tf.reduce_max(pool, 1)
            saliency = tf.gradients(neuron, x)
            neuron_idx = tf.arg_max(pool, 1)
            this_res = sess.run([saliency[0], neuron_idx],
                                feed_dict={x: img})

            grad = this_res[0][0] / np.max(np.abs(this_res[0]))
            axs[pool_i].imshow((grad * 128 + 128).astype(np.uint8))
            axs[pool_i].set_title(poolname)
def test_random_enhance_any_color():
    image = data.coffee()

    for i in xrange(10):
        enhanced = random_enhance_color(image,_seed=42)
        assert (image != enhanced).any()
        assert (image.shape == enhanced.shape)
        assert (image.sum() < enhanced.sum())
Exemplo n.º 3
0
def color_transformation():
    # 彩色变换
    image=data.coffee()
    brighter=np.uint8(image*0.5+255*0.5)
    darker=np.uint8(image*0.5)
    io.imshow(brighter)
    io.show()
    io.imshow(darker)
    io.show()
Exemplo n.º 4
0
	def getImage(self,params):
		sigma = float(params['sigma'])
		r = float(params['red'])
		g = float(params['green'])
		b = float(params['blue'])
		image = data.coffee()
		new_image = filter.gaussian_filter(image, sigma=sigma, multichannel=True)
		new_image[:,:,0] = r*new_image[:,:,0]
		new_image[:,:,1] = g*new_image[:,:,1]
		new_image[:,:,2] = b*new_image[:,:,2]
		return new_image
def main():
    """Load image, collect pixels, cluster, create segment images, plot."""
    # load image
    img_rgb = data.coffee()
    img_rgb = misc.imresize(img_rgb, (256, 256)) / 255.0
    img = color.rgb2hsv(img_rgb)
    height, width, channels = img.shape
    print("Image shape is: ", img.shape)

    # collect pixels as tuples of (r, g, b, y, x)
    print("Collecting pixels...")
    pixels = []
    for y in range(height):
        for x in range(width):
            pixel = img[y, x, ...]
            pixels.append([pixel[0], pixel[1], pixel[2], (y / height) * 2.0, (x / width) * 2.0])
    pixels = np.array(pixels)
    print("Found %d pixels to cluster" % (len(pixels)))

    # cluster the pixels using mean shift
    print("Clustering...")
    bandwidth = estimate_bandwidth(pixels, quantile=0.05, n_samples=500)
    clusterer = MeanShift(bandwidth=bandwidth, bin_seeding=True)
    labels = clusterer.fit_predict(pixels)

    # process labels generated during clustering
    labels_unique = set(labels)
    labels_counts = [(lu, len([l for l in labels if l == lu])) for lu in labels_unique]
    labels_unique = sorted(list(labels_unique), key=lambda l: labels_counts[l], reverse=True)
    nb_clusters = len(labels_unique)
    print("Found %d clusters" % (nb_clusters))
    print(labels.shape)

    print("Creating images of segments...")
    img_segments = [np.copy(img_rgb) * 0.25 for label in labels_unique]

    for y in range(height):
        for x in range(width):
            pixel_idx = (y * width) + x
            label = labels[pixel_idx]
            img_segments[label][y, x, 0] = 1.0

    print("Plotting...")
    images = [img_rgb]
    titles = ["Image"]
    for i in range(min(8, nb_clusters)):
        images.append(img_segments[i])
        titles.append("Segment %d" % (i))

    plot_images(images, titles)
Exemplo n.º 6
0
def test_write_rgb(tmpdir_factory):
    img = coffee()
    filename = str(tmpdir_factory.mktemp("write").join("rgb_img.tif"))
    with Tiff(filename, "w") as handle:
        handle.write(img, method="tile")
    with Tiff(filename) as handle:
        data = handle[:]
        assert np.all(img == data[:, :, :3])

    with Tiff(filename, "w") as handle:
        handle.write(img, method="scanline")
    with Tiff(filename) as handle:
        data = handle[:]
        assert np.all(img == data[:, :, :3])
Exemplo n.º 7
0
def run(dict,canload=0):
    import os.path
    if 'fname' in dict:
        filename=dict['fname']
    else:
        print("No filename given")
        exit(1)
    print("\n",filename,"============================================","\n")
    plt.ion()
    G=hamiltonian.GaussGreen(dict['ell'],0)
    no_steps=dict['no_steps']
    if isinstance(no_steps, list):
        ODE=diffeo.MultiShoot(G,1)
    else:
        ODE=diffeo.Shoot(G)  # use single shooting
    #
    ODE.set_no_steps(dict['no_steps'])
    ODE.set_landmarks(dict['landmarks_n'])
    ODE.solve()
    # plot warp
    plot_setup()
    plt.axis('equal')
    ODE.plot_warp()
    plt.savefig(filename+'warp.pdf',bbox_inches='tight')
    #
    # load test image
    #image = data.checkerboard()
    image = data.coffee()
    #
    # apply warp to image
    new_image=ODE.warp(image)
    # plotting and save to png
    plot_setup()
    plt.close()
    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')
    mpl.image.imsave('orig_image.png',image,cmap=plt.cm.gray)
    ax0.axis('off')
    #
    ax1.imshow(new_image, cmap=plt.cm.gray, interpolation='none')
    mpl.image.imsave('new_image.png',new_image,cmap=plt.cm.gray)
    ax1.axis('off')
    plt.show()
    print("finished.")
Exemplo n.º 8
0
def test_minsize():
    # single-channel:
    img = data.coins()[20:168, 0:128]
    for min_size in np.arange(10, 100, 10):
        segments = felzenszwalb(img, min_size=min_size, sigma=3)
        counts = np.bincount(segments.ravel())
        # actually want to test greater or equal.
        assert_greater(counts.min() + 1, min_size)
    # multi-channel:
    coffee = data.coffee()[::4, ::4]
    for min_size in np.arange(10, 100, 10):
        segments = felzenszwalb(coffee, min_size=min_size, sigma=3)
        counts = np.bincount(segments.ravel())
        # actually want to test greater or equal.
        assert_greater(counts.min() + 1, min_size)
Exemplo n.º 9
0
def test_minsize():
    # single-channel:
    img = data.coins()[20:168,0:128]
    for min_size in np.arange(10, 100, 10):
        segments = felzenszwalb(img, min_size=min_size, sigma=3)
        counts = np.bincount(segments.ravel())
        # actually want to test greater or equal.
        assert_greater(counts.min() + 1, min_size)
    # multi-channel:
    coffee = data.coffee()[::4, ::4]
    for min_size in np.arange(10, 100, 10):
        segments = felzenszwalb(coffee, min_size=min_size, sigma=3)
        counts = np.bincount(segments.ravel())
        # actually want to test greater or equal.
        # the construction doesn't guarantee min_size is respected
        # after intersecting the sementations for the colors
        assert_greater(np.mean(counts) + 1, min_size)
Exemplo n.º 10
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)

        with expected_warnings(['Possible precision loss']):
            image = img_as_ubyte(transform.downscale_local_mean(
                color.rgb2gray(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
Exemplo n.º 11
0
def test_coffee():
    """ Test that "coffee" image can be loaded. """
    data.coffee()
References
----------
.. [1] Xie, Yonghong, and Qiang Ji. "A new efficient ellipse detection
       method." Pattern Recognition, 2002. Proceedings. 16th International
       Conference on. Vol. 2. IEEE, 2002
"""

import matplotlib.pyplot as plt

from skimage import data, filter, color
from skimage.transform import hough_ellipse
from skimage.draw import ellipse_perimeter

# Load picture, convert to grayscale and detect edges
image_rgb = data.coffee()[0:220, 160:420]
image_gray = color.rgb2gray(image_rgb)
edges = filter.canny(image_gray,
                     sigma=2.0,
                     low_threshold=0.55,
                     high_threshold=0.8)

# Perform a Hough Transform
# The accuracy corresponds to the bin size of a major axis.
# The value is chosen in order to get a single high accumulator.
# The threshold eliminates low accumulators
result = hough_ellipse(edges,
                       accuracy=20,
                       threshold=250,
                       min_size=100,
                       max_size=120)
Exemplo n.º 13
0
from skimage import data, color, img_as_ubyte
import cv2
image_rgb = data.coffee()
cv2.imshow('dimg', image_rgb)
cv2.waitKey(0)
Exemplo n.º 14
0
tidy.shape

np.savetxt('/tmp/img.csv', tidy, delimiter=',', fmt='%d')

### SLIC
import matplotlib.pyplot as plt
import numpy as np

from skimage import data
from skimage.segmentation import slic
from skimage.segmentation import mark_boundaries
from skimage.util import img_as_float
from skimage.viewer import ImageViewer
from skimage.color import label2rgb

viewer = ImageViewer(data.coffee())
viewer.show()

img = img_as_float(data.coffee()[::2, ::2])

from scipy import misc
img = misc.imread('/home/abergman/walking/img/output-00125.png')

n_segs = np.prod(np.array(img.shape)[0:2] / 10)

import matplotlib as mpl
mpl.rcParams['image.interpolation'] = 'nearest'

segments = slic(img, n_segments=n_segs, compactness=5, sigma=2)
print "SLIC # of segments: %d " % len(np.unique(segments))
overlay = label2rgb(segments, image=img)
Exemplo n.º 15
0
"""
Created on Sat Feb 17 20:07:17 2018

@author: raja
"""

import numpy as np
from skimage import io, color
from skimage import data
from skimage.viewer import ImageViewer
from matplotlib import pyplot as plt

a = data.camera()
io.imshow(a)

b = data.coffee()
io.imshow(b)

c = data.coins()
io.imshow(c)

d = io.imread('coloredChips.png')
dd = plt.imshow(d)

r, c, dim = np.shape(d)
new = np.zeros((r, c))

for i in range(0, r):
    for j in range(0, c):
        if ((d[i, j, 0] > 200) and (d[i, j, 1] < 48) and (d[i, j, 2] < 80)):
            new[i, j] = (5 * d[i, j, 0] + d[i, j, 1] + d[i, j, 2]) / 7
Exemplo n.º 16
0
# Import the necessary modules
from skimage import data, exposure

# Load the image
original_image = data.coffee()

# Apply the adaptive equalization on the original image
adapthist_eq_image = exposure.equalize_adapthist(original_image,
                                                 clip_limit=0.03)

# Compare the original image to the equalized
show_image(original_image)
show_image(adapthist_eq_image, '#ImageProcessingDatacamp')
Exemplo n.º 17
0
def test_random_enhance_color():
    image = data.coffee()
    enhanced = random_enhance_color(image,_seed=42, _color_id=0)
    assert (image[...,0] != enhanced[...,0]).any()
    assert (image.shape == enhanced.shape)
    assert (image.sum() < enhanced.sum())
Exemplo n.º 18
0
def exposureUse():
    img = data.coffee()
    # 对比度调整
    imgshow(img)
    imgshow(exposure.adjust_gamma(img, 0.2))
    imgshow(exposure.adjust_gamma(img, 2))
Exemplo n.º 19
0
#!/usr/bin/env python

"""Get superpixels of an image."""

from skimage.segmentation import slic, quickshift  # , felzenszwalb
from skimage.segmentation import mark_boundaries
from skimage.data import coffee

import matplotlib.pyplot as plt

import Image
import numpy

img = coffee()
drip = ("/home/moose/GitHub/MediSeg/DATA/Segmentation_Rigid_Training/"
        "Training/OP4/Raw/")


for i in range(10, 40):
    im = Image.open(drip + "img_%i_raw.png" % i)
    img = numpy.array(im)

    w, h, d = original_shape = tuple(img.shape)

    segments = slic(img,
                    n_segments=50,
                    compactness=20)
    b1 = mark_boundaries(img, segments, color=(1, 1, 0))
    segments = quickshift(img, ratio=0.5, max_dist=10, sigma=0.0)
    b2 = mark_boundaries(img, segments, color=(1, 1, 0))
    segments = quickshift(img, ratio=0.5, max_dist=10, sigma=0.1)
Exemplo n.º 20
0
    astroT = torch.tensor(astro, dtype=torch.float32)
    astro_grayT = torch.tensor(astro_gray, dtype=torch.float32)
    checkerboard = img_as_float(data.checkerboard())
    checkerboard_gray = color.gray2rgb(checkerboard)
    astcheckerboardroT = torch.tensor(checkerboard, dtype=torch.float32)
    checkerboard_grayT = torch.tensor(checkerboard_gray, dtype=torch.float32)

    #test the all test cases from skimage package
    test_denoise_tv_chambolle_2d()
    test_denoise_tv_chambolle_multichannel()
    test_denoise_tv_chambolle_float_result_range()
    test_denoise_tv_chambolle_3d()
    test_denoise_tv_chambolle_1d()
    test_denoise_tv_chambolle_4d()
    test_denoise_tv_chambolle_weighting()

    coffee = img_as_float(data.coffee())
    coffeeT = torch.tensor(coffee)
    #add noise to the original image to test the denoising effect
    noise = torch.randn(coffeeT.size(), dtype=coffeeT.dtype) * 0.15
    fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(8, 8))
    ax1.imshow(coffee + noise.numpy())
    ax1.set_title('Original Image')
    #result of torch
    ax2.imshow(denoise_tv_chambolle_torch(coffeeT + noise))
    ax2.set_title('Denoised(torch)')
    #result of numpy
    ax3.imshow(restoration.denoise_tv_chambolle(coffee + noise.numpy()))
    ax3.set_title('Denoised(numpy)')
    plt.show()
Exemplo n.º 21
0
# -*- coding: utf-8 -*-
"""
Created on Sun Sep  9 13:38:03 2018

@author: ldz
"""
from skimage import io, data, data_dir, color, transform, exposure
from skimage import filters, feature, draw, morphology
from skimage.morphology import disk
from skimage.filters import rank
import skimage.morphology as sm
import matplotlib.pyplot as plt
from copy import deepcopy
import numpy as np
import skimage as ski
image_rgb = data.coffee()[0:220, 160:420]  #裁剪原图像,不然速度非常慢
image_gray = color.rgb2gray(image_rgb)
edges = feature.canny(image_gray,
                      sigma=2.0,
                      low_threshold=0.55,
                      high_threshold=0.8)
#执行椭圆变换
result = transform.hough_ellipse(edges,
                                 accuracy=20,
                                 threshold=250,
                                 min_size=100,
                                 max_size=120)
result.sort(order='accumulator')  #根据累加器排序
#估计椭圆参数
best = list(result[-1])  #排完序后取最后一个
yc, xc, a, b = [int(round(x)) for x in best[1:5]]
Exemplo n.º 22
0
#

import skimage.data as skd
import numpy as np
import matplotlib.pyplot as plt

from recon.interfaces import Segmentation


def rgb2gray(rgb):
    r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2]
    gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
    return gray


gt = rgb2gray(skd.coffee())[:, 80:481]
gt = gt/np.max(gt)
gt = gt/np.max(gt)

classes = [0, 50/255, 120/255, 190/255, 220/255]

segmentation = Segmentation(gt.shape, classes=classes, lam=5, tau='calc')
result, _ = segmentation.solve(gt, max_iter=4000)

f = plt.figure(figsize=(8, 4))
f.add_subplot(1, 2, 1)
plt.axis('off')
plt.imshow(gt)
plt.title("GT")
f.add_subplot(1, 2, 2)
plt.imshow(result)
Exemplo n.º 23
0
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import IPython.display as ipyd
from libs import gif, nb_utils

sess = tf.InteractiveSession()

from libs import inception

net = inception.get_inception_model()
tf.import_graph_def(net['graph_def'], name='inception')
from skimage.data import coffee

og = coffee()
img = inception.preprocess(og)
img_4d = img[np.newaxis]

g = tf.get_default_graph()
names = [op.name for op in g.get_operations()]

input_name = names[0] + ':0'
x = g.get_tensor_by_name(input_name)


def compute_gradient(input_placeholder, img, layer_name, neuron_i):
    feature = g.get_tensor_by_name(layer_name)
    gradient = tf.gradients(tf.reduce_mean(feature[:, :, :, neuron_i]), x)
    res = sess.run(gradient, feed_dict={input_placeholder: img})[0]
    return res
Exemplo n.º 24
0
from skimage import data
from skimage.color import rgb2gray
from skimage import img_as_ubyte,img_as_float
gray_images = {
        "cat":rgb2gray(img_as_float(data.chelsea())),
        "astro":rgb2gray(img_as_float(data.astronaut())),
        "camera":data.camera(),
        "coin": data.coins(),
        "clock":data.clock(),
        "blobs":data.binary_blobs(),
        "coffee":rgb2gray(img_as_float(data.coffee()))
}
from numpy.linalg import svd
def compress_svd(image,k):
U,s,V = svd(image,full_matrices=False)
    reconst_matrix = np.dot(U[:,:k],np.dot(np.diag(s[:k]),V[:k,:]))
   
    return reconst_matrix,s
    
def compress_show_gray_images(img_name,k):
    
    image=gray_images[img_name]
    original_shape = image.shape
    reconst_img,s = compress_svd(image,k)
    fig,axes = plt.subplots(1,2,figsize=(8,5))
    axes[0].plot(s)
    compression_ratio =100.0* (k*(original_shape[0] + original_shape[1])+k)/(original_shape[0]*original_shape[1])
    axes[1].set_title("compression ratio={:.2f}".format(compression_ratio)+"%")
    axes[1].imshow(reconst_img,cmap='gray')
    axes[1].axis('off')
    fig.tight_layout()
Exemplo n.º 25
0
image can then be effectively performed by a mere thresholding of the HSV
channels.

.. [1] https://en.wikipedia.org/wiki/HSL_and_HSV

"""

##############################################################################
# We first load the RGB image and extract the Hue and Value channels:

import matplotlib.pyplot as plt

from skimage import data
from skimage.color import rgb2hsv

rgb_img = data.coffee()
hsv_img = rgb2hsv(rgb_img)
hue_img = hsv_img[:, :, 0]
value_img = hsv_img[:, :, 2]

fig, (ax0, ax1, ax2) = plt.subplots(ncols=3, figsize=(8, 2))

ax0.imshow(rgb_img)
ax0.set_title("RGB image")
ax0.axis('off')
ax1.imshow(hue_img, cmap='hsv')
ax1.set_title("Hue channel")
ax1.axis('off')
ax2.imshow(value_img)
ax2.set_title("Value channel")
ax2.axis('off')
References
----------
.. [1] Xie, Yonghong, and Qiang Ji. "A new efficient ellipse detection
       method." Pattern Recognition, 2002. Proceedings. 16th International
       Conference on. Vol. 2. IEEE, 2002
"""

import matplotlib.pyplot as plt

from skimage import data, filter, color
from skimage.transform import hough_ellipse
from skimage.draw import ellipse_perimeter

# Load picture, convert to grayscale and detect edges
image_rgb = data.coffee()[0:220, 160:420]
image_gray = color.rgb2gray(image_rgb)
edges = filter.canny(image_gray, sigma=2.0,
                     low_threshold=0.55, high_threshold=0.8)

# Perform a Hough Transform
# The accuracy corresponds to the bin size of a major axis.
# The value is chosen in order to get a single high accumulator.
# The threshold eliminates low accumulators
result = hough_ellipse(edges, accuracy=20, threshold=250,
                       min_size=100, max_size=120)
result.sort(order='accumulator')

# Estimated parameters for the ellipse
best = result[-1]
yc = int(best[1])
Exemplo n.º 27
0
# skimage but many developers will have it.
try:
    import skimage.data as data

    TEST_IMAGES.update({
        "Astronaut": {
            "shape": (512, 512),
            "factory": lambda: data.astronaut(),
        },
        "Chelsea": {
            "shape": (300, 451),
            "factory": lambda: data.chelsea(),
        },
        "Coffee": {
            "shape": (400, 600),
            "factory": lambda: data.coffee()
        },
    })
except ImportError:
    pass  # These images won't be listed.


class QtSetShape(QGroupBox):
    """Controls to set the shape of an image."""
    def __init__(self):
        super().__init__("Dimensions")

        layout = QVBoxLayout()
        self.height = QtLabeledSpinBox("Height", IMAGE_SHAPE_DEFAULT[0],
                                       IMAGE_SHAPE_RANGE)
        layout.addLayout(self.height)
Exemplo n.º 28
0
# 합성곱의 이해 : filter, stride, padding
import matplotlib.pyplot as plt
from scipy.ndimage import correlate
import numpy as np
from skimage import data
from skimage.color import rgb2gray
from skimage.transform import resize

# 초기 컵 이미지(흑백)
im = rgb2gray(data.coffee())
im = resize(im, (64, 64))
print(im.shape)

plt.axis('off')
plt.imshow(im, cmap='gray')
plt.show()

# horizontal edge filter : 합성곱 필터(3*3) 적용--------
filter1 = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]])

new_image = np.zeros(im.shape)
im_pad = np.pad(im, 1, 'constant')

for i in range(im.shape[0]):
    for j in range(im.shape[1]):
        try:
            new_image[i,j] = im_pad[i-1,j-1] * filter1[0,0] + im_pad[i-1,j] * filter1[0,1] + \
            im_pad[i-1,j+1] * filter1[0,2] + \
            im_pad[i,j-1] * filter1[1,0] + \
            im_pad[i,j] * filter1[1,1] + \
            im_pad[i,j+1] * filter1[1,2] +\
from skimage.color import rgb2gray, gray2rgb
from skimage.segmentation import mark_boundaries
import time
import matplotlib.image as mpimg
exec(open('/Users/Salim_Andre/Desktop/IMA/PRAT/code/pd_segmentation_0.py').read())
exec(open('/Users/Salim_Andre/Desktop/IMA/PRAT/code/tree.py').read())

### DATASET

PATH_img = '/Users/Salim_Andre/Desktop/IMA/PRAT/' # path to my own images

swans=mpimg.imread(PATH_img+'swans.jpg');
baby=mpimg.imread(PATH_img+'baby.jpg'); 
	
img_set = [data.astronaut(), data.camera(), data.coins(), data.checkerboard(), data.chelsea(), \
	data.coffee(), data.clock(), data.hubble_deep_field(), data.horse(), data.immunohistochemistry(), \
	data.moon(), data.page(), data.rocket(), swans, baby]
	
### IMAGE

I=img_as_float(img_set[0]);

###	PARAMETERS FOR 0-HOMOLOGY GROUPS

mode='customized';
n_superpixels=10000;
RV_epsilon=30;
gauss_sigma=0.5;
list_events=[800];
n_pxl_min_ = 30;
density_excl=0.0;
Exemplo n.º 30
0
import matplotlib.pyplot as plt

from skimage import data
from skimage import exposure
from skimage import io

reference = data.coffee()
image = io.imread('atlantis.png')


fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3, figsize=(8, 3),
                                    sharex=True, sharey=True)
for aa in (ax1, ax2, ax3):
    aa.set_axis_off()

ax1.imshow(image)
ax1.set_title('Source')

fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(5, 8))


for c, c_color in enumerate(('red', 'green', 'blue')):
    img_hist, bins = exposure.histogram(image[..., c])
    axes[c].plot(bins, img_hist / img_hist.max())
    img_cdf, bins = exposure.cumulative_distribution(image[..., c])
    axes[c].plot(bins, img_cdf)
    axes[c].set_ylabel(c_color)

axes[0].set_title('Source')

plt.tight_layout()
from skimage import data, transform, color, io

A = cp.arange(9).reshape(3, 3).astype('f')  # cupy上で3*3の行列を生成
B = cp.arange(9).reshape(3, 3).astype('f')  # cupy上で3*3の行列を生成
print('A = \n', A)
print('B = \n', B)

C = A + B  # 行列の和
print('和:A + B = \n', C)

D = cp.dot(A, B)  # 行列の積
print('積:A・B = \n', D)

# 画像のロード
np_img = data.coffee()  # コーヒーカップ画像をロード

np_img = transform.resize(np_img, (4096, 4096))  # 4096*4096にリサイズ
np_img = color.rgb2gray(np_img)  # グレースケール化
np_img = np_img.astype('f')

io.imshow(np_img)  # 表示
io.show()

# フーリエ変換
cp_img = cp.asarray(np_img)  # numpy配列 ⇒ cupy配列に変換
cp_fimg = cp.fft.fft2(cp_img)  # 【フーリエ変換】
cp_fimg = cp.fft.fftshift(cp_fimg)  # fftshiftを使ってシフト

# パワースペクトルで表示
cp_fabs = cp.absolute(cp_fimg)  # 絶対値をとる
Exemplo n.º 32
0
# https://scikit-image.org/docs/dev/auto_examples/segmentation/plot_segmentations.html

# Felzenszwalbs's method の例
# http://cs.brown.edu/people/pfelzens/segment/

# Quickshift

# SLIC - K-Means based image segmentation

# Compact watershed segmentation of gradient images

image_file = "./Intermediate_img_400/isv01lpd_0.png"
image = io.imread(image_file)
# img = img_as_float(image)
img = img_as_float(coffee()[::2, ::2])
# img = img_as_float(moon()[::2, ::2])

segments_fz = felzenszwalb(img, scale=100, sigma=2.5, min_size=250)
segments_slic = slic(img, n_segments=250, compactness=10, sigma=1)
segments_quick = quickshift(img, kernel_size=3, max_dist=6, ratio=0.5)
gradient = sobel(rgb2gray(img))
segments_watershed = watershed(gradient, markers=250, compactness=0.001)

print("Felzenszwalb number of segments: {}".format(len(
    np.unique(segments_fz))))
print('SLIC number of segments: {}'.format(len(np.unique(segments_slic))))
print('Quickshift number of segments: {}'.format(len(
    np.unique(segments_quick))))

fig, ax = plt.subplots(2, 2, figsize=(10, 10), sharex=True, sharey=True)
Exemplo n.º 33
0
independently for each channel, as long as the number of channels is equal in
the input image and the reference.

Histogram matching can be used as a lightweight normalisation for image
processing, such as feature matching, especially in circumstances where the
images have been taken from different sources or in different conditions (i.e.
lighting).
"""

import matplotlib.pyplot as plt

from skimage import data
from skimage import exposure
from skimage.transform import match_histograms

reference = data.coffee()
image = data.chelsea()

matched = match_histograms(image, reference)

fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3, figsize=(8, 3),
                                    sharex=True, sharey=True)
for aa in (ax1, ax2, ax3):
    aa.set_axis_off()

ax1.imshow(image)
ax1.set_title('Source')
ax2.imshow(reference)
ax2.set_title('Reference')
ax3.imshow(matched)
ax3.set_title('Matched')
Exemplo n.º 34
0
    if bias is not None:
        conv_raw = tf.nn.bias_add(conv_raw, bias)
    shp = [s.value for s in conv_raw.get_shape()]
    reshaped = tf.reshape(conv_raw[:, :, :, :n_out_w * n_out_h],
                          (shp[0], shp[1], shp[2], n_out_h, n_out_w))
    transposed = tf.transpose(reshaped, (0, 1, 3, 2, 4))
    output = tf.reshape(transposed,
                        (shp[0], shp[1] * n_out_h, shp[2] * n_out_w, 1))
    return output


if __name__ == "__main__":

    from skimage.data import coffee
    import numpy as np
    c = coffee().astype('float32') / 256.

    conv_kernel = tf.get_variable(
        'kernel',
        dtype=tf.float32,
        shape=(5, 5, 3, 64),
        initializer=tf.contrib.layers.xavier_initializer_conv2d())

    x = tf.placeholder(tf.float32, shape=(1, ) + c.shape)

    convd = cortex_conv(x, conv_kernel)

    sess = tf.Session()
    sess.run(tf.initialize_all_variables())

    out = sess.run(convd, {x: c[np.newaxis]})
Exemplo n.º 35
0
# --------
# imshow() needs numpy array nparray
#
\n\n"""
print(__doc__)

import numpy as np
import matplotlib.pyplot as plt

from skimage import data

scales = ['gray', 'magma', 'jet']

# imshow needs 2d,3d ndarray
img_coins = data.coins()
img_coffee = data.coffee()
img_cat = data.chelsea()
img_original = data.camera()

img_face_area = img_original[50:180, 160:290]  # [y,x]
img_random = np.random.random([300, 300])
img_circle = (lambda x, y: np.exp(-(x**2 + y**2) / 15))(*np.ogrid[-5:5:0.1,
                                                                  -5:5:0.1])


def draw_imgs(img, scales=['gray'], figsize=(10, 5)):
    """show 2 bisect imgs - jet / gray scale """

    fig, axs = plt.subplots(ncols=len(scales), nrows=1, figsize=figsize)

    if len(scales) > 1:
Exemplo n.º 36
0
def color_complements():
    # 补色
    image = data.coffee()
    invert = 255 - image
    io.imshow(invert)
    io.show()
Exemplo n.º 37
0
def color_complements():
    # 补色
    image=data.coffee()
    invert=255-image
    io.imshow(invert)
    io.show()
Exemplo n.º 38
0
from skimage import data, segmentation, color
from skimage.future import graph
from matplotlib import pyplot as plt
import numpy as np

img = data.coffee()

labels1 = segmentation.slic(img, compactness=30, n_segments=400)
out1 = color.label2rgb(labels1, img, kind='avg')
print(np.sum(labels1))
img = data.coffee()
g = graph.rag_mean_color(img, labels1, mode='similarity')
labels2 = graph.cut_normalized(labels1, g)
print(np.sum(labels2))
out2 = color.label2rgb(labels2, img, kind='avg')

fig, ax = plt.subplots(nrows=2, sharex=True, sharey=True, figsize=(6, 8))

ax[0].imshow(out1)
ax[1].imshow(out2)

for a in ax:
    a.axis('off')

plt.tight_layout()
plt.show()
Exemplo n.º 39
0
 def test_gamma(self):
     img = data.coffee()  #测试图片
     gamma_correction(img, 2.2, 1, 1, 1)  #函数内调用我们的类
     gamma_correction(img, 2.2, 2)
     gamma_correction(img, 2.2, 3)
Exemplo n.º 40
0
'''
题目:从skimage.data模块中读取coffee、astronaut、chelsea三张图片,从本地读取一张sea图片,
显示在一个窗口中,将窗口划分成3行2列,分别用于显示这四张图片以及coffee和chelsea的灰度图像,
然后将coffee和chelsea的灰度图像保存到本地,保存为gif格式。
'''
from skimage import io, data, data_dir
import matplotlib.pyplot as plt

img1 = data.coffee()
img2 = data.astronaut()
img3 = data.chelsea()
img4 = io.imread('E:/sea.jpg')
img1_gray = io.imread(data_dir + '/coffee.png', as_gray=True)
img3_gray = io.imread(data_dir + '/chelsea.png', as_gray=True)

plt.subplot(3, 2, 1)  #将窗口分为三行两列六个子图,则可显示六幅图片
plt.title('coffee')  #第一幅图片标题
plt.imshow(img1)  #绘制第一幅图片

plt.subplot(3, 2, 2)
plt.title('astronaut')
plt.imshow(img2)
plt.axis('off')

plt.subplot(3, 2, 3)
plt.title('chelsea')
plt.imshow(img3)
plt.axis('off')

plt.subplot(3, 2, 4)
plt.title('sea')
Exemplo n.º 41
0
# <codecell>

from skimage import data, img_as_float
inception_predict(data.chelsea())   



# <codecell>

inception_predict(data.camera())   



# <codecell>

inception_predict(data.coffee())   


# <markdowncell>
# You can fine-tune Inception to classify your own classes, as described at
# 
# https://keras.io/applications/#fine-tune-inceptionv3-on-a-new-set-of-classes


# <markdowncell>
# ## SciPy: LowLevelCallable
# 
# https://ilovesymposia.com/2017/03/12/scipys-new-lowlevelcallable-is-a-game-
# changer/

Exemplo n.º 42
0
from skimage.data import coffee, camera
from sklearn_theano.feature_extraction import (
    GoogLeNetTransformer, GoogLeNetClassifier)
import numpy as np
from nose import SkipTest
import os

co = coffee().astype(np.float32)
ca = camera().astype(np.float32)[:, :, np.newaxis] * np.ones((1, 1, 3),
                                                             dtype='float32')


def test_googlenet_transformer():
    """smoke test for googlenet transformer"""
    if os.environ.get('CI', None) is not None:
        raise SkipTest("Skipping heavy data loading on CI")
    t = GoogLeNetTransformer()

    t.transform(co)
    t.transform(ca)


def test_googlenet_classifier():
    """smoke test for googlenet classifier"""
    if os.environ.get('CI', None) is not None:
        raise SkipTest("Skipping heavy data loading on CI")
    c = GoogLeNetClassifier()

    c.predict(co)
    c.predict(ca)
Exemplo n.º 43
0
import matplotlib.pyplot as plt

from skimage.feature import hog
from skimage import data, color, exposure


image = color.rgb2gray(data.coffee())

fd, hog_image = hog(image, orientations=8, pixels_per_cell=(16, 16),
                    cells_per_block=(1, 1), visualise=True)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4))

ax1.axis('off')
ax1.imshow(image, cmap=plt.cm.gray)
ax1.set_title('Input image')

# Rescale histogram for better display
hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.02))

ax2.axis('off')
ax2.imshow(hog_image_rescaled, cmap=plt.cm.gray)
ax2.set_title('Histogram of Oriented Gradients')
plt.show()
Exemplo n.º 44
0
    This method computes the mean color of `dst`.

    Parameters
    ----------
    graph : RAG
        The graph under consideration.
    src, dst : int
        The vertices in `graph` to be merged.
    """
    graph.node[dst]['total color'] += graph.node[src]['total color']
    graph.node[dst]['pixel count'] += graph.node[src]['pixel count']
    graph.node[dst]['mean color'] = (graph.node[dst]['total color'] /
                                     graph.node[dst]['pixel count'])


img = data.coffee()
labels = segmentation.slic(img, compactness=30, n_segments=400)
g = graph.rag_mean_color(img, labels)

labels2 = graph.merge_hierarchical(labels, g, thresh=35, rag_copy=False,
                                   in_place_merge=True,
                                   merge_func=merge_mean_color,
                                   weight_func=_weight_mean_color)

g2 = graph.rag_mean_color(img, labels2)

out = color.label2rgb(labels2, img, kind='avg')
out = segmentation.mark_boundaries(out, labels2, (0, 0, 0))
io.imshow(out)
io.show()
Exemplo n.º 45
0
from skimage import data, io, filters
from skimage.color import rgb2gray
from skimage import exposure
from skimage.feature import match_template

# from skimage.exposure import match_histograms


image = data.coffee()
io.imshow(image)
io.show()




# rgb to grayscale
image_gs = rgb2gray(image)
io.imshow(image_gs)
io.show()

# edges
edges = filters.sobel(image[:,:,2])
io.imshow(edges)
io.show()

# histogramme matching
image2 = data.astronaut()
io.imshow(image2)

# matched = match_histograms(image, image2, multichannel=True)
# io.imshow(matched)
Exemplo n.º 46
0
                if neighbours[0, n] > center:
                    lbp_value[0, n] = 1
                else:
                    lbp_value[0, n] = 0

            for n in range(n_points):
                lbp += lbp_value[0, n] * 2**n

            # 转换到0-255的灰度空间,比如n_points=16位时结果会超出这个范围,对该结果归一化
            dst[y, x] = int(lbp / (2**n_points - 1) * 255)

    return dst


if __name__ == "__main__":
    img = coffee()
    fig = plt.figure()
    f1 = fig.add_subplot(121)
    f1.imshow(img)
    f1.set_title("image")

    for colour_channel in (0, 1, 2):
        img[:, :,
            colour_channel] = local_binary_pattern(img[:, :, colour_channel],
                                                   8, 1.0)
    print(img[:, :, colour_channel])
    print(circular_LBP(img[:, :, colour_channel], 8, 1))

    f2 = fig.add_subplot(122)
    f2.imshow(img)
    f2.set_title("LBP")
Exemplo n.º 47
0
""" Script comparing different RPCA algorithms """

from skimage import data, img_as_float
from skimage.util import random_noise
from skimage.color import rgb2grey
from skimage.restoration import denoise_tv_bregman

import numpy as np
import scipy.linalg as la

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid

import nllrtv.wnnm as wnnm

original = img_as_float(rgb2grey(data.coffee()))[::2, ::2]

# add some outliers, i.e., salt and pepper noise
noisy = random_noise(original, "s&p", salt_vs_pepper=1)
# outlier positions
outliers = original != noisy

# weights
U, s, Vh = la.svd(noisy)
C = np.sqrt(noisy.size) * 0.08
w = C / (np.sqrt(s) + 0.001)

params = {
    "w": w,
    "lbda": 0.1,  # TV regularization for additional smoothing
    "mu": 100.0,  # ignore noise, only consider sparse outliers
Exemplo n.º 48
0
def test_coffee():
    """ Test that "coffee" image can be loaded. """
    data.coffee()
ax[1].set_title('Histogram')
ax[1].axvline(thresh, color='r')

ax[2].imshow(binary, cmap=plt.cm.gray)
ax[2].set_title('Thresholded')
ax[2].axis('off')

plt.show()

import matplotlib.pyplot as plt

from skimage import data
from skimage import exposure
from skimage.transform import match_histograms

ref = data.coffee()
img = data.chelsea()

matched = match_histograms(img, ref, multichannel=True)

fig, (ax1, ax2, ax3) = plt.subplots(nrows=1,
                                    ncols=3,
                                    figsize=(8, 3),
                                    sharex=True,
                                    sharey=True)
for aa in (ax1, ax2, ax3):
    aa.set_axis_off()

ax1.imshow(img)
ax1.set_title('Source')
ax2.imshow(ref)