Example #1
0
def test_q4a_apply_hue_adjustment(tmp_path):
    img = data.rocket()
    imsave(tmp_path / 'original.png', img)

    # Adjust the hue in 45-degree increments.
    for amount in range(0, 361, 45):
        adj = adjustment.adjust_hue(img, amount)
        imsave(tmp_path / f'adjusted-{amount}.png', img_as_ubyte(adj))
Example #2
0
def test_q5a_custom_rgb_to_grey():
    img = data.rocket()
    img = img_as_float(img)

    # Setting a weight to '1' and the rest to '0' is equivalent to selecting a
    # particular colour channel.
    assert_array_equal(adjustment.to_monochrome(img, 1, 0, 0), img[:, :, 0])
    assert_array_equal(adjustment.to_monochrome(img, 0, 1, 0), img[:, :, 1])
    assert_array_equal(adjustment.to_monochrome(img, 0, 0, 1), img[:, :, 2])
Example #3
0
def test_q5c_negative_weights_throw_errors():
    img = data.rocket()
    with pytest.raises(ValueError):
        adjustment.to_monochrome(img, -1/3, 1/3, 1/3)

    with pytest.raises(ValueError):
        adjustment.to_monochrome(img, 1/3, -1/3, 1/3)

    with pytest.raises(ValueError):
        adjustment.to_monochrome(img, 1/3, 1/3, -1/3)
Example #4
0
.. [1] Shai Avidan and Ariel Shamir
       "Seam Carving for Content-Aware Image Resizing"
       http://www.cs.jhu.edu/~misha/ReadingSeminar/Papers/Avidan07.pdf

"""
from skimage import data, draw
from skimage import transform, util
import numpy as np
from skimage import filters, color
from matplotlib import pyplot as plt


hl_color = np.array([0, 1, 0])

img = data.rocket()
img = util.img_as_float(img)
eimg = filters.sobel(color.rgb2gray(img))

plt.title('Original Image')
plt.imshow(img)

######################################################################

resized = transform.resize(img, (img.shape[0], img.shape[1] - 200),
                           mode='reflect')
plt.figure()
plt.title('Resized Image')
plt.imshow(resized)

######################################################################
# RGB to grayscale
# In this exercise you will load an image from scikit-image module data and make it grayscale, then compare both of them in the output.

# We have preloaded a function show_image(image, title='Image') that displays the image using Matplotlib. You can check more about its parameters using ?show_image() or help(show_image) in the console.

# Rocket
# Instructions
# 100 XP
# Import the data and color modules from Scikit image. The first module provides example images, and the second, color transformation functions.
# Load the rocket image.
# Convert the RGB-3 rocket image to grayscale.

# Import the modules from skimage
from skimage import data, color

# Load the rocket image
rocket = data.rocket()

# Convert the image to grayscale
gray_scaled_rocket = color.rgb2gray(rocket)

# Show the original image
show_image(rocket, 'Original RGB image')

# Show the grayscale image
show_image(gray_scaled_rocket, 'Grayscale image')
    for i in range(n):
        if (vm[i] == max_v):
            return i
    return "error"


def optimal_binarization(image):
    his = histogram(image)
    # print ( his )
    vm = varianzas(his, image)
    # print( vm )
    pos_vm = whereMax(vm)
    print(pos_vm)
    binimage = binarization(image, pos_vm)
    # print( image )
    return binimage


image = rgb2gray(data.rocket())
plt.figure()
plt.imshow(image)

bin_image = optimal_binarization(image * 255)

plt.figure()
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.subplot(1, 2, 2)
plt.imshow(bin_image, cmap='gray')
plt.show()
Example #7
0
#Está accediendo a los píxeles tales que están:

#Entre las filas 10 y 110 (excluida esta última)
#Entre las columnas 210 y 310 (excluida esta última)
#En el canal 0, que en el formato RGB es el canal Rojo


#Como hemos visto de los ejemplos anteriores, para mostrar una imagen se usa el comando imshow de la biblioteca de matplotlib. 
#Veamos una variación de este comando.

# Cargamos la imagen chelsea en la variable img0
img0 = data.chelsea() 

#Cargamos la imagen rocket en la variable img1

img1= data.rocket()

# La función subplots divide el espacio de la figura en subfiguras
# Los dos primeros parámetros que usamos aquí son el número de filas y columnas del subplot
# el tercer parámetro, figsize, es un parámetro que define el tamaño relativo de los subplots

f, ax = plt.subplots(1, 2, figsize=(20,10))

# Se muestra en el primer subplot la imagen 0, se le asigna un título y se eliminan los ejes del gráfico
ax[0].imshow(img0) # se muestra el primer subplot de la imagen 0
ax[0].set_title('Cat', fontsize=18) # se le asigna un titulo a la imagen y un tamaño
ax[0].axis ('off') # se le eliminan los ejes al grafico


# Se muestra en el primer subplot la imagen 0, se le asigna un título y se eliminan los ejes del gráfico
ax[1].imshow(img1) # se muestra el primer subplot de la imagen 0
Example #8
0
The good news is that the algorithm used by scikit-image works very well for
enlarging images up to a certain point.

In this exercise you'll enlarge an image three times!!

You'll do this by rescaling the image of a rocket, that will be loaded from
the data module.

> Import the module and function needed to enlarge images, you'll do this by
rescaling.
> Import the data module.
> Load the rocket() image from data.
> Enlarge the rocket_image so it is 3 times bigger, with the anti aliasing
filter applied.
> Make sure to set multichannel to True or you risk your session timing out!
"""
import sys
from skimage.transform import rescale
from skimage.data import rocket
sys.path.append('./helpers')
from settings import nda_import_image, show_image, plot_comparison

img_rocket = rocket()
img_rocket_enlarged = rescale(img_rocket,
                              3,
                              anti_aliasing=True,
                              multichannel=True)

plot_comparison(img_rocket, img_rocket_enlarged, '3-times enlarged image')
Example #9
0
from skimage import data
from plic import colorspace


TEST_SOURCE = [data.astronaut(), data.coffee(), data.chelsea(), data.rocket()]
TEST_IMAGES = list(map(colorspace.rgb2rdgdb, TEST_SOURCE))
Example #10
0
import skimage.filters as filters
import skimage.draw as draw
import skimage.color as color
import skimage.segmentation as seg  # For comparison purposes

import cv2

"""**Importing gray image from sklear.data:**"""

image = data.checkerboard()
# image = data.binary_blobs() or image = data.camera()		
plt.imshow(image, cmap = 'gray')

"""**Importing color image from sklearn.data:**"""

image = data.rocket()
# image = data.logo() or image = data.astronaut()
plt.imshow(image)

"""**Import a color image using a global URL:**"""

image = io.imread('https://www.gstatic.com/webp/gallery/1.jpg')
plt.imshow(image)

"""**Importing multiple images from local directory:**"""

image_array = io.ImageCollection('../images/*.png:../images/*.jpg')
print('Type: ', type(image_array))

"""**Customized function to show images:**"""
Example #11
0
import sys
from skimage import data, color
sys.path.append('./helpers')
from settings import show_image

img_rocket = data.rocket()

img_grey_scaled_rocket = color.rgb2gray(img_rocket)

show_image(img_rocket)

show_image(img_grey_scaled_rocket)
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;
entropy_thresh_=1.1;
Example #13
0
"""Color transformations on 2D image."""

from skimage import data, color
from skimage.filters import gaussian
from skimage.io import imsave
import matplotlib.pyplot as plt
import numpy as np
import compoda.core as coda
from compoda.utils import truncate_range
from matplotlib import rcParams
rcParams['font.family'] = "serif"
# rcParams['mathtext.fontset'] = 'dejavuserif'

# load image
orig = data.rocket()
img = np.copy(orig) * 1.0
dims = img.shape

# impute zeros
idx1 = (img[..., 0] <= 0) + (img[..., 1] <= 0) + (img[..., 2] <= 0)
gauss = gaussian(img, sigma=0.5, multichannel=True)
img[idx1, :] = gauss[idx1, :]

# rgb to hsv for control
hsv = color.rgb2hsv(img)
hsv[..., 0] = -np.abs(hsv[..., 0] - 0.5) + 0.5

# coda stuff
angdif_norm_int = np.zeros(img.shape)
temp = img.reshape(dims[0] * dims[1], dims[2]) * 1.0
bary = coda.closure(temp, 100)
Example #14
0
import pylab as plt
from matplotlib.animation import FuncAnimation
from skimage import data

a = [data.astronaut(), data.camera(), data.rocket()]
fig = plt.figure(figsize=(3, 3))


def update(frame_index):
    plt.imshow(a[frame_index % len(a)])


animation = FuncAnimation(fig, update, interval=1000)
plt.axis('off')
plt.show()
Example #15
0
# Import the module and function to enlarge images
from skimage.transform import rescale
import matplotlib.pyplot as plt
import matplotlib

# Import the data module
from skimage import data

# Load the image from data
rocket_image = data.rocket()

# Enlarge the image so it is 3 times bigger
enlarged_rocket_image = rescale(rocket_image,
                                3,
                                anti_aliasing=True,
                                multichannel=True)

# Show original and resulting image
show_image(rocket_image)
show_image(enlarged_rocket_image, "3 times enlarged image")
Example #16
0
# Adjusting brightness
# exposure module is used for analyzing image light intensities using histograms
from skimage import exposure, io, data

image = data.rocket()  #by default gamma value is 1
image_bright = exposure.adjust_gamma(image, gamma=0.5)
image_dark = exposure.adjust_gamma(image, gamma=2)

io.imshow_collection([image, image_bright, image_dark])
io.show()
Example #17
0
def test_rocket():
    """ Test that "rocket" image can be loaded. """
    data.rocket()
Example #18
0
    tf.keras.layers.Dense(1024, activation=tf.nn.relu),
    tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])

#model.compile(optimizer = 'adam',
#              loss = 'sparse_categorical_crossentropy')
#
#model.fit(training_images, training_labels, epochs=1)
#
#model.evaluate(test_images, test_labels)
#
#classifications = model.predict(test_images)

from skimage import data, color

rocket = data.rocket()  #; plt.imshow(rocket)


def show_image(image, title='Title', cmap_type='gray'):
    plt.imshow(image, cmap=cmap_type)
    plt.title(title)
    plt.axis('off')
    plt.show()


def show_image_contour(image, contours):
    plt.figure()
    for n, contour in enumerate(contours):
        plt.plot(contour[:, 1], contour[:, 0], linewidth=3)
    plt.imshow(image, interpolation='nearest', cmap='gray_r')
    plt.title('Contours')