def test_binary_blobs(): blobs = data.binary_blobs(length=128) assert_almost_equal(blobs.mean(), 0.5, decimal=1) blobs = data.binary_blobs(length=128, volume_fraction=0.25) assert_almost_equal(blobs.mean(), 0.25, decimal=1) blobs = data.binary_blobs(length=32, volume_fraction=0.25, n_dim=3) assert_almost_equal(blobs.mean(), 0.25, decimal=1) other_realization = data.binary_blobs(length=32, volume_fraction=0.25, n_dim=3) assert not np.all(blobs == other_realization)
def test_4d_input_pixel(): phantom = img_as_float(binary_blobs(length=32, n_dim=4)) reference_image = np.fft.fftn(phantom) shift = (-2., 1., 5., -3) shifted_image = fourier_shift(reference_image, shift) result, error, diffphase = register_translation(reference_image, shifted_image, space="fourier") assert_allclose(result, -np.array(shift), atol=0.05)
def test_3d_vs_fiji(): # generate an image with blobs and compate its skeleton to # the skeleton generated by FIJI img = binary_blobs(32, 0.05, n_dim=3, seed=1234) img = img[:-2, ...] img = img.astype(np.uint8)*255 img_s = skeletonize_3d(img) img_f = io.imread(os.path.join(data_dir, "_blobs_3d_fiji_skeleton.tif")) assert_equal(img_s, img_f)
def test_3d_input(): phantom = img_as_float(binary_blobs(length=32, n_dim=3)) reference_image = np.fft.fftn(phantom) shift = (-2., 1., 5.) shifted_image = fourier_shift(reference_image, shift) result, error, diffphase = register_translation(reference_image, shifted_image, space="fourier") assert_allclose(result, -np.array(shift), atol=0.05) # subpixel precision not available for 3-D data subpixel_shift = (-2.3, 1., 5.) shifted_image = fourier_shift(reference_image, subpixel_shift) result, error, diffphase = register_translation(reference_image, shifted_image, space="fourier") assert_allclose(result, -np.array(shift), atol=0.5) assert_raises(NotImplementedError, register_translation, reference_image, shifted_image, upsample_factor=100, space="fourier")
def setup(self, ndims, image_size, upscale_factor, *args): shifts = (-2.3, 1.7, 5.4, -3.2)[:ndims] phantom = img_as_float(binary_blobs(length=image_size, n_dim=ndims)) self.reference_image = np.fft.fftn(phantom) self.shifted_image = ndi.fourier_shift(self.reference_image, shifts)
""" Display one 4-D image layer using the add_image API """ import numpy as np from skimage import data import napari with napari.gui_qt(): blobs = data.binary_blobs(length=128, blob_size_fraction=0.05, n_dim=3, volume_fraction=0.1).astype(float) viewer = napari.view(blobs.astype(float)) # create one random polygon per "plane" planes = np.tile(np.arange(128).reshape((128, 1, 1)), (1, 5, 1)) np.random.seed(0) corners = np.random.uniform(0, 128, size=(128, 5, 2)) shapes = np.concatenate((planes, corners), axis=2) base_cols = ['red', 'green', 'blue', 'white', 'yellow', 'magenta', 'cyan'] colors = np.random.choice(base_cols, size=128) layer = viewer.add_shapes( np.array(shapes), shape_type='polygon', face_color=colors, name='sliced', )
"NOTE: if you get a bad results for ssi, blame stochastic optimisation and retry..." ) print( " The training is done on the same exact image that we infer on, very few pixels..." ) print(" Training should be more stable given more data...") with napari.gui_qt(): viewer = napari.Viewer() viewer.add_image(image, name='image') viewer.add_image(blurred_image, name='blurred') viewer.add_image(noisy_blurred_image, name='noisy_blurred_image') #viewer.add_image(lr_deconvolved_image_2_clipped, name='lr_deconvolved_image_2') viewer.add_image(lr_deconvolved_image_5_clipped, name='lr_deconvolved_image_5') #viewer.add_image(lr_deconvolved_image_10_clipped, name='lr_deconvolved_image_10') #viewer.add_image(lr_deconvolved_image_20_clipped, name='lr_deconvolved_image_20') viewer.add_image(deconvolved_image_clipped, name='ssi_deconvolved_image') if __name__ == '__main__': from skimage import data image = data.binary_blobs(length=64, n_dim=3, blob_size_fraction=0.1, seed=1) demo(image)
import numpy as np import matplotlib.pyplot as plt from skimage.segmentation import random_walker from skimage.data import binary_blobs from skimage.exposure import rescale_intensity import skimage # noisy synthetic data generation # seeds data = skimage.img_as_float(binary_blobs(length=128, seed=1)) sigma = 0.35 data += np.random.normal(loc=0, scale=sigma, size=data.shape) # rescale intensity range from -sigma, 1+sigma to -1, 1 data = rescale_intensity(data, in_range=(-sigma, 1 + sigma), out_range=(-1, 1)) # choose hottest and coldest pixels as markers markers = np.zeros(data.shape, dtype=np.uint) markers[data < -0.95] = 1 # if data < -0.95 then 1 markers[data > 0.95] = 2 # if data > 0.95 then 2 # prob = exp(-beta(zp - zq)): zp and zq are two charged particles (nodes) # random_walker is solved like for an electron # prob is like conductange - lesser it is, harder it is to iterate that path labels = random_walker(data, markers, beta=10, mode='bf') # plot results fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(8, 3.2), sharex=True, \ sharey=True)
# ``skeletonize_3d`` [Lee94]_ uses an octree data structure to examine a 3x3x3 # neighborhood of a pixel. The algorithm proceeds by iteratively sweeping # over the image, and removing pixels at each iteration until the image # stops changing. Each iteration consists of two steps: first, a list of # candidates for removal is assembled; then pixels from this list are # rechecked sequentially, to better preserve connectivity of the image. # # Note that ``skeletonize_3d`` is designed to be used mostly on 3-D images. # However, for illustrative purposes, we apply this algorithm on a 2-D image. import matplotlib.pyplot as plt from skimage.morphology import skeletonize, skeletonize_3d from skimage.data import binary_blobs data = binary_blobs(200, blob_size_fraction=.2, volume_fraction=.35, seed=1) skeleton = skeletonize(data) skeleton3d = skeletonize_3d(data) fig, axes = plt.subplots(1, 3, figsize=(8, 4), sharex=True, sharey=True, subplot_kw={'adjustable': 'box-forced'}) ax = axes.ravel() ax[0].imshow(data, cmap=plt.cm.gray, interpolation='nearest') ax[0].set_title('original') ax[0].axis('off') ax[1].imshow(skeleton, cmap=plt.cm.gray, interpolation='nearest') ax[1].set_title('skeletonize') ax[1].axis('off')
from mpl_toolkits.mplot3d.art3d import Poly3DCollection from lib.read_write import * from skimage import measure from skimage.draw import ellipsoid from skimage.data import binary_blobs from lib.render import * import sys # Generate a level set about zero of two identical ellipsoids in 3D # ellip_base = ellipsoid(6, 10, 16, levelset=True) # ellip_double = np.concatenate((ellip_base[:-1, ...], # ellip_base[2:, ...]), axis=0) data = binary_blobs(length=50, blob_size_fraction=0.4, n_dim=3, volume_fraction=0.1, seed=None) data = scipy.io.loadmat( "L:\\Users\\gordon\\00000004 - Running Projects\\20180126 Mito quantification for Gordon\\20180306_results\\3D_seg\\CSM_0b29da6715724d089eb08c6ec15ad193_3DS.mat" )['data'] data[data > 0] = 1 stack_viewer(data) # print type(data[0,0,0]) print data.shape # sys.exit() # Use marching cubes to obtain the surface mesh of these ellipsoids verts, faces, normals, values = measure.marching_cubes_lewiner( data, level=None,
def next(viewer): blobs = data.binary_blobs(length=128, blob_size_fraction=0.05, n_dim=2, volume_fraction=0.25).astype(float) viewer.layers[0].data = blobs
""" Display one points layer ontop of one 4-D image layer using the add_points and add_image APIs, where the markes are visible as nD objects across the dimensions, specified by their size """ import numpy as np from skimage import data import napari blobs = data.binary_blobs(length=100, blob_size_fraction=0.05, n_dim=3, volume_fraction=0.05) viewer = napari.view_image(blobs.astype(float)) # create the points points = [] for z in range(blobs.shape[0]): points += [[z, 25, 25], [z, 25, 75], [z, 75, 25], [z, 75, 75]] # create the property for setting the face and edge color. face_property = np.array([True, True, True, True, False, False, False, False] * int(blobs.shape[0] / 2)) edge_property = np.array(['A', 'B', 'C', 'D', 'E'] * int(len(points) / 5)) properties = { 'face_property': face_property, 'edge_property': edge_property, }
''' # %% import numpy as np from skimage import data, filters import napari from skimage import segmentation from skimage import morphology import os from dask import array as da # %% blobs_raw = np.stack([ data.binary_blobs(length=256, n_dim=3, volume_fraction=f) for f in np.linspace(0.05, 0.5, 10) ]) blobs = filters.gaussian(blobs_raw, sigma=(0, 2, 2, 2)) print(blobs.shape) (10, 256, 256, 256) # %% viewer = napari.view_image(blobs) # %% coins = data.coins()
""" Playground2: Development of MorphoSphere3D @authors: Fanny Georgi """ import skimage import math import cv2 from scipy import ndimage from skimage import measure, morphology, data import numpy as np import matplotlib.pyplot as plt import pandas as pd from ggplot import * from PIL import Image import re #import multiproessing #import tiffcapture as tc import skimage.io im = data.binary_blobs(128, n_dim=3, volume_fraction=0.2) print im.shape labels = measure.label(im) print type(im), type(labels) labels[0, 0, 0] print 'done' ################## breakpoint is happy here
#!/usr/bin/env python # -*- coding:utf-8 -*- from skimage import data from skimage import io import numpy as np import matplotlib.pyplot as plt import pylab image = data.binary_blobs() plt.imshow(image, 'gray') pylab.show() image_color = data.astronaut() plt.imshow(image_color) pylab.show() image_local = io.imread('e:/cf400dc4d7e128635f2e066f7497eb8b.jpg') plt.imshow(image_local) pylab.show()
values, and use the random walker for the segmentation. .. [1] *Random walks for image segmentation*, Leo Grady, IEEE Trans. Pattern Anal. Mach. Intell. 2006 Nov; 28(11):1768-83 :DOI:`10.1109/TPAMI.2006.233` """ import numpy as np import matplotlib.pyplot as plt from skimage.segmentation import random_walker from skimage.data import binary_blobs from skimage.exposure import rescale_intensity import skimage # Generate noisy synthetic data data = skimage.img_as_float(binary_blobs(length=128, seed=1)) sigma = 0.35 data += np.random.normal(loc=0, scale=sigma, size=data.shape) data = rescale_intensity(data, in_range=(-sigma, 1 + sigma), out_range=(-1, 1)) # The range of the binary image spans over (-1, 1). # We choose the hottest and the coldest pixels as markers. markers = np.zeros(data.shape, dtype=np.uint) markers[data < -0.95] = 1 markers[data > 0.95] = 2 # Run random walker algorithm labels = random_walker(data, markers, beta=10, mode='bf') # Plot results
# .. [Zha84] A fast parallel algorithm for thinning digital patterns, # T. Y. Zhang and C. Y. Suen, Communications of the ACM, # March 1984, Volume 27, Number 3. # # .. [Lee94] T.-C. Lee, R.L. Kashyap and C.-N. Chu, Building skeleton models # via 3-D medial surface/axis thinning algorithms. # Computer Vision, Graphics, and Image Processing, 56(6):462-478, # 1994. # import matplotlib.pyplot as plt from skimage.morphology import skeletonize from skimage.data import binary_blobs data = binary_blobs(200, blob_size_fraction=.2, volume_fraction=.35, seed=1) skeleton = skeletonize(data) skeleton_lee = skeletonize(data, method='lee') fig, axes = plt.subplots(1, 3, figsize=(8, 4), sharex=True, sharey=True) ax = axes.ravel() ax[0].imshow(data, cmap=plt.cm.gray) ax[0].set_title('original') ax[0].axis('off') ax[1].imshow(skeleton, cmap=plt.cm.gray) ax[1].set_title('skeletonize') ax[1].axis('off')
""" Display a labels layer above of an image layer using the add_labels and add_image APIs """ from skimage import data from scipy import ndimage as ndi from napari_animation import Animation import napari blobs = data.binary_blobs(length=128, volume_fraction=0.1, n_dim=3) viewer = napari.view_image(blobs.astype(float), name='blobs') labeled = ndi.label(blobs)[0] viewer.add_labels(labeled, name='blob ID') animation = Animation(viewer) viewer.update_console({'animation': animation}) animation.capture_keyframe() viewer.camera.zoom = 0.2 animation.capture_keyframe() viewer.camera.zoom = 10.0 viewer.camera.center = (0, 40.0, 10.0) animation.capture_keyframe() viewer.dims.current_step = (60, 0, 0) animation.capture_keyframe(steps=60) viewer.dims.current_step = (0, 0, 0) animation.capture_keyframe(steps=60) viewer.reset_view() animation.capture_keyframe()
""" Layers ====== Display multiple image layers using the add_image API and then reorder them using the layers swap method and remove one """ from skimage import data from skimage.color import rgb2gray import numpy as np import napari # create the viewer with several image layers viewer = napari.view_image(rgb2gray(data.astronaut()), name='astronaut') viewer.add_image(data.camera(), name='photographer') viewer.add_image(data.coins(), name='coins') viewer.add_image(data.moon(), name='moon') viewer.add_image(np.random.random((512, 512)), name='random') viewer.add_image(data.binary_blobs(length=512, volume_fraction=0.2, n_dim=2), name='blobs') viewer.grid.enabled = True if __name__ == '__main__': napari.run()