Exemple #1
0
def setup_binary_test():
    horse = data.horse()
    tf_horse = horse == 1
    tf_horse = tf.cast(tf_horse, tf.int32)
    tf_horse = tf.reshape(tf_horse, (1, 328, 400, 1))
    selem = skimage.morphology.disk(6)
    tf_selem = tf.cast(selem, tf.int32)
    tf_selem = tf.reshape(tf_selem, (13, 13, 1))
    return (horse, tf_horse), (selem, tf_selem)
Exemple #2
0
 def test_resample_image(self):
     original = data.horse()
     # Test simple cropping with no resampling
     new_shape = (int(original.shape[0] * 0.5), int(original.shape[1] * 0.5))
     resized = resample_image(original, new_shape=new_shape,
                              src_dims=(1, 1), new_dims=(0.5, 0.5))
     self.assertEqual(resized.shape, new_shape)
     # Test sample resizing with no cropping
     new_shape = (int(original.shape[0] * 2), int(original.shape[1] * 2))
     resized = resample_image(original, new_shape=new_shape,
                              src_dims=(1, 1), new_dims=(1, 1))
     self.assertEqual(resized.shape, new_shape)
Exemple #3
0
    def setup(self, *args):
        try:
            # use a separate skeletonize_3d function on older scikit-image
            if Version(skimage.__version__) < Version('0.16.0'):
                self.skeletonize = morphology.skeletonize_3d
            else:
                self.skeletonize = morphology.skeletonize
        except AttributeError:
            raise NotImplementedError("3d skeletonize unavailable")

        # we stack the horse data 5 times to get an example volume
        self.image = np.stack(5 * [util.invert(data.horse())])
Exemple #4
0
 def test_crop_image(self):
     original = data.horse()
     # Test simple cropping
     cropped = crop_image(original, (64, 64), center=(164, 200))
     expected = original[132:196,168:232]
     np.testing.assert_equal(cropped, expected)
     # Test with a center outside the window
     cropped = crop_image(original, (64, 64), center=(30, 380))
     expected = original[:64,336:]
     np.testing.assert_equal(cropped, expected)
     # Test what happens if the target is bigger than the destination
     with self.assertRaises(exceptions.XanesMathError):
         cropped = crop_image(original, (600, 600))
Exemple #5
0
    def __init__(self):
        super(Root, self).__init__()
        self.title("GÖRÜNTÜ İŞLEME")
        self.minsize(500, 700)
        self.img = data.coins()
        self.img_gray = data.coins()
        self.retina = data.retina()
        self.moon = data.moon()
        self.horse = data.horse()
        self.camera = data.camera()
        self.width = 50
        self.imageGlobal = data.retina()
        self.imageGlobal = cv2.cvtColor(self.imageGlobal, cv2.COLOR_BGR2GRAY)

        self.labelFrame = tk.LabelFrame(self, text="DOSYA AÇ")
        self.labelFrame.grid(column=0, row=1, padx=20, pady=20)

        self.filterFrame = tk.LabelFrame(self, text="FİLTRELER")
        self.filterFrame.grid(column=0, row=2, padx=20, pady=20)

        self.histogramFrame = tk.LabelFrame(self, text="HİSTOGRAM EŞİTLEME")
        self.histogramFrame.grid(column=0, row=3, padx=20, pady=20)

        self.transformFrame = tk.LabelFrame(self, text="DÖNÜŞTÜRME İŞLEMLERİ")
        self.transformFrame.grid(column=0, row=4, padx=20, pady=20)

        self.videoFrame = tk.LabelFrame(self, text="VİDEO FİLTRESİ")
        self.videoFrame.grid(column=0, row=5, padx=20, pady=20)

        self.intensityFrame = tk.LabelFrame(self, text="YOĞUNLUK İŞLEMLERİ")
        self.intensityFrame.grid(column=1, row=4, padx=20, pady=20)

        self.morphologyFrame = tk.LabelFrame(self, text="MORFOLOJİK İŞLEMLER")
        self.morphologyFrame.grid(column=1, row=3, padx=20, pady=20)
        
        self.activeFrame = tk.LabelFrame(self, text="ACTİVE CONTOUR")
        self.activeFrame.grid(column=1, row=1, padx=20, pady=20)
        
        self.socialFrame = tk.LabelFrame(self, text="SOSYAL MEDYA EFEKTİ")
        self.socialFrame.grid(column=1, row=2, padx=20, pady=20)

        self.upload_image_button()
        self.filterButton()
        self.histogramButton()
        self.transformButton()
        self.videoButton()
        self.intensityButton()
        self.morphologyButton()
        self.activeContourButton()
        self.socialButton()
Exemple #6
0
def skeletonize():
    image = color.rgb2gray(data.horse())
    image = 1 - image  # Invert
    skeleton = morphology.skeletonize(image)

    fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(8, 4))
    ax1.imshow(image, cmap=plt.cm.get_cmap('gray'))
    ax1.set_title('original', fontsize=15)
    ax1.axis('off')
    ax2.imshow(skeleton, cmap=plt.cm.get_cmap('gray'))
    ax2.set_title('skeleton', fontsize=15)
    ax2.axis('off')
    fig.tight_layout()
    plt.show()
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()
def morph_demo():
    image = data.horse()
    gray = color.rgb2gray(image)
    ret = filters.threshold_otsu(gray)
    binary = gray < ret # 二值化反
    skele = morphology.skeletonize(binary)

    fig, axes = plt.subplots(1, 2, figsize=(8, 4))
    ax = axes.ravel()

    ax[0].imshow(gray,cmap='gray')
    ax[0].set_title("Input ")
    ax[1].imshow(skele, cmap='gray')
    ax[1].set_title("skeletonize")
    ax[0].axis('off')
    ax[1].axis('off')

    fig.tight_layout()
    plt.show()
Exemple #9
0
def testSkeleton():
    image = color.rgb2gray(data.horse())
    image = 1 - image
    # 实施骨架算法
    skeleton = morphology.skeletonize(image)

    # 显示结果
    fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(8, 4))

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

    ax2.imshow(skeleton, cmap=plt.cm.gray)
    ax2.axis('off')
    ax2.set_title('skeleton', fontsize=20)

    fig.tight_layout()
    plt.show()
def test():
    from skimage.morphology import skeletonize
    import numpy as np
    from skimage import data
    import matplotlib.pyplot as plt

    img = data.horse()
    ske = skeletonize(~img).astype(np.uint16)
    graph = build_sknw(ske)
    plt.imshow(img, cmap='gray')
    for (s, e) in graph.edges():
        ps = graph[s][e]['pts']
        plt.plot(ps[:, 1], ps[:, 0], 'green')

    node, nodes = graph.node, graph.nodes()
    ps = np.array([node[i]['o'] for i in nodes])
    plt.plot(ps[:, 1], ps[:, 0], 'r.')
    plt.title('Build Graph')
    plt.show()
Exemple #11
0
    def __init__(self):
        super(Root, self).__init__()
        self.title("Image Processor")
        self.minsize(640, 400)
        self.img = data.coins()
        self.img_gray = data.coins()
        self.retina = data.retina()
        self.moon = data.moon()
        self.horse = data.horse()
        self.camera = data.camera()
        self.width = 50

        self.labelFrame = tk.LabelFrame(self, text="Open File")
        self.labelFrame.grid(column=0, row=1, padx=20, pady=20)

        self.filterFrame = tk.LabelFrame(self, text="Filters")
        self.filterFrame.grid(column=1, row=1, padx=20, pady=20)

        self.histogramFrame = tk.LabelFrame(self, text="Histogram Matching")
        self.histogramFrame.grid(column=2, row=1, padx=20, pady=20)

        self.transformFrame = tk.LabelFrame(self, text="Transform Operations")
        self.transformFrame.grid(column=0, row=2, padx=20, pady=20)

        self.videoFrame = tk.LabelFrame(
            self, text="Green Filtered Video from your cam")
        self.videoFrame.grid(column=1, row=2, padx=20, pady=20)

        self.intensityFrame = tk.LabelFrame(self, text="Intensity Operations")
        self.intensityFrame.grid(column=2, row=2, padx=20, pady=20)

        self.morphologyFrame = tk.LabelFrame(self,
                                             text="Morphological Operations")
        self.morphologyFrame.grid(column=0, row=3, padx=20, pady=20)

        self.upload_image_button()
        self.filterButton()
        self.histogramButton()
        self.transformButton()
        self.videoButton()
        self.intensityButton()
        self.morphologyButton()
Exemple #12
0
def convex_hull():

    # The original image is inverted as the object must be white.
    image = util.invert(data.horse())

    chull = morphology.convex_hull_image(image)

    fig, axes = plt.subplots(1, 2, figsize=(8, 4))
    ax = axes.ravel()

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

    ax[1].set_title('Transformed picture')
    ax[1].imshow(chull, cmap=plt.cm.gray)
    ax[1].set_axis_off()

    plt.tight_layout()
    plt.show()
Exemple #13
0
def skeletonize():    
    image = util.invert(data.horse())  
    # perform skeletonization
    skeleton = morphology.skeletonize(image)

    # display results
    fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(8, 4),
                            sharex=True, sharey=True)

    ax = axes.ravel()

    ax[0].imshow(image, cmap=plt.cm.gray)
    ax[0].axis('off')
    ax[0].set_title('original', fontsize=20)

    ax[1].imshow(skeleton, cmap=plt.cm.gray)
    ax[1].axis('off')
    ax[1].set_title('skeleton', fontsize=20)

    fig.tight_layout()
    plt.show()
from cv2 import cv2 as cv
from skimage.data import horse
import numpy as np

img_raw = horse().astype('uint8')
img_raw = np.ones(img_raw.shape) - img_raw

img = img_raw.copy().astype('uint8')

contours, hierachy = cv.findContours(img, cv.RETR_TREE,
                                     cv.CHAIN_APPROX_TC89_KCOS)
image = cv.drawContours(img, contours, 0, 2)

cv.imshow('horse', image)
cv.waitKey(0)
import matplotlib.pyplot as plt
from skimage import data, color, morphology

# 生成二值测试图像
img = color.rgb2gray(data.horse())
img = (img < 0.5) * 1

chull = morphology.convex_hull_image(img)

# 绘制轮廓
fig, axes = plt.subplots(1, 2, figsize=(8, 8))
ax0, ax1 = axes.ravel()
ax0.imshow(img, plt.cm.gray)
ax0.set_title('original image')

ax1.imshow(chull, plt.cm.gray)
ax1.set_title('convex_hull image')
plt.show()
Exemple #16
0
        i2=id-w;i8=id+w;i1=i2-1;i3=i2+1;
        i4=id-1;i6=id+1;i7=i8-1;i9=i8+1;

        c = (data[i1]>0)<<0|(data[i2]>0)<<1\
            |(data[i3]>0)<<2|(data[i4]>0)<<3\
            |(data[i6]>0)<<4|(data[i7]>0)<<5\
            |(data[i8]>0)<<6|(data[i9]>0)<<7
        if (lut[c//8]>> c%8) &1:data[id]=0
    return 0;

def mid_axis(img):
    dis = distance_transform_edt(img)
    dis[[0,-1],:] = 0; dis[:,[0,-1]] = 0
    idx = np.argsort(dis.flat).astype(np.int32)
    medial_axis(dis, idx, lut)
    return dis

if __name__ == '__main__':
    from time import time
    from skimage.data import horse
    #from skimage.morphology import medial_axis
    import matplotlib.pyplot as plt

    img = ~horse()*255
    mid_axis(img.copy())
    t1 = time()
    a = mid_axis(img)
    t2 = time()
    print(t2 - t1)
    plt.imshow(a)
    plt.show()
Exemple #17
0
    def medialAxis(self):
        filteredImage = morphology.medial_axis(data.horse() == 0)

        self.showImage(filteredImage)
        self.rawImage = filteredImage
        print("Medial Axis")
Exemple #18
0
def test_horse():
    """ Test that "horse" image can be loaded. """
    horse = data.horse()
    assert_equal(horse.ndim, 2)
    assert_equal(horse.dtype, np.dtype('bool'))
 def setup(self, *args):
     # we stack the horse data 5 times to get an example volume
     self.image = np.stack(5 * [invert(data.horse())])
Exemple #20
0
	eroded = morphology.erosion(arr, square(3))
	morphology.dilation(eroded, square(3))
coins = data.coins()
binary = coins > 150
show(coins, binary)
eroded = Image(morphology.erosion(binary, square(3)))
show(binary, eroded)
dilated = Image(morphology.dilation(binary, square(3)))
show(binary, dilated)
dilated = Image(morphology.dilation(binary, square(5)))
eroded = Image(morphology.erosion(dilated, square(5)))
show(binary, dilated, eroded)
result = eroded
opened = morphology.opening(result, square(2))
show(result, opened)
horse = rgb2gray(255 - data.horse()) > 0.5

count = 3
eroded = horse
for i in range(count):
    eroded = morphology.erosion(eroded, square(5))

dilated = eroded
for i in range(count):
    dilated = morphology.dilation(dilated, square(5))

show(horse, eroded, dilated)


horse = rgb2gray(255 - data.horse()) > 0.5
# of another operation. This duality can be summarized as follows:
#
#   1. Erosion <-> Dilation
#
#   2. Opening <-> Closing
#
#   3. White tophat <-> Black tophat
#
# Skeletonize
# ===========
#
# Thinning is used to reduce each connected component in a binary image to a
# *single-pixel wide skeleton*. It is important to note that this is
# performed on binary images only.

horse = data.horse()

sk = skeletonize(horse == 0)
plot_comparison(horse, sk, 'skeletonize')

######################################################################
# As the name suggests, this technique is used to thin the image to 1-pixel
# wide skeleton by applying thinning successively.
#
# Convex hull
# ===========
#
# The ``convex_hull_image`` is the *set of pixels included in the smallest
# convex polygon that surround all white pixels in the input image*. Again
# note that this is also performed on binary images.
Exemple #22
0
    def binaryErosion(self):
        filteredImage = morphology.binary_erosion(data.horse() == 0)

        self.showImage(filteredImage)
        self.rawImage = filteredImage
        print("binaryErosion")
Exemple #23
0
    def skeletonize(self):
        filteredImage = morphology.skeletonize(data.horse() == 0)

        self.showImage(filteredImage)
        self.rawImage = filteredImage
        print("Skeletonize")
Exemple #24
0
    def convexHull(self):
        filteredImage = morphology.convex_hull_image(util.invert(data.horse()))

        self.showImage(filteredImage)
        self.rawImage = filteredImage
        print("Convex Hull")
'''
Skeletonization reduces binary objects to 1 pixel wide representations.
This can be useful for feature extraction, and/or representing an object’s topology

works by making successive passes of the image, removing pixels on object borders. This continues until no more pixels can be removed. The image is correlated with a mask that assigns each pixel a number in the range [0…255] corresponding to each possible pattern of its 8 neighbouring pixels. A look up table is then used to assign the pixels a value of 0, 1, 2 or 3, which are selectively removed during the iterations.
'''
from skimage.morphology import skeletonize
from skimage import data
import matplotlib.pyplot as plt
from skimage.util import invert

# Invert the horse image
image = invert(data.horse())

# perform skeletonization
skeleton = skeletonize(image)

# display results
fig, axes = plt.subplots(nrows=1,
                         ncols=2,
                         figsize=(8, 4),
                         sharex=True,
                         sharey=True)
ax = axes.ravel()
ax[0].imshow(image, cmap=plt.cm.gray)
ax[0].axis('off')
ax[0].set_title('original', fontsize=20)
ax[1].imshow(skeleton, cmap=plt.cm.gray)
ax[1].axis('off')
ax[1].set_title('skeleton', fontsize=20)
fig.tight_layout()
Exemple #26
0
    nbs = neighbors(dis.shape)
    acc = np.cumprod((1, ) + dis.shape[::-1][:-1])[::-1]
    line = dis.ravel()
    pts = np.zeros(max(line.size // 4, 1024**2), dtype=np.int64)
    roots = np.zeros(max(line.size // 4, 1024**2), dtype=np.int64)
    s = collect(line, nbs, pts, roots)
    for level in range(10000):
        s, c = clear(pts, roots, s, 0)
        s = step(line, pts, roots, s, level, nbs, acc, scale)
        if s == 0: break
    return dis[(slice(1, -1), ) * img.ndim]


if __name__ == '__main__':
    import matplotlib.pyplot as plt
    from skimage.io import imread
    from glob import glob
    arr = np.ones((255, 255), dtype=np.uint8)
    arr[128, 128] = 0
    from skimage.data import horse

    arr = ~horse() * 255
    print(arr.min(), arr.max())
    dis = distance_transform_edt(arr, np.float64)

    from scipy.ndimage import distance_transform_edt as sciedt
    dis2 = sciedt(arr)
    print(np.abs(dis - dis2).max())
    plt.imshow(dis2)
    plt.show()
Exemple #27
0
    plt.tight_layout()
    plt.show()
    plt.close()


##Driver script
if __name__ == "__main__":
    #test 2 3channels figures

    reference = data.coffee()
    source = data.astronaut()
    #plot
    plot(source, reference)

    #test 2  1channels figures
    '''
    It will rasie ValueError('Number of channels in the input image and reference' 
    (same as orginal function in skimage)
    '''
    reference2 = data.camera()
    source2 = data.horse()
    plot(source2, reference2)

    #test 3  2 different channels figures
    '''
    It will rasie ValueError: Number of channels in the input image and reference image must match!
    '''
    reference3 = data.coffee()
    source3 = data.horse()
    plot(source3, reference3)
print(tform.params)

#Alternatively you can define a transformation by the transformation matrix itself:
matrix = tform.params.copy()
matrix[1, 2] = 2
tform2 = tf.SimilarityTransform(matrix)

coord = [1, 0]
print(tform2(coord))
print(tform2.inverse(tform2(coord)))



#Geometric transformations can also be used to warp images:

text = data.horse()

tform = tf.SimilarityTransform(scale=1, rotation=math.pi/4,
                               translation=(text.shape[0]/2, -100))

rotated = tf.warp(text, tform)
back_rotated = tf.warp(rotated, tform.inverse)

fig, ax = plt.subplots(nrows=3)

ax[0].imshow(text, cmap=plt.cm.gray)
ax[1].imshow(rotated, cmap=plt.cm.gray)
ax[2].imshow(back_rotated, cmap=plt.cm.gray)

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

Skeletonization reduces binary objects to 1 pixel wide representations. This
can be useful for feature extraction, and/or representing an object's topology.

``skeletonize`` works by making successive passes of the image. On each pass,
border pixels are identified and removed on the condition that they do not
break the connectivity of the corresponding object.
"""
from skimage.morphology import skeletonize
from skimage import data
import matplotlib.pyplot as plt
from skimage.util import invert

# Invert the horse image
image = invert(data.horse())

# perform skeletonization
skeleton = skeletonize(image)

# display results
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(8, 4),
                         sharex=True, sharey=True,
                         subplot_kw={'adjustable': 'box-forced'})

ax = axes.ravel()

ax[0].imshow(image, cmap=plt.cm.gray)
ax[0].axis('off')
ax[0].set_title('original', fontsize=20)
Exemple #30
0
plt.show()

from skimage import io
import matplotlib.pyplot as plt

my_image = io.imread(
    'C:\Users\jackh\OneDrive\Documents\College\Python\Images\pose.jpg')
plt.imshow(my_image)
plt.show()

### rotate an image

from skimage import data
from skimage.transform import rotate

image = data.horse()
plt.subplot(2, 1, 1)
plt.imshow(image)
rotated_image = rotate(image, 30)
plt.subplot(2, 1, 2)
plt.imshow(rotated_image)
plt.show()

### resize

from skimage import data
from skimage.transform import resize

image = data.horse()
plt.subplot(2, 1, 1)
plt.imshow(image)
Exemple #31
0
# Obtain the segmentation with 400 regions
segments = slic(face_image, n_segments= 400)

# Put segments on top of original image to compare
segmented_image = label2rgb(segments, face_image, kind='avg')

# Show the segmented image
show_image(segmented_image, "Segmented image, 400 superpixels")

--------------------------------------------------
# Exercise_7 
# Import the modules
from skimage import data, measure

# Obtain the horse image
horse_image = data.horse()

# Find the contours with a constant level value of 0.8
contours = measure.find_contours(horse_image, 0.8)

# Shows the image with contours found
show_image_contour(horse_image, contours)

--------------------------------------------------
# Exercise_8 
#1
# Make the image grayscale
image_dices = color.rgb2gray(image_dices)
#2
# Make the image grayscale
image_dices = color.rgb2gray(image_dices)
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;
from skimage import morphology, data, color
import matplotlib.pyplot as plt

image = color.rgb2gray(data.horse())
image = 1 - image  #反相
#实施骨架算法
skeleton = morphology.skeletonize(image)

#显示结果
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(8, 4))

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

ax2.imshow(skeleton, cmap=plt.cm.gray)
ax2.axis('off')
ax2.set_title('skeleton', fontsize=20)

fig.tight_layout()
plt.show()
Exemple #34
0
    def thin(self):
        filteredImage = morphology.thin(data.horse() == 0)

        self.showImage(filteredImage)
        self.rawImage = filteredImage
        print("Thin")