def test_plot_plugin(): viewer = ImageViewer(data.moon()) plugin = PlotPlugin(image_filter=lambda x: x) viewer += plugin assert_equal(viewer.image, data.moon()) plugin._update_original_image(data.coins()) assert_equal(viewer.image, data.coins()) viewer.close()
def test_paint_tool(): img = data.moon() viewer = ImageViewer(img) tool = PaintTool(viewer.ax, img.shape) tool.radius = 10 assert_equal(tool.radius, 10) tool.label = 2 assert_equal(tool.label, 2) assert_equal(tool.shape, img.shape) start = create_mouse_event(viewer.ax, xdata=100, ydata=100) tool.on_mouse_press(start) move = create_mouse_event(viewer.ax, xdata=110, ydata=110) tool.on_move(move) tool.on_mouse_release(move) assert_equal(tool.overlay[tool.overlay == 2].size, 761) tool.label = 5 start = create_mouse_event(viewer.ax, xdata=20, ydata=20) tool.on_mouse_press(start) move = create_mouse_event(viewer.ax, xdata=40, ydata=40) tool.on_move(move) tool.on_mouse_release(move) assert_equal(tool.overlay[tool.overlay == 5].size, 881) assert_equal(tool.overlay[tool.overlay == 2].size, 761) enter = create_mouse_event(viewer.ax, key='enter') tool.on_mouse_press(enter) tool.overlay = tool.overlay * 0 assert_equal(tool.overlay.sum(), 0)
def test_paint_tool(): img = data.moon() viewer = ImageViewer(img) tool = PaintTool(viewer, img.shape) tool.radius = 10 assert_equal(tool.radius, 10) tool.label = 2 assert_equal(tool.label, 2) assert_equal(tool.shape, img.shape) do_event(viewer, 'mouse_press', xdata=100, ydata=100) do_event(viewer, 'move', xdata=110, ydata=110) do_event(viewer, 'mouse_release') assert_equal(tool.overlay[tool.overlay == 2].size, 761) tool.label = 5 do_event(viewer, 'mouse_press', xdata=20, ydata=20) do_event(viewer, 'move', xdata=40, ydata=40) do_event(viewer, 'mouse_release') assert_equal(tool.overlay[tool.overlay == 5].size, 881) assert_equal(tool.overlay[tool.overlay == 2].size, 761) do_event(viewer, 'key_press', key='enter') tool.overlay = tool.overlay * 0 assert_equal(tool.overlay.sum(), 0)
def mono_check(plugin, fmt='png'): """Check the roundtrip behavior for images that support most types. All major input types should be handled. """ img = img_as_ubyte(data.moon()) r1 = roundtrip(img, plugin, fmt) testing.assert_allclose(img, r1) img2 = img > 128 r2 = roundtrip(img2, plugin, fmt) testing.assert_allclose(img2.astype(np.uint8), r2) img3 = img_as_float(img) r3 = roundtrip(img3, plugin, fmt) if r3.dtype.kind == 'f': testing.assert_allclose(img3, r3) else: testing.assert_allclose(r3, img_as_uint(img)) img4 = img_as_int(img) if fmt.lower() in (('tif', 'tiff')): img4 -= 100 r4 = roundtrip(img4, plugin, fmt) testing.assert_allclose(r4, img4) else: r4 = roundtrip(img4, plugin, fmt) testing.assert_allclose(r4, img_as_uint(img4)) img5 = img_as_uint(img) r5 = roundtrip(img5, plugin, fmt) testing.assert_allclose(r5, img5)
def main(): """Load image, apply filters and plot the results.""" img = data.moon() util.plot_images_grayscale( [img, median(img), morphological_edge(img), erosion(img), dilation(img), opening(img), closing(img)], ["Image", "Median", "Morphological Edge", "Erosion", "Dilation", "Opening", "Closing"] )
def test_isodata_moon_image_negative_float(): moon = skimage.img_as_ubyte(data.moon()).astype(np.float64) moon -= 100 assert -14 < threshold_isodata(moon) < -13 thresholds = threshold_isodata(moon, return_all=True) assert_almost_equal(thresholds, [-13.83789062, -12.84179688, -11.84570312, 22.02148438, 23.01757812, 24.01367188, 38.95507812, 39.95117188])
def test_isodata_moon_image(): moon = skimage.img_as_ubyte(data.moon()) threshold = threshold_isodata(moon) assert np.floor((moon[moon <= threshold].mean() + moon[moon > threshold].mean()) / 2.0) == threshold assert threshold == 86 thresholds = threshold_isodata(moon, return_all=True) for threshold in thresholds: assert np.floor((moon[moon <= threshold].mean() + moon[moon > threshold].mean()) / 2.0) == threshold assert_equal(thresholds, [86, 87, 88, 122, 123, 124, 139, 140])
def test_isodata_moon_image_negative_int(): moon = skimage.img_as_ubyte(data.moon()).astype(np.int32) moon -= 100 threshold = threshold_isodata(moon) assert np.floor((moon[moon <= threshold].mean() + moon[moon > threshold].mean()) / 2.0) == threshold assert threshold == -14 thresholds = threshold_isodata(moon, return_all=True) for threshold in thresholds: assert np.floor((moon[moon <= threshold].mean() + moon[moon > threshold].mean()) / 2.0) == threshold assert_equal(thresholds, [-14, -13, -12, 22, 23, 24, 39, 40])
def test_adapthist_scalar(): """Test a scalar uint8 image """ img = skimage.img_as_ubyte(data.moon()) adapted = exposure.equalize_adapthist(img, kernel_size=64, clip_limit=0.02) assert adapted.min() == 0.0 assert adapted.max() == 1.0 assert img.shape == adapted.shape full_scale = skimage.exposure.rescale_intensity(skimage.img_as_float(img)) assert_almost_equal(peak_snr(full_scale, adapted), 102.066, 3) assert_almost_equal(norm_brightness_err(full_scale, adapted), 0.038, 3)
def test_adapthist_scalar(): '''Test a scalar uint8 image ''' img = skimage.img_as_ubyte(data.moon()) adapted = exposure.equalize_adapthist(img, clip_limit=0.02) assert adapted.min() == 0 assert adapted.max() == (1 << 16) - 1 assert img.shape == adapted.shape full_scale = skimage.exposure.rescale_intensity(skimage.img_as_uint(img)) assert_almost_equal = np.testing.assert_almost_equal assert_almost_equal(peak_snr(full_scale, adapted), 101.231, 3) assert_almost_equal(norm_brightness_err(full_scale, adapted), 0.041, 3) return img, adapted
def test_base_tool(): img = data.moon() viewer = ImageViewer(img) tool = CanvasToolBase(viewer) tool.set_visible(False) tool.set_visible(True) do_event(viewer, 'key_press', key='enter') tool.redraw() tool.remove() tool = CanvasToolBase(viewer, useblit=False) tool.redraw()
def test_label_painter(): image = data.camera() moon = data.moon() viewer = ImageViewer(image) lp = LabelPainter() viewer += lp assert_equal(lp.radius, 5) lp.label = 1 assert_equal(str(lp.label), '1') lp.label = 2 assert_equal(str(lp.paint_tool.label), '2') assert_equal(lp.paint_tool.radius, 5) lp._on_new_image(moon) assert_equal(lp.paint_tool.shape, moon.shape)
def test_base_tool(): img = data.moon() viewer = ImageViewer(img) tool = CanvasToolBase(viewer.ax) tool.set_visible(False) tool.set_visible(True) enter = create_mouse_event(viewer.ax, key='enter') tool._on_key_press(enter) tool.redraw() tool.remove() tool = CanvasToolBase(viewer.ax, useblit=False) tool.redraw()
def test_keypoints_censure_moon_image_octagon(): """Verify the actual Censure keypoints and their corresponding scale with the expected values for Octagon filter.""" img = moon() actual_kp_octagon, actual_scale = keypoints_censure(img, 1, 7, 'Octagon', 0.15) expected_kp_octagon = np.array([[ 21, 496], [ 35, 46], [287, 250], [356, 239], [463, 116]]) expected_scale = np.array([3, 4, 2, 2, 2]) assert_array_equal(expected_kp_octagon, actual_kp_octagon) assert_array_equal(expected_scale, actual_scale)
def test_keypoints_censure_moon_image_dob(): """Verify the actual Censure keypoints and their corresponding scale with the expected values for DoB filter.""" img = moon() actual_kp_dob, actual_scale = keypoints_censure(img, 1, 7, 'DoB', 0.15) expected_kp_dob = np.array([[ 21, 497], [ 36, 46], [119, 350], [185, 177], [287, 250], [357, 239], [463, 116], [464, 132], [467, 260]]) expected_scale = np.array([3, 4, 4, 2, 2, 3, 2, 2, 2]) assert_array_equal(expected_kp_dob, actual_kp_dob) assert_array_equal(expected_scale, actual_scale)
def test_keypoints_censure_moon_image_star(): """Verify the actual Censure keypoints and their corresponding scale with the expected values for STAR filter.""" img = moon() actual_kp_star, actual_scale = keypoints_censure(img, 1, 7, 'STAR', 0.15) expected_kp_star = np.array([[ 21, 497], [ 36, 46], [117, 356], [185, 177], [260, 227], [287, 250], [357, 239], [451, 281], [463, 116], [467, 260]]) expected_scale = np.array([3, 3, 6, 2, 3, 2, 3, 5, 2, 2]) assert_array_equal(expected_kp_star, actual_kp_star) assert_array_equal(expected_scale, actual_scale)
def test_plugin(): img = skimage.img_as_float(data.moon()) viewer = ImageViewer(img) def median_filter(img, radius=3): return median(img, selem=disk(radius=radius)) plugin = Plugin(image_filter=median_filter) viewer += plugin plugin += Slider('radius', 1, 5) assert_almost_equal(np.std(viewer.image), 12.556, 3) plugin.filter_image() assert_almost_equal(np.std(viewer.image), 12.931, 3) plugin.show() plugin.close() plugin.clean_up() img, _ = plugin.output() assert_equal(img, viewer.image)
return UnitMap() def _plot_data_default(self): return ArrayPlotData( image=self.image_data, ) def _plot_default(self): plot = Plot(self.plot_data) plot.x_axis = None plot.y_axis = None plot.padding = 0 self.tcm = TransformColorMapper.from_color_map(gray) self.tcm.unit_func = self.unit_map.function self.unit_map.on_trait_change(self.map_changed, 'function') plot.img_plot('image', colormap=self.tcm) return plot view = View( VGroup( Item('plot', editor=ComponentEditor(), springy=True), Item('histogram_view', editor=InstanceEditor(), style='custom'), show_labels=False ), resizable=True ) if __name__ == '__main__': image_view = ImageView(image_data=moon()) image_view.configure_traits()
ax_hist.hist(image.ravel(), bins=bins, histtype='step', color='black') ax_hist.ticklabel_format(axis='y', style='scientific', scilimits=(0, 0)) ax_hist.set_xlabel('Pixel intensity') ax_hist.set_xlim(0, 1) ax_hist.set_yticks([]) # Display cumulative distribution img_cdf, bins = exposure.cumulative_distribution(image, bins) ax_cdf.plot(bins, img_cdf, 'r') ax_cdf.set_yticks([]) return ax_img, ax_hist, ax_cdf # Load an example image img = data.moon() # Contrast stretching p2, p98 = np.percentile(img, (2, 98)) img_rescale = exposure.rescale_intensity(img, in_range=(p2, p98)) # Equalization img_eq = exposure.equalize_hist(img) # Adaptive Equalization img_adapteq = exposure.equalize_adapthist(img, clip_limit=0.03) # Display results fig = plt.figure(figsize=(8, 5)) axes = np.zeros((2, 4), dtype=np.object) axes[0, 0] = fig.add_subplot(2, 4, 1)
import os import tensorflow as tf import numpy as np import time import matplotlib.pyplot as plt from skimage import data as dataExamples import time import matplotlib.pyplot as plt print(dataExamples.moon().shape, dataExamples.camera().shape) IN_IMGS = np.stack([dataExamples.moon(), dataExamples.camera()]) imgs_size = IN_IMGS[0].shape[1] print(IN_IMGS.shape) def correctScale(imgsRaw): for i in range(imgsRaw.shape[0]): imgsRaw[i] = imgsRaw[i] - np.min( imgsRaw[i]) / (np.max(imgsRaw[i]) - np.min(imgsRaw[i])) return imgsRaw IN_IMGS = correctScale(IN_IMGS) IN_IMGS = IN_IMGS.astype(np.complex64) #NUMPY VERSION def npLPFilter(imgs_in): stime = time.time()
image represent the maximum and minimum possible values of the reconstructed image. We start with an image containing both peaks and holes: """ import matplotlib.pyplot as plt import time from skimage import io from skimage import data from skimage.exposure import rescale_intensity import Image t1 = time.time() image = data.moon() #image = io.imread("stone.jpg") # Rescale image intensity so that we can see dim features. image = rescale_intensity(image, in_range=(50, 200)) # convenience function for plotting images def imshow(image, **kwargs): plt.figure(figsize=(5, 4)) plt.imshow(image, **kwargs) plt.axis('off') #imshow(image) #plt.title('original image') """
def test_adapthist_ntiles_raises(): img = skimage.img_as_ubyte(data.moon()) assert_raises(ValueError, exposure.equalize_adapthist, img, ntiles_x=8) assert_raises(ValueError, exposure.equalize_adapthist, img, ntiles_y=8) assert_raises(ValueError, exposure.equalize_adapthist, img, ntiles_x=8, ntiles_y=8)
from skimage import data import napari ##### color maps # PiYG # blue # cyan # gist_earth # gray # green # hsv # inferno # magma # magenta # plasma # red # turbo # twilight # twilight_shifted # yellow # viridis with napari.gui_qt(): # assigning a color map to a gray image # the min and max value of the gray image are mapped to the # color map's bounds viewer = napari.view_image(data.moon(), colormap='viridis')
import matplotlib.pyplot as plt from skimage import data from skimage.exposure import rescale_intensity import time t1 = time.time() image = data.moon() # Rescale image intensity so that we can see dim features. image = rescale_intensity(image, in_range=(50, 200)) t2 = time.time() print (t2-t1) # convenience function for plotting images def imshow(image, **kwargs): plt.figure(figsize=(5, 4)) plt.imshow(image, **kwargs) plt.axis('off') #imshow(image) #plt.title('original image')
''' 1、gamma调整 原理:I=Ig 对原图像的像素,进行幂运算,得到新的像素值。公式中的g就是gamma值。 如果gamma>1, 新图像比原图像暗 如果gamma<1,新图像比原图像亮 函数格式为: ''' from skimage import data, exposure, img_as_float import matplotlib.pyplot as plt image = img_as_float(data.moon()) gam1 = exposure.adjust_gamma(image, 2) #调暗 gam2 = exposure.adjust_gamma(image, 0.5) #调亮plt.figure('adjust_gamma',figsize=(8,8)) plt.subplot(131) plt.title('origin image') plt.imshow(image, plt.cm.gray) plt.axis('off') plt.subplot(132) plt.title('gamma=2') plt.imshow(gam1, plt.cm.gray) plt.axis('off') plt.subplot(133) plt.title('gamma=0.5') plt.imshow(gam2, plt.cm.gray) plt.axis('off') plt.show()
# 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]) @cleanup @pytest.mark.skipif(not has_qt, reason="Qt not installed") @pytest.mark.parametrize('img', [data.moon(), data.astronaut()]) def test_paint_tool(img): viewer = ImageViewer(img) tool = PaintTool(viewer, img.shape) tool.radius = 10 assert_equal(tool.radius, 10) tool.label = 2 assert_equal(tool.label, 2) assert_equal(tool.shape, img.shape[:2]) do_event(viewer, 'mouse_press', xdata=100, ydata=100) do_event(viewer, 'move', xdata=110, ydata=110) do_event(viewer, 'mouse_release')
def test_isodata_moon_image_negative_int(): moon = skimage.img_as_ubyte(data.moon()).astype(np.int32) moon -= 100 assert threshold_isodata(moon) == -13
def test_isodata_moon_image(): moon = skimage.img_as_ubyte(data.moon()) assert threshold_isodata(moon) == 87
from skimage.data import camera, moon from skimage.exposure import cumulative_distribution, equalize_hist from skimage.io import imshow, show from numpy import vectorize im_camera = camera() im_moon = moon() dist_camera, bins = cumulative_distribution(im_camera) dist_moon, bins = cumulative_distribution(im_moon) # def rechercher_transformation(dist_source, dist_target): # nb_source = len(dist_source) # nb_target = len(dist_target) # transformation = [nb_source - 1] * nb_source # i, j = 0, 0 # while j < nb_target: # while i < nb_source and dist_source[i] < dist_target[j]: # transformation[i] = j # i += 1 # j += 1 # return transformation def rechercher_transformation(dist_source, dist_target): nb_source = len(dist_source) nb_target = len(dist_target) transformation = [nb_source - 1] * nb_source i, j = 0, 0 ind0, val0 = 0, 0 while j < nb_target:
import numpy as np from numpy.testing import assert_array_equal, assert_raises from skimage.data import moon from skimage.feature import CENSURE img = moon() np.random.seed(0) def test_censure_on_rectangular_images(): """Censure feature detector should work on 2D image of any shape.""" rect_image = np.random.rand(300, 200) square_image = np.random.rand(200, 200) CENSURE().detect((square_image)) CENSURE().detect((rect_image)) def test_keypoints_censure_color_image_unsupported_error(): """Censure keypoints can be extracted from gray-scale images only.""" assert_raises(ValueError, CENSURE().detect, np.zeros((20, 20, 3))) def test_keypoints_censure_mode_validity_error(): """Mode argument in keypoints_censure can be either DoB, Octagon or STAR.""" assert_raises(ValueError, CENSURE, mode='dummy') def test_keypoints_censure_scale_range_error(): """Difference between the the max_scale and min_scale parameters in keypoints_censure should be greater than or equal to two."""
def setup(self): self.image = img_as_float(data.moon()) self.image = rescale(self.image, 2.0, anti_aliasing=False)
composite_image = np.ones((rows, int(cols + cols/2), 3), dtype=np.double) #生成背景 composite_image[:rows, :cols, :] = pyramid[0] #融合原始图像 i_row = 0 for p in pyramid[1:]: n_rows, n_cols = p.shape[:2] composite_image[i_row:i_row + n_rows, cols:cols + n_cols] = p #循环融合9幅金字塔图像 i_row += n_rows plt.figure('pyramid') plt.imshow(composite_image) plt.show() #除了高斯金字塔,还有其他种类的金字塔,如pyramid_laplacian # ============================================================================= print('''六、对比度与亮度调整''') # ============================================================================= '''1、gamma调整:I=I**g''' image = ski.img_as_float(data.moon()) gam1= exposure.adjust_gamma(image, 2) #调暗 gam2= exposure.adjust_gamma(image, 0.5) #调亮 plt.figure('adjust_gamma',figsize=(8,8)) plt.subplot(131) plt.title('origin image') plt.imshow(image,plt.cm.gray) plt.axis('off') plt.subplot(132) plt.title('gamma=2') plt.imshow(gam1,plt.cm.gray) plt.axis('off') plt.subplot(133) plt.title('gamma=0.5') plt.imshow(gam2,plt.cm.gray) plt.axis('off')
""" 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 from napari import ViewerApp from napari.util import app_context with app_context(): # create the viewer with several image layers viewer = ViewerApp(astronaut=rgb2gray(data.astronaut()), photographer=data.camera(), coins=data.coins(), moon=data.moon()) # remove the coins layer viewer.layers.remove('coins') # swap the order of astronaut and moon viewer.layers['astronaut', 'moon'] = viewer.layers['moon', 'astronaut']
def test_moon(): """ Test that "moon" image can be loaded. """ data.moon()
def setup(self): self.image = img_as_float(data.moon()) self.image = rescale(self.image, 2.0, anti_aliasing=False) # for Contrast stretching self.p2, self.p98 = np.percentile(self.image, (2, 98))
import numpy as np from skimage import exposure, data def plot_img_hist(img, img_name='', bins=256): '''plot image and its histogram''' plt.figure(img_name) plt.subplot(1, 2, 1) plt.imshow(img, cmap='gray') plt.subplot(1, 2, 2) plt.hist(img.ravel(), bins) plt.show # Main procedure img_moon = data.moon() # Load data # Low contrast image plot_img_hist(img_moon, 'Low contrast image') # Contrast stretching p1, p2 = np.percentile(img_moon, (2, 98)) img_moon_ctrststre = exposure.rescale_intensity(img_moon, in_range=(p1, p2)) plot_img_hist(img_moon_ctrststre, 'Contrast stretching') # Histogram equalization img_moon_eqhist = exposure.equalize_hist(img_moon) plot_img_hist(img_moon_eqhist, 'Histogram equalization') # Adaptive Equalization img_moon_adapteq = exposure.equalize_adapthist(img_moon, clip_limit=0.03)
ax_img, ax_hist, ax_cdf = plot_img_and_hist(actual, axes[:, 2]) ax_img.set_title('Tensorflow CLAHE') ax_cdf.set_ylabel('Fraction of total intensity') ax_cdf.set_yticks(np.linspace(0, 1, 5)) # prevent overlap of y-axis labels fig.tight_layout() def compare(expected, actual): return (expected == actual).all() # Load an image to use for testing test_image = data.moon() expected_result = exposure.equalize_adapthist(test_image, clip_limit=0.03) #plot_comparison(test_image, expected_result, expected_result) print(compare(expected_result, expected_result)) #plt.show() import equalize_adapthist a, b = equalize_adapthist.histogram(test_image) equalize_adapthist.tfhist(test_image) print(a) print(b) # get equalization
ax_hist.hist(img.ravel(), bins=bins, histtype='step', color='black') ax_hist.ticklabel_format(axis='y', style='scientific', scilimits=(0, 0)) ax_hist.set_xlabel('Pixel intensity') ax_hist.set_xlim(0, 1) ax_hist.set_yticks([]) # Display cumulative distribution img_cdf, bins = exposure.cumulative_distribution(img, bins) ax_cdf.plot(bins, img_cdf, 'r') ax_cdf.set_yticks([]) return ax_img, ax_hist, ax_cdf # Load an example image img = data.moon() # Contrast stretching p2, p98 = np.percentile(img, (2, 98)) img_rescale = exposure.rescale_intensity(img, in_range=(p2, p98)) # Equalization img_eq = exposure.equalize_hist(img) # Adaptive Equalization img_adapteq = exposure.equalize_adapthist(img, clip_limit=0.03) # Display results fig = plt.figure(figsize=(8, 5)) axes = np.zeros((2,4), dtype=np.object) axes[0,0] = fig.add_subplot(2, 4, 1)
ax_hist.hist(image.ravel(), bins=bins) ax_hist.ticklabel_format(axis='y', style='scientific', scilimits=(0, 0)) ax_hist.set_xlabel('Pixel intensity') xmin, xmax = dtype_range[image.dtype.type] ax_hist.set_xlim(xmin, xmax) # Display cumulative distribution img_cdf, bins = exposure.cumulative_distribution(image, bins) ax_cdf.plot(bins, img_cdf, 'r') return ax_img, ax_hist, ax_cdf # Load an example image img = img_as_ubyte(data.moon()) # Global equalize img_rescale = exposure.equalize_hist(img) # Equalization selem = disk(30) img_eq = rank.equalize(img, selem=selem) # Display results fig = plt.figure(figsize=(8, 5)) axes = np.zeros((2, 3), dtype=np.object) axes[0, 0] = plt.subplot(2, 3, 1) axes[0, 1] = plt.subplot(2, 3, 2, sharex=axes[0, 0], sharey=axes[0, 0]) axes[0, 2] = plt.subplot(2, 3, 3, sharex=axes[0, 0], sharey=axes[0, 0]) axes[1, 0] = plt.subplot(2, 3, 4)
# 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]) @cleanup @testing.skipif(not has_qt, reason="Qt not installed") @parametrize('img', [data.moon(), data.astronaut()]) def test_paint_tool(img): viewer = ImageViewer(img) tool = PaintTool(viewer, img.shape) tool.radius = 10 assert_equal(tool.radius, 10) tool.label = 2 assert_equal(tool.label, 2) assert_equal(tool.shape, img.shape[:2]) do_event(viewer, 'mouse_press', xdata=100, ydata=100) do_event(viewer, 'move', xdata=110, ydata=110) do_event(viewer, 'mouse_release')
def find_bounding_box(Array): a = np.zeros(4).reshape((2,2)) a[0] = Array[0] for x in range(0, array.shape[0]): if(a[0][0] > array[x][0]): a[0][0] = array[x][0] if(a[0][1] > array[x][1]): a[0][1] = array[x][1] if(a[1][0] < array[x][0]): a[1][0] = array[x][0] elif(a[1][1] < array[x][1]): a[1][1] = array[x][1] return a def fault_detector(image): fault_sercher = image_search() bounding_box = find_bounding_box(fault_sercher) bound_image = image_cut(image,bounding_box[0][0],bounding_box[0][1],(bounding_box[1][0] - bounding_box[0][0]), (bounding_box[1][1]-bounding_box[0][1])) return bound_image #=============================================================================== #MAIN PROGRAM #test_image = data.load("/home/lapowell/Downloads/asteroids.jpg") image1 = data.moon() l = image_search(image1,78) print l
from skimage import data import napari with napari.gui_qt(): viewer = napari.Viewer() # each image is stacked on a layer list (it should be a layer stack =D) # we assign a label to each layer so that we can recover it easily later viewer.add_image(data.astronaut(), name='astronaut') viewer.add_image(data.moon(), name='moon') viewer.add_image(data.camera(), name='camera') # we can access the layers # # viewer.layers[key] # # key can be the key/label assigned to the layer or # an index (integer value) # # `viewer.layers` has type LayerList, which is a list-like layer collection # with built-in reordering and callback hooks. # A layer with an image has the type: napari.layers.image.image.Image # or 'Image layer' # To remove a layer, just use: # viewer.layers.pop(i) # All these codes can be used in the built-in interactive terminal # of Napari, which already has all loaded data on memory
import numpy as np from numpy.testing import assert_array_equal, assert_raises from skimage.data import moon from skimage.feature import CENSURE img = moon() def test_censure_on_rectangular_images(): """Censure feature detector should work on 2D image of any shape.""" rect_image = np.random.random((300, 200)) square_image = np.random.random((200, 200)) CENSURE().detect((square_image)) CENSURE().detect((rect_image)) def test_keypoints_censure_color_image_unsupported_error(): """Censure keypoints can be extracted from gray-scale images only.""" assert_raises(ValueError, CENSURE().detect, np.zeros((20, 20, 3))) def test_keypoints_censure_mode_validity_error(): """Mode argument in keypoints_censure can be either DoB, Octagon or STAR.""" assert_raises(ValueError, CENSURE, mode='dummy') def test_keypoints_censure_scale_range_error(): """Difference between the the max_scale and min_scale parameters in keypoints_censure should be greater than or equal to two."""
def test_isodata_moon_image_negative_float(): moon = skimage.img_as_ubyte(data.moon()).astype(np.float64) moon -= 100 assert -13 < threshold_isodata(moon) < -12
# try_all_threshold, # _mean_std, _cross_entropy, ) # from skimage.filters._multiotsu import (_get_multiotsu_thresh_indices_lut, # _get_multiotsu_thresh_indices) from skimage._shared import testing from cupy.testing import assert_array_equal, assert_array_almost_equal # transfer images to GPU astronautd = cp.asarray(data.astronaut()) camerad = cp.asarray(data.camera()) celld = cp.asarray(data.cell()) coinsd = cp.asarray(data.coins()) moond = cp.asarray(data.moon()) class TestSimpleImage: def setup(self): # fmt: off self.image = cp.asarray( [[0, 0, 1, 3, 5], [0, 1, 4, 3, 4], [1, 2, 5, 4, 1], [2, 4, 5, 2, 1], [4, 5, 1, 0, 0]], dtype=int) # fmt: on def test_minimum(self): with pytest.raises(RuntimeError): threshold_minimum(self.image)
ax_hist.hist(img.ravel(), bins=bins) ax_hist.ticklabel_format(axis="y", style="scientific", scilimits=(0, 0)) ax_hist.set_xlabel("Pixel intensity") xmin, xmax = dtype_range[img.dtype.type] ax_hist.set_xlim(xmin, xmax) # Display cumulative distribution img_cdf, bins = exposure.cumulative_distribution(img, bins) ax_cdf.plot(bins, img_cdf, "r") return ax_img, ax_hist, ax_cdf # Load an example image img = img_as_ubyte(data.moon()) # Global equalize img_rescale = exposure.equalize_hist(img) # Equalization selem = disk(30) img_eq = rank.equalize(img, selem=selem) # Display results f, axes = plt.subplots(2, 3, figsize=(8, 5)) ax_img, ax_hist, ax_cdf = plot_img_and_hist(img, axes[:, 0]) ax_img.set_title("Low contrast image") ax_hist.set_ylabel("Number of pixels")
"""Copy screenshot of the canvas or the whole viewer to clipboard.""" from skimage import data from qtpy.QtWidgets import QVBoxLayout, QPushButton, QWidget import napari # create the viewer with an image viewer = napari.view_image(data.moon()) class Grabber(QWidget): def __init__(self): super().__init__() self.copy_canvas_btn = QPushButton("Copy Canvas to Clipboard", self) self.copy_canvas_btn.setToolTip( "Copy screenshot of the canvas to clipboard.") self.copy_viewer_btn = QPushButton("Copy Viewer to Clipboard", self) self.copy_viewer_btn.setToolTip( "Copy screenshot of the entire viewer to clipboard.") layout = QVBoxLayout(self) layout.addWidget(self.copy_canvas_btn) layout.addWidget(self.copy_viewer_btn) def create_grabber_widget(): """Create widget""" widget = Grabber()