def main(): """Load image, apply sobel (to get x/y gradients), plot the results.""" img = data.camera() sobel_y = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]]) sobel_x = np.rot90(sobel_y) # rotates counter-clockwise # apply x/y sobel filter to get x/y gradients img_sx = signal.correlate(img, sobel_x, mode="same") img_sy = signal.correlate(img, sobel_y, mode="same") # combine x/y gradients to gradient magnitude # scikit-image's implementation divides by sqrt(2), not sure why img_s = np.sqrt(img_sx ** 2 + img_sy ** 2) / np.sqrt(2) # create binarized image threshold = np.average(img_s) img_s_bin = np.zeros(img_s.shape) img_s_bin[img_s > threshold] = 1 # generate ground truth (scikit-image method) ground_truth = skifilters.sobel(data.camera()) # plot util.plot_images_grayscale( [img, img_sx, img_sy, img_s, img_s_bin, ground_truth], [ "Image", "Sobel (x)", "Sobel (y)", "Sobel (magnitude)", "Sobel (magnitude, binarized)", "Sobel (Ground Truth)", ], )
def test_li_camera_image(): image = skimage.img_as_ubyte(data.camera()) threshold = threshold_li(image) ce_actual = _cross_entropy(image, threshold) assert 62 < threshold_li(image) < 63 assert ce_actual < _cross_entropy(image, threshold + 1) assert ce_actual < _cross_entropy(image, threshold - 1)
def test_rect_tool(): img = data.camera() viewer = ImageViewer(img) tool = RectangleTool(viewer.ax, maxdist=10) tool.extents = (100, 150, 100, 150) assert_equal(tool.corners, ((100, 150, 150, 100), (100, 100, 150, 150))) assert_equal(tool.extents, (100, 150, 100, 150)) assert_equal(tool.edge_centers, ((100, 125.0, 150, 125.0), (125.0, 100, 125.0, 150))) assert_equal(tool.geometry, (100, 150, 100, 150)) # grab a corner and move it grab = create_mouse_event(viewer.ax, xdata=100, ydata=100) tool.press(grab) move = create_mouse_event(viewer.ax, xdata=120, ydata=120) tool.onmove(move) tool.release(move) assert_equal(tool.geometry, [120, 150, 120, 150]) # create a new line new = create_mouse_event(viewer.ax, xdata=10, ydata=10) tool.press(new) move = create_mouse_event(viewer.ax, xdata=100, ydata=100) tool.onmove(move) tool.release(move) assert_equal(tool.geometry, [10, 100, 10, 100])
def test_image_stack_correlation(): num_levels = 1 num_bufs = 2 # must be even coins = data.camera() coins_stack = [] for i in range(4): coins_stack.append(coins) coins_mesh = np.zeros_like(coins) coins_mesh[coins < 30] = 1 coins_mesh[coins > 50] = 2 g2, lag_steps = corr.multi_tau_auto_corr(num_levels, num_bufs, coins_mesh, coins_stack) assert np.all(g2[:, 0], axis=0) assert np.all(g2[:, 1], axis=0) num_buf = 5 # check the number of buffers are even assert_raises(ValueError, lambda: corr.multi_tau_auto_corr(num_levels, num_buf, coins_mesh, coins_stack)) # check image shape and labels shape are equal # assert_raises(ValueError, # lambda : corr.multi_tau_auto_corr(num_levels, num_bufs, # indices, coins_stack)) # check the number of pixels is zero mesh = np.zeros_like(coins) assert_raises(ValueError, lambda: corr.multi_tau_auto_corr(num_levels, num_bufs, mesh, coins_stack))
def test_masked_registration_random_masks_non_equal_sizes(): """masked_register_translation should be able to register translations between images that are not the same size even with random masks.""" # See random number generator for reproducible results np.random.seed(23) reference_image = camera() shift = (-7, 12) shifted = np.real(np.fft.ifft2(fourier_shift( np.fft.fft2(reference_image), shift))) # Crop the shifted image shifted = shifted[64:-64, 64:-64] # Random masks with 75% of pixels being valid ref_mask = np.random.choice( [True, False], reference_image.shape, p=[3 / 4, 1 / 4]) shifted_mask = np.random.choice( [True, False], shifted.shape, p=[3 / 4, 1 / 4]) measured_shift = masked_register_translation( reference_image, shifted, np.ones_like(ref_mask), np.ones_like(shifted_mask)) assert_equal(measured_shift, -np.array(shift))
def test_rect_tool(): img = data.camera() viewer = ImageViewer(img) tool = RectangleTool(viewer, maxdist=10) tool.extents = (100, 150, 100, 150) assert_equal(tool.corners, ((100, 150, 150, 100), (100, 100, 150, 150))) assert_equal(tool.extents, (100, 150, 100, 150)) assert_equal(tool.edge_centers, ((100, 125.0, 150, 125.0), (125.0, 100, 125.0, 150))) assert_equal(tool.geometry, (100, 150, 100, 150)) # grab a corner and move it do_event(viewer, 'mouse_press', xdata=100, ydata=100) do_event(viewer, 'move', xdata=120, ydata=120) do_event(viewer, 'mouse_release') # assert_equal(tool.geometry, [120, 150, 120, 150]) # create a new line do_event(viewer, 'mouse_press', xdata=10, ydata=10) do_event(viewer, 'move', xdata=100, ydata=100) do_event(viewer, 'mouse_release') assert_equal(tool.geometry, [10, 100, 10, 100])
def run(): # img = np.ones((8,8)) img = data.camera() # sp.misc.imsave('woop_orig.png', img) # img_f = np.fft.fft2(img) # print img.shape # print img_f.shape # sigma = 4 # img_f = fft2_deriv(img_f, sigma, 3, 3) # img = np.fft.ifft2(img_f).real # print np.max(img), np.min(img) # sp.misc.imsave('woop.png', img) # img = data.camera() # img = gaussian_filter(img, sigma) # sp.misc.imsave('woop_gaussian_filter.png', img) # return # y,x = np.mgrid[-50:51,-50:51] # img = exp(- (x**2 + y**2)/(2.*1**2)) # print img # print img_f # sp.misc.imsave('img_s.png', img) # sp.misc.imsave('img_f.png', img_f.real) # sp.misc.imsave('img_f_.png', img_f.imag) # img = sp.misc.imread('img.png',flatten=True) jets = jet(img)
def test_compare_8bit_vs_16bit(): # filters applied on 8-bit image ore 16-bit image (having only real 8-bit # of dynamic) should be identical image8 = util.img_as_ubyte(data.camera()) image16 = image8.astype(np.uint16) assert_equal(image8, image16) methods = [ "autolevel", "bottomhat", "equalize", "gradient", "maximum", "mean", "subtract_mean", "median", "minimum", "modal", "enhance_contrast", "pop", "threshold", "tophat", ] for method in methods: func = getattr(rank, method) f8 = func(image8, disk(3)) f16 = func(image16, disk(3)) assert_equal(f8, f16)
def setUp(self): self.seed = 1234 self.BATCH_SIZE = 10 self.num_batches = 1000 np.random.seed(self.seed) ### 2D initialiazations cam = data.camera() self.cam = cam[np.newaxis, np.newaxis, :, :] self.cam_left = self.cam[:,:,:,::-1] self.cam_updown = self.cam[:,:,::-1,:] self.cam_updown_left = self.cam[:,:,::-1,::-1] self.x_2D = self.cam self.y_2D = self.cam ### 3D initialiazations self.cam_3D = np.random.rand(20,20,20)[np.newaxis, np.newaxis, :, :, :] self.cam_3D_left = self.cam_3D[:,:,:,::-1,:] self.cam_3D_updown = self.cam_3D[:,:,::-1,:,:] self.cam_3D_updown_left = self.cam_3D[:,:,::-1,::-1,:] self.cam_3D_left_z = self.cam_3D_left[:,:,:,:,::-1] self.cam_3D_updown_z = self.cam_3D_updown[:,:,:,:,::-1] self.cam_3D_updown_left_z = self.cam_3D_updown_left[:,:,:,:,::-1] self.cam_3D_z = self.cam_3D[:,:,:,:,::-1] self.x_3D = self.cam_3D self.y_3D = self.cam_3D
def main(): """Load template image (needle) and the large example image (haystack), generate matching score per pixel, plot the results.""" img_haystack = skiutil.img_as_float(data.camera()) # the image in which to search img_needle = img_haystack[140:190, 220:270] # the template to search for img_sad = np.zeros(img_haystack.shape) # score image height_h, width_h = img_haystack.shape height_n, width_n = img_needle.shape # calculate score for each pixel # stop iterating over pixels when the whole template cannot any more (i.e. stop # at bottom and right border) for y in range(height_h - height_n): for x in range(width_h - width_n): patch = img_haystack[y:y+height_n, x:x+width_n] img_sad[y, x] = sad(img_needle, patch) img_sad = img_sad / np.max(img_sad) # add highest score to bottom and right borders img_sad[height_h-height_n:, :] = np.max(img_sad[0:height_h, 0:width_h]) img_sad[:, width_h-width_n:] = np.max(img_sad[0:height_h, 0:width_h]) # plot results util.plot_images_grayscale( [img_haystack, img_needle, img_sad], ["Image", "Image (Search Template)", "Matching (darkest = best match)"] )
def test_crop(): image = data.camera() viewer = ImageViewer(image) c = Crop() viewer += c c.crop((0, 100, 0, 100)) assert_equal(viewer.image.shape, (101, 101))
def test_isodata_camera_image(): camera = skimage.img_as_ubyte(data.camera()) threshold = threshold_isodata(camera) assert np.floor((camera[camera <= threshold].mean() + camera[camera > threshold].mean()) / 2.0) == threshold assert threshold == 87 assert threshold_isodata(camera, return_all=True) == [87]
def test_threshold_minimum(): camera = skimage.img_as_ubyte(data.camera()) threshold = threshold_minimum(camera) assert_equal(threshold, 76) astronaut = skimage.img_as_ubyte(data.astronaut()) threshold = threshold_minimum(astronaut) assert_equal(threshold, 114)
def test_is_rgb(): color = data.lena() gray = data.camera() assert is_rgb(color) assert not is_gray(color) assert is_gray(gray) assert not is_gray(color)
def test_measure(): image = data.camera() viewer = ImageViewer(image) m = Measure() viewer += m m.line_changed([(0, 0), (10, 10)]) assert_equal(str(m._length.text), '14.1') assert_equal(str(m._angle.text[:5]), '135.0')
def test_poisson(): seed = 42 data = camera() # 512x512 grayscale uint8 cam_noisy = random_noise(data, mode='poisson', seed=seed) cam_noisy2 = random_noise(data, mode='poisson', seed=seed, clip=False) np.random.seed(seed=seed) expected = np.random.poisson(img_as_float(data) * 256) / 256. assert_allclose(cam_noisy, np.clip(expected, 0., 1.)) assert_allclose(cam_noisy2, expected)
def test_canny(): image = data.camera() viewer = ImageViewer(image) c = CannyPlugin() viewer += c canny_edges = viewer.show(False) viewer.close() edges = canny_edges[0][0] assert edges.sum() == 2852
def test_correlation(): reference_image = np.fft.fftn(camera()) shift = (-7, 12) shifted_image = fourier_shift(reference_image, shift) # pixel precision result, error, diffphase = register_translation(reference_image, shifted_image, space="fourier") assert_allclose(result[:2], -np.array(shift))
def test_subpixel_precision(): reference_image = np.fft.fftn(camera()) subpixel_shift = (-2.4, 1.32) shifted_image = fourier_shift(reference_image, subpixel_shift) # subpixel precision result, error, diffphase = register_translation(reference_image, shifted_image, 100, space="fourier") assert_allclose(result[:2], -np.array(subpixel_shift), atol=0.05)
def test_real_input(): reference_image = camera() subpixel_shift = (-2.4, 1.32) shifted_image = fourier_shift(np.fft.fftn(reference_image), subpixel_shift) shifted_image = np.fft.ifftn(shifted_image) # subpixel precision result, error, diffphase = register_translation(reference_image, shifted_image, 100) assert_allclose(result[:2], -np.array(subpixel_shift), atol=0.05)
def test_line_profile(): """ Test a line profile using an ndim=2 image""" plugin = setup_line_profile(data.camera()) line_image, scan_data = plugin.output() for inp in [line_image.nonzero()[0].size, line_image.sum() / line_image.max(), scan_data.size]: assert_equal(inp, 172) assert_equal(line_image.shape, (512, 512)) assert_allclose(scan_data.max(), 0.9139, rtol=1e-3) assert_allclose(scan_data.mean(), 0.2828, rtol=1e-3)
def test_compare_autolevels(): # compare autolevel and percentile autolevel with p0=0.0 and p1=1.0 # should returns the same arrays image = util.img_as_ubyte(data.camera()) selem = disk(20) loc_autolevel = rank.autolevel(image, selem=selem) loc_perc_autolevel = rank.autolevel_percentile(image, selem=selem, p0=0.0, p1=1.0) assert_equal(loc_autolevel, loc_perc_autolevel)
def test_size_one_dimension_input(): # take a strip of the input image reference_image = np.fft.fftn(camera()[:, 15]).reshape((-1, 1)) subpixel_shift = (-2.4, 4) shifted_image = fourier_shift(reference_image, subpixel_shift) # subpixel precision result, error, diffphase = register_translation(reference_image, shifted_image, 100, space="fourier") assert_allclose(result[:2], -np.array((-2.4, 0)), atol=0.05)
def test_compare_autolevels_16bit(): # compare autolevel(16-bit) and percentile autolevel(16-bit) with p0=0.0 # and p1=1.0 should returns the same arrays image = data.camera().astype(np.uint16) * 4 selem = disk(20) loc_autolevel = rank.autolevel(image, selem=selem) loc_perc_autolevel = rank.autolevel_percentile(image, selem=selem, p0=0.0, p1=1.0) assert_equal(loc_autolevel, loc_perc_autolevel)
def test_compare_8bit_vs_16bit(self, method): # filters applied on 8-bit image ore 16-bit image (having only real 8-bit # of dynamic) should be identical image8 = util.img_as_ubyte(data.camera())[::2, ::2] image16 = image8.astype(np.uint16) assert_equal(image8, image16) func = getattr(rank, method) f8 = func(image8, disk(3)) f16 = func(image16, disk(3)) assert_equal(f8, f16)
def test_cross_correlate_masked_autocorrelation_trivial_masks(): """Masked normalized cross-correlation between identical arrays should reduce to an autocorrelation even with random masks.""" # See random number generator for reproducible results np.random.seed(23) arr1 = camera() arr2 = camera() # Random masks with 75% of pixels being valid m1 = np.random.choice([True, False], arr1.shape, p=[3 / 4, 1 / 4]) m2 = np.random.choice([True, False], arr2.shape, p=[3 / 4, 1 / 4]) xcorr = cross_correlate_masked(arr1, arr1, m1, m1, axes=(0, 1), mode='same', overlap_ratio=0).real max_index = np.unravel_index(np.argmax(xcorr), xcorr.shape) # Autocorrelation should have maximum in center of array testing.assert_almost_equal(xcorr.max(), 1) testing.assert_array_equal(max_index, np.array(arr1.shape) / 2)
def test_pepper(): seed = 42 cam = img_as_float(camera()) cam_noisy = random_noise(cam, seed=seed, mode="pepper", d=0.15) peppermask = cam != cam_noisy # Ensure all changes are to 1.0 assert_allclose(cam_noisy[peppermask], np.zeros(peppermask.sum())) # Ensure approximately correct amount of noise was added proportion = float(peppermask.sum()) / (cam.shape[0] * cam.shape[1]) assert 0.11 < proportion <= 0.18
def test_threshold_minimum(): camera = skimage.img_as_ubyte(data.camera()) threshold = threshold_minimum(camera) assert threshold == 76 threshold = threshold_minimum(camera, bias='max') assert threshold == 77 astronaut = skimage.img_as_ubyte(data.astronaut()) threshold = threshold_minimum(astronaut) assert threshold == 117
def test_salt(): seed = 42 cam = img_as_float(camera()) cam_noisy = random_noise(cam, seed=seed, mode='salt', amount=0.15) saltmask = cam != cam_noisy # Ensure all changes are to 1.0 assert_allclose(cam_noisy[saltmask], np.ones(saltmask.sum())) # Ensure approximately correct amount of noise was added proportion = float(saltmask.sum()) / (cam.shape[0] * cam.shape[1]) assert 0.11 < proportion <= 0.15
def test_percentile_median(): # check that percentile p0 = 0.5 is identical to local median img = data.camera() img16 = img.astype(np.uint16) selem = disk(15) # check for 8bit img_p0 = rank.percentile(img, selem=selem, p0=.5) img_max = rank.median(img, selem=selem) assert_equal(img_p0, img_max) # check for 16bit img_p0 = rank.percentile(img16, selem=selem, p0=.5) img_max = rank.median(img16, selem=selem) assert_equal(img_p0, img_max)
def test_otsu_camera_image(): camera = skimage.img_as_ubyte(data.camera()) assert 86 < threshold_otsu(camera) < 88
def run_all_profiles(): print("running profiler...") spokelengths = [512] nspokes = [405] ncoils = [15] im_sizes = [256] batch_sizes = [1] devices = [torch.device("cpu")] sparse_mat_flags = [False, True] toep_flags = [False, True] oversamp_factors = [2] sizes_3d = [None] if torch.cuda.is_available(): devices.append(torch.device("cuda")) params = [(sl, ns, nc, ims, bs, dev, smf, tf, s3, of) for sl in spokelengths for ns in nspokes for nc in ncoils for ims in im_sizes for bs in batch_sizes for dev in devices for smf in sparse_mat_flags for tf in toep_flags for s3 in sizes_3d for of in oversamp_factors] for ( spokelength, nspoke, ncoil, im_size, batch_size, device, sparse_mat_flag, toep_flag, size_3d, oversamp_factor, ) in params: if sparse_mat_flag and toep_flag: continue # create an example to run on image = np.array(Image.fromarray(camera()).resize((256, 256))) image = image.astype(np.complex) im_size = image.shape image = (torch.tensor( image, dtype=torch.complex128).unsqueeze(0).unsqueeze(0).repeat( batch_size, 1, 1, 1)) if size_3d is not None: image = image.unsqueeze(2).repeat(1, 1, size_3d, 1, 1) im_size = (size_3d, ) + im_size # create k-space trajectory ga = np.deg2rad(180 / ((1 + np.sqrt(5)) / 2)) kx = np.zeros(shape=(spokelength, nspoke)) ky = np.zeros(shape=(spokelength, nspoke)) ky[:, 0] = np.linspace(-np.pi, np.pi, spokelength) for i in range(1, nspoke): kx[:, i] = np.cos(ga) * kx[:, i - 1] - np.sin(ga) * ky[:, i - 1] ky[:, i] = np.sin(ga) * kx[:, i - 1] + np.cos(ga) * ky[:, i - 1] ky = np.transpose(ky) kx = np.transpose(kx) ktraj = torch.tensor(np.stack((ky.flatten(), kx.flatten()), axis=0)) if size_3d is not None: zlocs = np.linspace(-np.pi, np.pi, size_3d) kz = [] for zloc in zlocs: kz.append(torch.ones(ktraj.shape[1]) * zloc) ktraj = torch.cat( (ktraj.repeat(1, size_3d), torch.cat(kz).unsqueeze(0))) smap_sz = (batch_size, ncoil) + im_size smap = torch.ones(*smap_sz, dtype=torch.complex128) print( f"im_size: {im_size}, " f"spokelength: {spokelength}, num spokes: {nspoke}, ncoil: {ncoil}, " f"batch_size: {batch_size}, device: {device}, " f"sparse_mats: {sparse_mat_flag}, toep_mat: {toep_flag}, " f"size_3d: {size_3d}") grid_size = tuple([int(ims * oversamp_factor) for ims in im_size]) profile_torchkbnufft( image, ktraj, smap, im_size, grid_size, device=device, sparse_mats_flag=sparse_mat_flag, toep_flag=toep_flag, )
__author__ = 'tomas' import skimage.data as skidat import matplotlib.pyplot as plt import numpy as np import markov_random_field as mrf #- - - - - - - - - - - - - - - - - - - # loading the image img = skidat.camera() n_rows, n_cols = img.shape # seed points seeds_1 = (np.array([90, 252, 394]), np.array([220, 212, 108])) # first class seeds_2 = (np.array([68, 265, 490]), np.array([92, 493, 242])) # second class seeds = np.zeros((n_rows, n_cols), dtype=np.uint8) seeds[seeds_1] = 1 seeds[seeds_2] = 2 # plt.figure() # plt.imshow(seeds, interpolation='nearest') # plt.show() # plt.figure() # plt.imshow(img, 'gray') # plt.show() # run(img, seeds)
ax.scatter(x=cars['weight'], y=cars['mpg'], label=origin) for origin, data in cars.groupby('origin name'): ax.scatter(x=data['weight'], y=data['mpg'], label=origin) fig, ax = plt.subplots() for origin, data in cars.groupby('origin name'): ax.scatter(x=data['weight'], y=data['mpg'], label=origin) ax.legend() ax.legend_ ax.legend_.draggable ax.legend_.draggable(True) colordat = pd.read_csv('colormap_data.csv') colordat.head() get_ipython().magic('pinfo sns.stripplot') get_ipython().magic('pinfo sns.stripplot') colordat['error'] = colordat['user_value'] - colordat['real_value'] sns.stripplot(data=colordat, x='colormap', y='error', hue='colormap') sns.stripplot(data=colordat, x='colormap', y='error', hue='colormap', jitter=True) from skimage import data cam = data.camera() plt.imshow(cam) plt.imshow(cam, cmap='viridis') cars.head() cars['color'] = (cars['year'] - cars['year'].min()) / (cars['year'].max() - cars['year'].min()) cars['colorvalue'] = (cars['year'] - cars['year'].min()) / (cars['year'].max() - cars['year'].min()) cars['color'] = cars['colorvalue'].apply(plt.cm.viridis) fig, ax = plt.subplots() ax.scatter(x=cars['weight'], y=cars['mpg'], c=cars['color'])
def test_camera(): """ Test that "camera" image can be loaded. """ cameraman = data.camera() assert_equal(cameraman.ndim, 2)
def test_local_even_block_size_error(): img = data.camera() with testing.raises(ValueError): threshold_local(img, block_size=4)
def main(_): from skimage import data, transform, img_as_float import matplotlib.pyplot as plt color = False if color: image = data.astronaut() else: # [h,w] -> [h,w,1] image = data.camera() image = np.expand_dims(image, axis=-1) # image = transform.resize(image, output_shape=[128, 128]) img = img_as_float(image) print(img.shape) rows, cols, channels = img.shape noise = np.ones_like(img) * 0.2 * (img.max() - img.min()) noise[np.random.random(size=noise.shape) > 0.5] *= -1 img_noise = img + noise img_noise = np.clip(img_noise, a_min=0, a_max=1) plt.figure() plt.subplot(121) if color: plt.imshow(img) plt.subplot(122) plt.imshow(img_noise) else: plt.imshow(img[:,:,0], cmap='gray') plt.subplot(122) plt.imshow(img_noise[:,:,0], cmap='gray') plt.show() ## TF CALC START image1 = tf.placeholder(tf.float32, shape=[rows, cols, channels]) image2 = tf.placeholder(tf.float32, shape=[rows, cols, channels]) def image_to_4d(image): image = tf.expand_dims(image, 0) return image image4d_1 = image_to_4d(image1) image4d_2 = image_to_4d(image2) print(img.min(), img.max(), img_noise.min(), img_noise.max()) ssim_index = ssim(image4d_1, image4d_2) #, min_val=0.0, max_val=1.0) msssim_index = ms_ssim(image4d_1, image4d_2) #, min_val=0.0, max_val=1.0) # img *= 255 # img_noise *= 255 # ssim_index = ssim(image4d_1, image4d_2, min_val=0.0, max_val=255.0) # msssim_index = ms_ssim(image4d_1, image4d_2, min_val=0.0, max_val=255.0) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) tf_ssim_none = sess.run(ssim_index, feed_dict={image1: img, image2: img}) tf_ssim_noise = sess.run(ssim_index, feed_dict={image1: img, image2: img_noise}) tf_msssim_none = sess.run(msssim_index, feed_dict={image1: img, image2: img}) tf_msssim_noise = sess.run(msssim_index, feed_dict={image1: img, image2: img_noise}) ###TF CALC END print('tf_ssim_none', tf_ssim_none) print('tf_ssim_noise', tf_ssim_noise) print('tf_msssim_none', tf_msssim_none) print('tf_msssim_noise', tf_msssim_noise)
from skimage import data from skimage.feature import canny from skimage.viewer import ImageViewer from skimage.viewer.widgets import Slider from skimage.viewer.plugins.overlayplugin import OverlayPlugin plugin = OverlayPlugin(image_filter=canny) plugin += Slider('sigma', 0, 5) plugin += Slider('low threshold', 0, 255, value_type='int') plugin += Slider('high threshold', 0, 255, value_type='int') viewer = ImageViewer(data.camera()) viewer += plugin viewer.show()
def get_one_sample_image(): from skimage import data image = data.camera() image = cv2.resize(image, (100, 100)) return image
#-*-coding:utf-8-*- from skimage import transform, data import matplotlib.pyplot as plt img = data.camera() print(img.shape) #图片原始大小 img1 = transform.rotate(img, 60) #旋转60度,不改变大小 print(img1.shape) img2 = transform.rotate(img, 30, resize=True) #旋转30度,同时改变大小 print(img2.shape) plt.subplot(121) plt.title('rotate 60') plt.imshow(img1, plt.cm.gray) plt.subplot(122) plt.title('rotate 30') plt.imshow(img2, plt.cm.gray) plt.show()
plt.subplot(122) plt.imshow(hsobel_text, cmap='jet', interpolation='nearest') # plt.axis('off') plt.tight_layout() plt.show() # ## nonlocal filter # In[14]: from skimage import data, exposure import matplotlib.pyplot as plt camera = data.camera() camera_equalized = exposure.equalize_hist(camera) plt.figure(figsize=(7, 3)) plt.subplot(121) plt.imshow(camera, cmap='gray', interpolation='nearest') plt.axis('off') plt.subplot(122) plt.imshow(camera_equalized, cmap='gray', interpolation='nearest') plt.axis('off') plt.tight_layout() plt.show()
import matplotlib.pyplot as plt from skimage import data from skimage.filters import threshold_otsu ###################################################################### # We illustrate how to apply one of these thresholding algorithms. # Otsu's method [2]_ calculates an "optimal" threshold (marked by a red line in the # histogram below) by maximizing the variance between two classes of pixels, # which are separated by the threshold. Equivalently, this threshold minimizes # the intra-class variance. # # .. [2] https://en.wikipedia.org/wiki/Otsu's_method # image = data.camera() thresh = threshold_otsu(image) binary = image > thresh fig, axes = plt.subplots(ncols=3, figsize=(8, 2.5)) ax = axes.ravel() ax[0] = plt.subplot(1, 3, 1) ax[1] = plt.subplot(1, 3, 2) ax[2] = plt.subplot(1, 3, 3, sharex=ax[0], sharey=ax[0]) ax[0].imshow(image, cmap=plt.cm.gray) ax[0].set_title('Original') ax[0].axis('off') ax[1].hist(image.ravel(), bins=256) ax[1].set_title('Histogram')
def img(): image = data.camera() return image
def test_bimodal_multiotsu_hist(): image = data.camera() thr_otsu = threshold_otsu(image) thr_multi = threshold_multiotsu(image, classes=2) assert thr_otsu == thr_multi
from __future__ import print_function import Image import AlignLib from skimage import data import numpy as np import matplotlib.pyplot as plt from collections import namedtuple import AlignCrop import SpectrumImage Rectangle = namedtuple('Rectangle', 'xmin, ymin, xmax, ymax') p1shaped = np.reshape(data.camera(), (1, 1, 1, 512, 512)) p1 = Image.Image(data.camera()) p2 = Image.Image(data.coins()) p3 = Image.Image(data.chelsea()[:, :, 0]) p4 = Image.Image(data.astronaut()[:, :, 0]) #print(np.shape(p1.data), np.shape(p2.data), np.shape(p3.data), np.shape(p4.data)) model, plotter = AlignLib.Align((p1, p2, p3, p4)) offsets = model.offsets #print(offsets) ################Will's thing #r1 = Rectangle(offsets[0, 0], offsets[1,0], p1.size[1]+offsets[0,0], p1.size[0]+offsets[1,0]) #r2 = Rectangle(offsets[0, 1], offsets[1,1], p2.size[1]+offsets[0,1], p2.size[0]+offsets[1,1]) #def FindRectangleIntersectionWillsWay(r1, r2): # if (r1.xmax<r2.xmin or r2.xmax<r1.xmin or r1.ymax<r2.ymin or r2.ymax<r1.ymin): # raise ValueError("No intersection! Fix it!")
def test_yen_camera_image(): camera = skimage.img_as_ubyte(data.camera()) assert 197 < threshold_yen(camera) < 199
sys.path.append('../../../optimaltransport') import numpy as np import matplotlib.pyplot as plt from skimage import data, img_as_float from optrans.utils import signal_to_pdf from optrans.continuous import RadonCDT """ Compute the forward and inverse Radon-CDT of a sample image. Liam Cattell -- January 2018 """ # Load a sample image img = img_as_float(data.camera()[::2, ::2]) # Select two patches to be our sample images img0 = img[50:162, 70:134] img1 = img[32:144, 64:128] # Convert images to PDFs img0 = signal_to_pdf(img0, sigma=1.) img1 = signal_to_pdf(img1, sigma=1.) # Compute Radon-CDT of img1 w.r.t img0 theta = np.arange(0, 179, 2) radoncdt = RadonCDT(theta=theta) img1_hat = radoncdt.forward(img0, img1) # Apply transport map in order to reconstruct images
from skimage import data from scipy import misc from scipy import signal as sg import matplotlib.pyplot as plt import numpy as np cameraIMG = data.camera() fig = plt.figure(figsize=(10, 10), dpi=100) a = fig.add_subplot(1, 2, 1) plt.imshow(cameraIMG, cmap=plt.cm.gray) a.set_title('Original') plt.tight_layout() plt.show() from scipy import signal as sg media3 = [[1. / 9., 1. / 9., 1. / 9.], [1. / 9., 1. / 9., 1. / 9.], [1. / 9., 1. / 9., 1. / 9.]] c_media = sg.convolve(cameraIMG, media3, "valid") fig = plt.figure(figsize=(10, 10), dpi=100) a = fig.add_subplot(1, 2, 2) plt.imshow(c_media, cmap=plt.cm.gray) a.set_title('Media 3x3') plt.show() row, col = cameraIMG.shape ch = 1 mean = 0
import basic_grayscale_transformation import matplotlib.pyplot as plt import skimage.data as sk_image if __name__ == '__main__': source_image = sk_image.camera() reverse_image = basic_grayscale_transformation.image_reverse(source_image) plt.subplot(1, 2, 1) plt.title("before") plt.imshow(source_image, cmap="gray") plt.subplot(1, 2, 2) plt.title("after") plt.imshow(reverse_image, cmap="gray") plt.show()
def test_thresholds_dask_compatibility(thresholding, lower, upper): pytest.importorskip('dask', reason="dask python library is not installed") import dask.array as da dask_camera = da.from_array(data.camera(), chunks=(256, 256)) assert lower < float(thresholding(dask_camera)) < upper
plt.imshow(labels) #%% from PIL import Image image = Image.open('C:/Users/horsepurve/Dropbox/UBR/Analysis/TopoSeg/RW/random_walker_matlab_code/training_axial_crop_pat0_77.jpg') plt.imshow(image) #%% # try chan vese method import numpy as np import matplotlib.pyplot as plt from skimage import data, img_as_float from skimage.segmentation import chan_vese image = img_as_float(data.camera()) image = score_map_1 # Feel free to play around with the parameters to see how they impact the result cv = chan_vese(image, mu=0.25, lambda1=1, lambda2=1, tol=1e-3, max_iter=200, dt=0.5, init_level_set="checkerboard", extended_output=True) fig, axes = plt.subplots(2, 2, figsize=(8, 8)) ax = axes.flatten() ax[0].imshow(image, cmap="gray") ax[0].set_axis_off() ax[0].set_title("Original Image", fontsize=12) ax[1].imshow(cv[0], cmap="gray") ax[1].set_axis_off() title = "Chan-Vese segmentation - {} iterations".format(len(cv[2]))
from skimage.util import img_as_float 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;
fig, (ax0, ax1, ax2) = plt.subplots(nrows=1, ncols=3, figsize=(10, 4)) img0 = ax0.imshow(noise_mask, cmap='gray') ax0.set_title("Object") ax1.imshow(img, cmap='gray') ax1.set_title("Noisy image") ax2.imshow(entr_img, cmap='viridis') ax2.set_title("Local entropy") fig.tight_layout() ###################################################################### # Texture detection # ================= image = img_as_ubyte(data.camera()) fig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(12, 4), sharex=True, sharey=True) img0 = ax0.imshow(image, cmap=plt.cm.gray) ax0.set_title("Image") ax0.axis("off") fig.colorbar(img0, ax=ax0) img1 = ax1.imshow(entropy(image, disk(5)), cmap='gray') ax1.set_title("Entropy") ax1.axis("off") fig.colorbar(img1, ax=ax1)
def test_adaptive_even_block_size_error(): img = data.camera() assert_raises(ValueError, threshold_adaptive, img, block_size=4)
ca = np.floor(cs).astype(np.uint32) np.clip(ra, 0, h - 1.5, out=ra) np.clip(ca, 0, w - 1.5, out=ca) rs -= ra cs -= ca outcol = out.reshape((-1, h * k, w * k)) imgcol = img.reshape((-1, h, w)) for i, o in zip(imgcol, outcol): _resize(i, k, ra, rs, 1 - rs, ca, cs, 1 - cs, o) return out if __name__ == '__main__': from time import time from skimage.data import astronaut, camera img = astronaut().transpose(2, 0, 1).astype(np.float32) img = camera().astype(np.float32) img = np.array([[1, 2], [3, 4]], dtype=np.float32) # firs time to jit resize(img, 4) start = time() for i in range(10): rst1 = resize(img, 2) print('mine v1', time() - start) import cv2 start = time() for i in range(10): rst2 = cv2.resize(img, (4, 4)) print('cv', time() - start)
def test_li_camera_image(): camera = skimage.img_as_ubyte(data.camera()) assert 63 < threshold_li(camera) < 65
from functools import partial import numpy as np from skimage import img_as_float, img_as_uint from skimage import color, data, filters from skimage.color.adapt_rgb import adapt_rgb, each_channel, hsv_value from skimage._shared._warnings import expected_warnings # Down-sample image for quicker testing. COLOR_IMAGE = data.astronaut()[::5, ::5] GRAY_IMAGE = data.camera()[::5, ::5] SIGMA = 3 smooth = partial(filters.gaussian, sigma=SIGMA) assert_allclose = partial(np.testing.assert_allclose, atol=1e-8) @adapt_rgb(each_channel) def edges_each(image): return filters.sobel(image) @adapt_rgb(each_channel) def smooth_each(image, sigma): return filters.gaussian(image, sigma) @adapt_rgb(hsv_value) def edges_hsv(image): return filters.sobel(image)
def test_all_negative_image(): im = np.array([-128, -1], dtype=np.int8) frequencies, bin_centers = exposure.histogram(im) assert_array_equal(bin_centers, np.arange(-128, 0)) assert frequencies[0] == 1 assert frequencies[-1] == 1 assert_array_equal(frequencies[1:-1], 0) # Test histogram equalization # =========================== np.random.seed(0) test_img_int = data.camera() # squeeze image intensities to lower image contrast test_img = skimage.img_as_float(test_img_int) test_img = exposure.rescale_intensity(test_img / 5. + 100) def test_equalize_uint8_approx(): """Check integer bins used for uint8 images.""" img_eq0 = exposure.equalize_hist(test_img_int) img_eq1 = exposure.equalize_hist(test_img_int, nbins=3) np.testing.assert_allclose(img_eq0, img_eq1) def test_equalize_ubyte(): with expected_warnings(['precision loss']): img = skimage.img_as_ubyte(test_img)
import numpy as np from skimage import color, data, restoration import numpy as np import numpy.random as npr from scipy.signal import convolve2d import helper camera = color.rgb2gray(data.camera()) camera = helper.get_image('cameraman') from scipy.signal import convolve2d psf = np.ones((5, 5)) / 25 camera = convolve2d(camera, psf, 'same') camera += 0.1 * camera.std() * np.random.standard_normal(camera.shape) deconvolved = restoration.richardson_lucy(camera, psf, 5) helper.show_images({'deconv': deconvolved})
"""This is a callback that update the current properties on the Shapes layer when the label menu selection changes """ selected_label = event.value current_properties = shapes_layer.current_properties current_properties[label_property] = np.asarray([selected_label]) shapes_layer.current_properties = current_properties label_menu.changed.connect(label_changed) return label_widget # create a stack with the camera image shifted in each slice n_slices = 5 base_image = data.camera() image = np.zeros((n_slices, base_image.shape[0], base_image.shape[1]), dtype=base_image.dtype) for slice_idx in range(n_slices): shift = 1 + 10 * slice_idx image[slice_idx, ...] = np.pad(base_image, ((0, 0), (shift, 0)), mode='constant')[:, :-shift] # create a viewer with a fake t+2D image viewer = napari.view_image(image) # create an empty shapes layer initialized with # text set to display the box label text_kwargs = {'text': text_property, 'size': text_size, 'color': text_color} shapes = viewer.add_shapes(face_color='black', property_choices={text_property: box_annotations},