深度学习的一些模型中常常需要import skimage,以下是转自他人博客的内容,觉得写得很不错
参考:https://blog.csdn.net/thesby/article/details/51340894
skimage是和scipy、numpy可以完美结合的,那么就可以很好的使用numpy了。
原文作者教大家怎么使用help来查看skimage中的各个包以及各个函数,需要大家自己花时间去阅读源码了解才行。

step 1 概览

学习一个python库第一步是干啥?百度、Google搜教程?No,第一步就是直接 import。

import skimage
help(skimage)

看看输出:

Help on package skimage:NAMEskimage - Image Processing SciKit (Toolbox for SciPy)DESCRIPTION``scikit-image`` (a.k.a. ``skimage``) is a collection of algorithms for imageprocessing and computer vision.The main package of ``skimage`` only provides a few utilities for convertingbetween image data types; for most features, you need to import one of thefollowing subpackages:Subpackages-----------colorColor space conversion.dataTest images and example data.drawDrawing primitives (lines, text, etc.) that operate on NumPy arrays.exposureImage intensity adjustment, e.g., histogram equalization, etc.featureFeature detection and extraction, e.g., texture analysis corners, etc.filtersSharpening, edge finding, rank filters, thresholding, etc.graphGraph-theoretic operations, e.g., shortest paths.ioReading, saving, and displaying images and video.measureMeasurement of image properties, e.g., similarity and contours.morphologyMorphological operations, e.g., opening or skeletonization.noviceSimplified interface for teaching purposes.restorationRestoration algorithms, e.g., deconvolution algorithms, denoising, etc.segmentationPartitioning an image into multiple regions.transformGeometric and other transforms, e.g., rotation or the Radon transform.utilGeneric utilities.viewerA simple graphical user interface for visualizing results and exploringparameters.Utility Functions-----------------img_as_floatConvert an image to floating point format, with values in [0, 1].img_as_uintConvert an image to unsigned integer format, with values in [0, 65535].img_as_intConvert an image to signed integer format, with values in [-32768, 32767].img_as_ubyteConvert an image to unsigned byte format, with values in [0, 255].PACKAGE CONTENTS_build_shared (package)color (package)data (package)draw (package)exposure (package)external (package)feature (package)filters (package)future (package)graph (package)io (package)measure (package)morphology (package)novice (package)restoration (package)run-hessianscripts (package)segmentation (package)setuptransform (package)util (package)viewer (package)FUNCTIONStest = _test(doctest=False, verbose=False)Run all unit tests.DATA__SKIMAGE_SETUP__ = False__warningregistry__ = {("the imp module is deprecated in favour of imp...data_dir = r'E:\App_install\Anaconda3\lib\site-packages\skimage\data'doctest = functools.partial(<function _test at 0x000001E6A4FF6BF8>, do...doctest_verbose = functools.partial(<function _test at 0x000001E6A4FF6...pkg_dir = r'E:\App_install\Anaconda3\lib\site-packages\skimage'test_verbose = functools.partial(<function _test at 0x000001E6A4FF6BF8...VERSION0.13.1

我们可以看到这里有好几个package是单独的,这意味着使用时要单独import。里面有那么多的库,每一个干啥用的?用help看看就知道了。

step 2 IO

我们这里看看如何读写图像文件。这个在skimage.io里面,主要包含图像的读写操作。
import skimage, skimage.io
help(skimage.io)
Help on package skimage.io in skimage:NAMEskimage.io - Utilities to read and write images in various formats.FILE/usr/local/lib/python2.7/dist-packages/skimage/io/__init__.pyDESCRIPTIONThe following plug-ins are available:========== ==============================================================Plugin     Description---------- --------------------------------------------------------------pil        Image reading via the Python Imaging Libraryqt         Fast image display using the Qt libraryfreeimage  Load images using the FreeImage librarygtk        Fast image display using the GTK librarymatplotlib Display or save images using Matplotlibfits       FITS image reading via PyFITSsimpleitk  Image reading and writing via SimpleITKimageio    Image reading via the ImageIO Libraryimread     Image reading and writing via imreadtifffile   Load and save TIFF and TIFF-based images using tifffile.pygdal       Image reading via the GDAL Library (www.gdal.org)========== ==============================================================PACKAGE CONTENTS_image_stack_io_plugins (package)collectionmanage_pluginssetupsifttests (package)utilDATAWRAP_LEN = 73available_plugins = {'fits': ['imread', 'imread_collection'], 'freeima...image_stack = []
好像没有列出全部的函数,没关系,继续看。
dir(skimage.io)
['ImageCollection','MultiImage','WRAP_LEN','__builtins__','__doc__','__file__','__name__','__package__','__path__','_format_plugin_info_table','_image_stack','_io','_plugins','_separator','_update_doc','available_plugins','call_plugin','collection','concatenate_images','find_available_plugins','image_stack','imread','imread_collection','imread_collection_wrapper','imsave','imshow','imshow_collection','load_sift','load_surf','manage_plugins','plugin_info','plugin_order','pop','push','reset_plugins','show','sift','use_plugin','util']
  1. imread: 和matlab一样,就是读取图像
  2. imsave: 和matlab一样,就是存储图像
  3. imshow: 调用的matplotlib的显示,所以必须再使用show才能真正显示。
    其他的就不多说了,自己help就很清楚了。

step 3 形态学变换

由step1可以看出形态学变换的东西肯定就在 skimage.morphology里面了。包含二进制的腐蚀,膨胀,开/闭操作,图像分水岭,凹凸检测等。
import skimage, skimage.morphology
help(skimage.morphology)
Help on package skimage.morphology in skimage:NAMEskimage.morphologyFILE/usr/local/lib/python2.7/dist-packages/skimage/morphology/__init__.pyPACKAGE CONTENTS_convex_hull_greyreconstruct_skeletonize_skeletonize_3d_skeletonize_3d_cy_skeletonize_cy_watershedbinaryconvex_hullgreygreyreconstructmiscselemsetuptests (package)watershedFUNCTIONSball(radius, dtype=<type 'numpy.uint8'>)Generates a ball-shaped structuring element.This is the 3D equivalent of a disk.A pixel is within the neighborhood if the euclidean distance betweenit and the origin is no greater than radius.Parameters----------radius : intThe radius of the ball-shaped structuring element.Other Parameters----------------dtype : data-typeThe data type of the structuring element.Returns-------selem : ndarrayThe structuring element where elements of the neighborhoodare 1 and 0 otherwise.binary_closing(image, selem=None, *args, **kwargs)Return fast binary morphological closing of an image.This function returns the same result as greyscale closing but performsfaster for binary images.The morphological closing on an image is defined as a dilation followed byan erosion. Closing can remove small dark spots (i.e. "pepper") and connectsmall bright cracks. This tends to "close" up (dark) gaps between (bright)features.Parameters----------image : ndarrayBinary input image.selem : ndarray, optionalThe neighborhood expressed as a 2-D array of 1's and 0's.If None, use cross-shaped structuring element (connectivity=1).out : ndarray of bool, optionalThe array to store the result of the morphology. If None,is passed, a new array will be allocated.Returns-------closing : ndarray of boolThe result of the morphological closing.binary_dilation(image, selem=None, *args, **kwargs)Return fast binary morphological dilation of an image.This function returns the same result as greyscale dilation but performsfaster for binary images.Morphological dilation sets a pixel at ``(i,j)`` to the maximum over allpixels in the neighborhood centered at ``(i,j)``. Dilation enlarges brightregions and shrinks dark regions.Parameters----------image : ndarrayBinary input image.selem : ndarray, optionalThe neighborhood expressed as a 2-D array of 1's and 0's.If None, use cross-shaped structuring element (connectivity=1).out : ndarray of bool, optionalThe array to store the result of the morphology. If None, ispassed, a new array will be allocated.Returns-------dilated : ndarray of bool or uintThe result of the morphological dilation with values in``[False, True]``.binary_erosion(image, selem=None, *args, **kwargs)Return fast binary morphological erosion of an image.This function returns the same result as greyscale erosion but performsfaster for binary images.Morphological erosion sets a pixel at ``(i,j)`` to the minimum over allpixels in the neighborhood centered at ``(i,j)``. Erosion shrinks brightregions and enlarges dark regions.Parameters----------image : ndarrayBinary input image.selem : ndarray, optionalThe neighborhood expressed as a 2-D array of 1's and 0's.If None, use cross-shaped structuring element (connectivity=1).out : ndarray of bool, optionalThe array to store the result of the morphology. If None ispassed, a new array will be allocated.Returns-------eroded : ndarray of bool or uintThe result of the morphological erosion taking values in``[False, True]``.binary_opening(image, selem=None, *args, **kwargs)Return fast binary morphological opening of an image.This function returns the same result as greyscale opening but performsfaster for binary images.The morphological opening on an image is defined as an erosion followed bya dilation. Opening can remove small bright spots (i.e. "salt") and connectsmall dark cracks. This tends to "open" up (dark) gaps between (bright)features.Parameters----------image : ndarrayBinary input image.selem : ndarray, optionalThe neighborhood expressed as a 2-D array of 1's and 0's.If None, use cross-shaped structuring element (connectivity=1).out : ndarray of bool, optionalThe array to store the result of the morphology. If Noneis passed, a new array will be allocated.Returns-------opening : ndarray of boolThe result of the morphological opening.black_tophat(image, selem=None, *args, **kwargs)Return black top hat of an image.The black top hat of an image is defined as its morphological closing minusthe original image. This operation returns the dark spots of the image thatare smaller than the structuring element. Note that dark spots in theoriginal image are bright spots after the black top hat.Parameters----------image : ndarrayImage array.selem : ndarray, optionalThe neighborhood expressed as a 2-D array of 1's and 0's.If None, use cross-shaped structuring element (connectivity=1).out : ndarray, optionalThe array to store the result of the morphology. If Noneis passed, a new array will be allocated.Returns-------opening : array, same shape and type as `image`The result of the black top filter.Examples-------->>> # Change dark peak to bright peak and subtract background>>> import numpy as np>>> from skimage.morphology import square>>> dark_on_grey = np.array([[7, 6, 6, 6, 7],...                          [6, 5, 4, 5, 6],...                          [6, 4, 0, 4, 6],...                          [6, 5, 4, 5, 6],...                          [7, 6, 6, 6, 7]], dtype=np.uint8)>>> black_tophat(dark_on_grey, square(3))array([[0, 0, 0, 0, 0],[0, 0, 1, 0, 0],[0, 1, 5, 1, 0],[0, 0, 1, 0, 0],[0, 0, 0, 0, 0]], dtype=uint8)closing(image, selem=None, *args, **kwargs)Return greyscale morphological closing of an image.The morphological closing on an image is defined as a dilation followed byan erosion. Closing can remove small dark spots (i.e. "pepper") and connectsmall bright cracks. This tends to "close" up (dark) gaps between (bright)features.Parameters----------image : ndarrayImage array.selem : ndarray, optionalThe neighborhood expressed as an array of 1's and 0's.If None, use cross-shaped structuring element (connectivity=1).out : ndarray, optionalThe array to store the result of the morphology. If None,is passed, a new array will be allocated.Returns-------closing : array, same shape and type as `image`The result of the morphological closing.Examples-------->>> # Close a gap between two bright lines>>> import numpy as np>>> from skimage.morphology import square>>> broken_line = np.array([[0, 0, 0, 0, 0],...                         [0, 0, 0, 0, 0],...                         [1, 1, 0, 1, 1],...                         [0, 0, 0, 0, 0],...                         [0, 0, 0, 0, 0]], dtype=np.uint8)>>> closing(broken_line, square(3))array([[0, 0, 0, 0, 0],[0, 0, 0, 0, 0],[1, 1, 1, 1, 1],[0, 0, 0, 0, 0],[0, 0, 0, 0, 0]], dtype=uint8)convex_hull_image(image)Compute the convex hull image of a binary image.The convex hull is the set of pixels included in the smallest convexpolygon that surround all white pixels in the input image.Parameters----------image : (M, N) arrayBinary input image. This array is cast to bool before processing.Returns-------hull : (M, N) array of boolBinary image with pixels in convex hull set to True.References----------.. [1] http://blogs.mathworks.com/steve/2011/10/04/binary-image-convex-hull-algorithm-notes/convex_hull_object(image, neighbors=8)Compute the convex hull image of individual objects in a binary image.The convex hull is the set of pixels included in the smallest convexpolygon that surround all white pixels in the input image.Parameters----------image : (M, N) arrayBinary input image.neighbors : {4, 8}, intWhether to use 4- or 8-connectivity.Returns-------hull : ndarray of boolBinary image with pixels in convex hull set to True.Notes-----This function uses skimage.morphology.label to define unique objects,finds the convex hull of each using convex_hull_image, and combinesthese regions with logical OR. Be aware the convex hulls of unconnectedobjects may overlap in the result. If this is suspected, consider usingconvex_hull_image separately on each object.cube(width, dtype=<type 'numpy.uint8'>)Generates a cube-shaped structuring element.This is the 3D equivalent of a square.Every pixel along the perimeter has a chessboard distanceno greater than radius (radius=floor(width/2)) pixels.Parameters----------width : intThe width, height and depth of the cube.Other Parameters----------------dtype : data-typeThe data type of the structuring element.Returns-------selem : ndarrayA structuring element consisting only of ones, i.e. everypixel belongs to the neighborhood.diamond(radius, dtype=<type 'numpy.uint8'>)Generates a flat, diamond-shaped structuring element.A pixel is part of the neighborhood (i.e. labeled 1) ifthe city block/Manhattan distance between it and the center ofthe neighborhood is no greater than radius.Parameters----------radius : intThe radius of the diamond-shaped structuring element.Other Parameters----------------dtype : data-typeThe data type of the structuring element.Returns-------selem : ndarrayThe structuring element where elements of the neighborhoodare 1 and 0 otherwise.dilation(image, selem=None, *args, **kwargs)Return greyscale morphological dilation of an image.Morphological dilation sets a pixel at (i,j) to the maximum over all pixelsin the neighborhood centered at (i,j). Dilation enlarges bright regionsand shrinks dark regions.Parameters----------image : ndarrayImage array.selem : ndarray, optionalThe neighborhood expressed as a 2-D array of 1's and 0's.If None, use cross-shaped structuring element (connectivity=1).out : ndarray, optionalThe array to store the result of the morphology. If None, ispassed, a new array will be allocated.shift_x, shift_y : bool, optionalshift structuring element about center point. This only affectseccentric structuring elements (i.e. selem with even numbered sides).Returns-------dilated : uint8 array, same shape and type as `image`The result of the morphological dilation.Notes-----For `uint8` (and `uint16` up to a certain bit-depth) data, the loweralgorithm complexity makes the `skimage.filter.rank.maximum` function moreefficient for larger images and structuring elements.Examples-------->>> # Dilation enlarges bright regions>>> import numpy as np>>> from skimage.morphology import square>>> bright_pixel = np.array([[0, 0, 0, 0, 0],...                          [0, 0, 0, 0, 0],...                          [0, 0, 1, 0, 0],...                          [0, 0, 0, 0, 0],...                          [0, 0, 0, 0, 0]], dtype=np.uint8)>>> dilation(bright_pixel, square(3))array([[0, 0, 0, 0, 0],[0, 1, 1, 1, 0],[0, 1, 1, 1, 0],[0, 1, 1, 1, 0],[0, 0, 0, 0, 0]], dtype=uint8)disk(radius, dtype=<type 'numpy.uint8'>)Generates a flat, disk-shaped structuring element.A pixel is within the neighborhood if the euclidean distance betweenit and the origin is no greater than radius.Parameters----------radius : intThe radius of the disk-shaped structuring element.Other Parameters----------------dtype : data-typeThe data type of the structuring element.Returns-------selem : ndarrayThe structuring element where elements of the neighborhoodare 1 and 0 otherwise.erosion(image, selem=None, *args, **kwargs)Return greyscale morphological erosion of an image.Morphological erosion sets a pixel at (i,j) to the minimum over all pixelsin the neighborhood centered at (i,j). Erosion shrinks bright regions andenlarges dark regions.Parameters----------image : ndarrayImage array.selem : ndarray, optionalThe neighborhood expressed as an array of 1's and 0's.If None, use cross-shaped structuring element (connectivity=1).out : ndarrays, optionalThe array to store the result of the morphology. If None ispassed, a new array will be allocated.shift_x, shift_y : bool, optionalshift structuring element about center point. This only affectseccentric structuring elements (i.e. selem with even numbered sides).Returns-------eroded : array, same shape as `image`The result of the morphological erosion.Notes-----For ``uint8`` (and ``uint16`` up to a certain bit-depth) data, thelower algorithm complexity makes the `skimage.filter.rank.minimum`function more efficient for larger images and structuring elements.Examples-------->>> # Erosion shrinks bright regions>>> import numpy as np>>> from skimage.morphology import square>>> bright_square = np.array([[0, 0, 0, 0, 0],...                           [0, 1, 1, 1, 0],...                           [0, 1, 1, 1, 0],...                           [0, 1, 1, 1, 0],...                           [0, 0, 0, 0, 0]], dtype=np.uint8)>>> erosion(bright_square, square(3))array([[0, 0, 0, 0, 0],[0, 0, 0, 0, 0],[0, 0, 1, 0, 0],[0, 0, 0, 0, 0],[0, 0, 0, 0, 0]], dtype=uint8)label(input, neighbors=None, background=None, return_num=False, connectivity=None)Label connected regions of an integer array.Two pixels are connected when they are neighbors and have the same value.In 2D, they can be neighbors either in a 1- or 2-connected sense.The value refers to the maximum number of orthogonal hops to consider apixel/voxel a neighbor::1-connectivity      2-connectivity     diagonal connection close-up[ ]           [ ]  [ ]  [ ]         [ ]|               \  |  /             |  <- hop 2[ ]--[x]--[ ]      [ ]--[x]--[ ]    [x]--[ ]|               /  |  \         hop 1[ ]           [ ]  [ ]  [ ]Parameters----------input : ndarray of dtype intImage to label.neighbors : {4, 8}, int, optionalWhether to use 4- or 8-"connectivity".In 3D, 4-"connectivity" means connected pixels have to share face,whereas with 8-"connectivity", they have to share only edge or vertex.**Deprecated, use ``connectivity`` instead.**background : int, optionalConsider all pixels with this value as background pixels, and labelthem as 0. By default, 0-valued pixels are considered as backgroundpixels.return_num : bool, optionalWhether to return the number of assigned labels.connectivity : int, optionalMaximum number of orthogonal hops to consider a pixel/voxelas a neighbor.Accepted values are ranging from  1 to input.ndim. If ``None``, a fullconnectivity of ``input.ndim`` is used.Returns-------labels : ndarray of dtype intLabeled array, where all connected regions are assigned thesame integer value.num : int, optionalNumber of labels, which equals the maximum label index and is onlyreturned if return_num is `True`.Examples-------->>> import numpy as np>>> x = np.eye(3).astype(int)>>> print(x)[[1 0 0][0 1 0][0 0 1]]>>> from skimage.measure import label>>> print(label(x, connectivity=1))[[1 0 0][0 2 0][0 0 3]]>>> print(label(x, connectivity=2))[[1 0 0][0 1 0][0 0 1]]>>> print(label(x, background=-1))[[1 2 2][2 1 2][2 2 1]]>>> x = np.array([[1, 0, 0],...               [1, 1, 5],...               [0, 0, 0]])>>> print(label(x))[[1 0 0][1 1 2][0 0 0]]medial_axis(image, mask=None, return_distance=False)Compute the medial axis transform of a binary imageParameters----------image : binary ndarray, shape (M, N)The image of the shape to be skeletonized.mask : binary ndarray, shape (M, N), optionalIf a mask is given, only those elements in `image` with a truevalue in `mask` are used for computing the medial axis.return_distance : bool, optionalIf true, the distance transform is returned as well as the skeleton.Returns-------out : ndarray of boolsMedial axis transform of the imagedist : ndarray of ints, optionalDistance transform of the image (only returned if `return_distance`is True)See also--------skeletonizeNotes-----This algorithm computes the medial axis transform of an imageas the ridges of its distance transform.The different steps of the algorithm are as follows* A lookup table is used, that assigns 0 or 1 to each configuration ofthe 3x3 binary square, whether the central pixel should be removedor kept. We want a point to be removed if it has more than one neighborand if removing it does not change the number of connected components.* The distance transform to the background is computed, as well asthe cornerness of the pixel.* The foreground (value of 1) points are ordered bythe distance transform, then the cornerness.* A cython function is called to reduce the image to its skeleton. Itprocesses pixels in the order determined at the previous step, andremoves or maintains a pixel according to the lookup table. Becauseof the ordering, it is possible to process all pixels in only onepass.Examples-------->>> square = np.zeros((7, 7), dtype=np.uint8)>>> square[1:-1, 2:-2] = 1>>> squarearray([[0, 0, 0, 0, 0, 0, 0],[0, 0, 1, 1, 1, 0, 0],[0, 0, 1, 1, 1, 0, 0],[0, 0, 1, 1, 1, 0, 0],[0, 0, 1, 1, 1, 0, 0],[0, 0, 1, 1, 1, 0, 0],[0, 0, 0, 0, 0, 0, 0]], dtype=uint8)>>> medial_axis(square).astype(np.uint8)array([[0, 0, 0, 0, 0, 0, 0],[0, 0, 1, 0, 1, 0, 0],[0, 0, 0, 1, 0, 0, 0],[0, 0, 0, 1, 0, 0, 0],[0, 0, 0, 1, 0, 0, 0],[0, 0, 1, 0, 1, 0, 0],[0, 0, 0, 0, 0, 0, 0]], dtype=uint8)octagon(m, n, dtype=<type 'numpy.uint8'>)Generates an octagon shaped structuring element.For a given size of (m) horizontal and vertical sidesand a given (n) height or width of slanted sides octagon is generated.The slanted sides are 45 or 135 degrees to the horizontal axisand hence the widths and heights are equal.Parameters----------m : intThe size of the horizontal and vertical sides.n : intThe height or width of the slanted sides.Other Parameters----------------dtype : data-typeThe data type of the structuring element.Returns-------selem : ndarrayThe structuring element where elements of the neighborhoodare 1 and 0 otherwise.octahedron(radius, dtype=<type 'numpy.uint8'>)Generates a octahedron-shaped structuring element.This is the 3D equivalent of a diamond.A pixel is part of the neighborhood (i.e. labeled 1) ifthe city block/Manhattan distance between it and the center ofthe neighborhood is no greater than radius.Parameters----------radius : intThe radius of the octahedron-shaped structuring element.Other Parameters----------------dtype : data-typeThe data type of the structuring element.Returns-------selem : ndarrayThe structuring element where elements of the neighborhoodare 1 and 0 otherwise.opening(image, selem=None, *args, **kwargs)Return greyscale morphological opening of an image.The morphological opening on an image is defined as an erosion followed bya dilation. Opening can remove small bright spots (i.e. "salt") and connectsmall dark cracks. This tends to "open" up (dark) gaps between (bright)features.Parameters----------image : ndarrayImage array.selem : ndarray, optionalThe neighborhood expressed as an array of 1's and 0's.If None, use cross-shaped structuring element (connectivity=1).out : ndarray, optionalThe array to store the result of the morphology. If Noneis passed, a new array will be allocated.Returns-------opening : array, same shape and type as `image`The result of the morphological opening.Examples-------->>> # Open up gap between two bright regions (but also shrink regions)>>> import numpy as np>>> from skimage.morphology import square>>> bad_connection = np.array([[1, 0, 0, 0, 1],...                            [1, 1, 0, 1, 1],...                            [1, 1, 1, 1, 1],...                            [1, 1, 0, 1, 1],...                            [1, 0, 0, 0, 1]], dtype=np.uint8)>>> opening(bad_connection, square(3))array([[0, 0, 0, 0, 0],[1, 1, 0, 1, 1],[1, 1, 0, 1, 1],[1, 1, 0, 1, 1],[0, 0, 0, 0, 0]], dtype=uint8)reconstruction(seed, mask, method='dilation', selem=None, offset=None)Perform a morphological reconstruction of an image.Morphological reconstruction by dilation is similar to basic morphologicaldilation: high-intensity values will replace nearby low-intensity values.The basic dilation operator, however, uses a structuring element todetermine how far a value in the input image can spread. In contrast,reconstruction uses two images: a "seed" image, which specifies the valuesthat spread, and a "mask" image, which gives the maximum allowed value ateach pixel. The mask image, like the structuring element, limits the spreadof high-intensity values. Reconstruction by erosion is simply the inverse:low-intensity values spread from the seed image and are limited by the maskimage, which represents the minimum allowed value.Alternatively, you can think of reconstruction as a way to isolate theconnected regions of an image. For dilation, reconstruction connectsregions marked by local maxima in the seed image: neighboring pixelsless-than-or-equal-to those seeds are connected to the seeded region.Local maxima with values larger than the seed image will get truncated tothe seed value.Parameters----------seed : ndarrayThe seed image (a.k.a. marker image), which specifies the values thatare dilated or eroded.mask : ndarrayThe maximum (dilation) / minimum (erosion) allowed value at each pixel.method : {'dilation'|'erosion'}Perform reconstruction by dilation or erosion. In dilation (orerosion), the seed image is dilated (or eroded) until limited by themask image. For dilation, each seed value must be less than or equalto the corresponding mask value; for erosion, the reverse is true.selem : ndarrayThe neighborhood expressed as a 2-D array of 1's and 0's.Returns-------reconstructed : ndarrayThe result of morphological reconstruction.Examples-------->>> import numpy as np>>> from skimage.morphology import reconstructionFirst, we create a sinusoidal mask image with peaks at middle and ends.>>> x = np.linspace(0, 4 * np.pi)>>> y_mask = np.cos(x)Then, we create a seed image initialized to the minimum mask value (forreconstruction by dilation, min-intensity values don't spread) and add"seeds" to the left and right peak, but at a fraction of peak value (1).>>> y_seed = y_mask.min() * np.ones_like(x)>>> y_seed[0] = 0.5>>> y_seed[-1] = 0>>> y_rec = reconstruction(y_seed, y_mask)The reconstructed image (or curve, in this case) is exactly the same as themask image, except that the peaks are truncated to 0.5 and 0. The middlepeak disappears completely: Since there were no seed values in this peakregion, its reconstructed value is truncated to the surrounding value (-1).As a more practical example, we try to extract the bright features of animage by subtracting a background image created by reconstruction.>>> y, x = np.mgrid[:20:0.5, :20:0.5]>>> bumps = np.sin(x) + np.sin(y)To create the background image, set the mask image to the original image,and the seed image to the original image with an intensity offset, `h`.>>> h = 0.3>>> seed = bumps - h>>> background = reconstruction(seed, bumps)The resulting reconstructed image looks exactly like the original image,but with the peaks of the bumps cut off. Subtracting this reconstructedimage from the original image leaves just the peaks of the bumps>>> hdome = bumps - backgroundThis operation is known as the h-dome of the image and leaves featuresof height `h` in the subtracted image.Notes-----The algorithm is taken from [1]_. Applications for greyscale reconstructionare discussed in [2]_ and [3]_.References----------.. [1] Robinson, "Efficient morphological reconstruction: a downhillfilter", Pattern Recognition Letters 25 (2004) 1759-1767... [2] Vincent, L., "Morphological Grayscale Reconstruction in ImageAnalysis: Applications and Efficient Algorithms", IEEE Transactionson Image Processing (1993).. [3] Soille, P., "Morphological Image Analysis: Principles andApplications", Chapter 6, 2nd edition (2003), ISBN 3540429883.rectangle(width, height, dtype=<type 'numpy.uint8'>)Generates a flat, rectangular-shaped structuring element.Every pixel in the rectangle generated for a given width and given heightbelongs to the neighborhood.Parameters----------width : intThe width of the rectangle.height : intThe height of the rectangle.Other Parameters----------------dtype : data-typeThe data type of the structuring element.Returns-------selem : ndarrayA structuring element consisting only of ones, i.e. everypixel belongs to the neighborhood.remove_small_holes(ar, min_size=64, connectivity=1, in_place=False)Remove continguous holes smaller than the specified size.Parameters----------ar : ndarray (arbitrary shape, int or bool type)The array containing the connected components of interest.min_size : int, optional (default: 64)The hole component size.connectivity : int, {1, 2, ..., ar.ndim}, optional (default: 1)The connectivity defining the neighborhood of a pixel.in_place : bool, optional (default: False)If `True`, remove the connected components in the input array itself.Otherwise, make a copy.Raises------TypeErrorIf the input array is of an invalid type, such as float or string.ValueErrorIf the input array contains negative values.Returns-------out : ndarray, same shape and type as input `ar`The input array with small holes within connected components removed.Examples-------->>> from skimage import morphology>>> a = np.array([[1, 1, 1, 1, 1, 0],...               [1, 1, 1, 0, 1, 0],...               [1, 0, 0, 1, 1, 0],...               [1, 1, 1, 1, 1, 0]], bool)>>> b = morphology.remove_small_holes(a, 2)>>> barray([[ True,  True,  True,  True,  True, False],[ True,  True,  True,  True,  True, False],[ True, False, False,  True,  True, False],[ True,  True,  True,  True,  True, False]], dtype=bool)>>> c = morphology.remove_small_holes(a, 2, connectivity=2)>>> carray([[ True,  True,  True,  True,  True, False],[ True,  True,  True, False,  True, False],[ True, False, False,  True,  True, False],[ True,  True,  True,  True,  True, False]], dtype=bool)>>> d = morphology.remove_small_holes(a, 2, in_place=True)>>> d is aTrueNotes-----If the array type is int, it is assumed that it contains already-labeledobjects. The labels are not kept in the output image (this function alwaysoutputs a bool image). It is suggested that labeling is completed afterusing this function.remove_small_objects(ar, min_size=64, connectivity=1, in_place=False)Remove connected components smaller than the specified size.Parameters----------ar : ndarray (arbitrary shape, int or bool type)The array containing the connected components of interest. If the arraytype is int, it is assumed that it contains already-labeled objects.The ints must be non-negative.min_size : int, optional (default: 64)The smallest allowable connected component size.connectivity : int, {1, 2, ..., ar.ndim}, optional (default: 1)The connectivity defining the neighborhood of a pixel.in_place : bool, optional (default: False)If `True`, remove the connected components in the input array itself.Otherwise, make a copy.Raises------TypeErrorIf the input array is of an invalid type, such as float or string.ValueErrorIf the input array contains negative values.Returns-------out : ndarray, same shape and type as input `ar`The input array with small connected components removed.Examples-------->>> from skimage import morphology>>> a = np.array([[0, 0, 0, 1, 0],...               [1, 1, 1, 0, 0],...               [1, 1, 1, 0, 1]], bool)>>> b = morphology.remove_small_objects(a, 6)>>> barray([[False, False, False, False, False],[ True,  True,  True, False, False],[ True,  True,  True, False, False]], dtype=bool)>>> c = morphology.remove_small_objects(a, 7, connectivity=2)>>> carray([[False, False, False,  True, False],[ True,  True,  True, False, False],[ True,  True,  True, False, False]], dtype=bool)>>> d = morphology.remove_small_objects(a, 6, in_place=True)>>> d is aTrueskeletonize(image)Return the skeleton of a binary image.Thinning is used to reduce each connected component in a binary imageto a single-pixel wide skeleton.Parameters----------image : numpy.ndarrayA binary image containing the objects to be skeletonized. '1'represents foreground, and '0' represents background. Italso accepts arrays of boolean values where True is foreground.Returns-------skeleton : ndarrayA matrix containing the thinned image.See also--------medial_axisNotes-----The algorithm [1]_ works by making successive passes of the image,removing pixels on object borders. This continues until nomore pixels can be removed.  The image is correlated with amask that assigns each pixel a number in the range [0...255]corresponding to each possible pattern of its 8 neighbouringpixels. A look up table is then used to assign the pixels avalue of 0, 1, 2 or 3, which are selectively removed duringthe iterations.Note that this algorithm will give different results than amedial axis transform, which is also often referred to as"skeletonization".References----------.. [1] 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.Examples-------->>> X, Y = np.ogrid[0:9, 0:9]>>> ellipse = (1./3 * (X - 4)**2 + (Y - 4)**2 < 3**2).astype(np.uint8)>>> ellipsearray([[0, 0, 0, 1, 1, 1, 0, 0, 0],[0, 0, 1, 1, 1, 1, 1, 0, 0],[0, 0, 1, 1, 1, 1, 1, 0, 0],[0, 0, 1, 1, 1, 1, 1, 0, 0],[0, 0, 1, 1, 1, 1, 1, 0, 0],[0, 0, 1, 1, 1, 1, 1, 0, 0],[0, 0, 1, 1, 1, 1, 1, 0, 0],[0, 0, 1, 1, 1, 1, 1, 0, 0],[0, 0, 0, 1, 1, 1, 0, 0, 0]], dtype=uint8)>>> skel = skeletonize(ellipse)>>> skel.astype(np.uint8)array([[0, 0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 1, 0, 0, 0, 0],[0, 0, 0, 0, 1, 0, 0, 0, 0],[0, 0, 0, 0, 1, 0, 0, 0, 0],[0, 0, 0, 0, 1, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)skeletonize_3d(img)Compute the skeleton of a binary image.Thinning is used to reduce each connected component in a binary imageto a single-pixel wide skeleton.Parameters----------img : ndarray, 2D or 3DA binary image containing the objects to be skeletonized. Zerosrepresent background, nonzero values are foreground.Returns-------skeleton : ndarrayThe thinned image.See also--------skeletonize, medial_axisNotes-----The method of [Lee94]_ uses an octree data structure to examine a 3x3x3neighborhood of a pixel. The algorithm proceeds by iteratively sweepingover the image, and removing pixels at each iteration until the imagestops changing. Each iteration consists of two steps: first, a list ofcandidates for removal is assembled; then pixels from this list arerechecked sequentially, to better preserve connectivity of the image.The algorithm this function implements is different from the algorithmsused by either `skeletonize` or `medial_axis`, thus for 2D images theresults produced by this function are generally different.References----------.. [Lee94] T.-C. Lee, R.L. Kashyap and C.-N. Chu, Building skeleton modelsvia 3-D medial surface/axis thinning algorithms.Computer Vision, Graphics, and Image Processing, 56(6):462-478, 1994.square(width, dtype=<type 'numpy.uint8'>)Generates a flat, square-shaped structuring element.Every pixel along the perimeter has a chessboard distanceno greater than radius (radius=floor(width/2)) pixels.Parameters----------width : intThe width and height of the square.Other Parameters----------------dtype : data-typeThe data type of the structuring element.Returns-------selem : ndarrayA structuring element consisting only of ones, i.e. everypixel belongs to the neighborhood.watershed(image, markers, connectivity=None, offset=None, mask=None)Return a matrix labeled using the watershed segmentation algorithmParameters----------image: ndarray (2-D, 3-D, ...) of integersData array where the lowest value points are labeled first.markers: ndarray of the same shape as `image`An array marking the basins with the values to be assigned in thelabel matrix. Zero means not a marker. This array should be of aninteger type.connectivity: ndarray, optionalAn array with the same number of dimensions as `image` whosenon-zero elements indicate neighbors for connection.Following the scipy convention, default is a one-connected array ofthe dimension of the image.offset: array_like of shape image.ndim, optionaloffset of the connectivity (one offset per dimension)mask: ndarray of bools or 0s and 1s, optionalArray of same shape as `image`. Only points at which mask == Truewill be labeled.Returns-------out: ndarrayA labeled matrix of the same type and shape as markersSee also--------skimage.segmentation.random_walker: random walker segmentationA segmentation algorithm based on anisotropic diffusion, usuallyslower than the watershed but with good results on noisy data andboundaries with holes.Notes-----This function implements a watershed algorithm [1]_that apportions pixelsinto marked basins. The algorithm uses a priority queue to hold the pixelswith the metric for the priority queue being pixel value, then the time ofentry into the queue - this settles ties in favor of the closest marker.Some ideas taken fromSoille, "Automated Basin Delineation from Digital Elevation Models UsingMathematical Morphology", Signal Processing 20 (1990) 171-182The most important insight in the paper is that entry time onto the queuesolves two problems: a pixel should be assigned to the neighbor with thelargest gradient or, if there is no gradient, pixels on a plateau shouldbe split between markers on opposite sides.This implementation converts all arguments to specific, lowest commondenominator types, then passes these to a C algorithm.Markers can be determined manually, or automatically using for examplethe local minima of the gradient of the image, or the local maxima of thedistance function to the background for separating overlapping objects(see example).References----------.. [1] http://en.wikipedia.org/wiki/Watershed_%28image_processing%29.. [2] http://cmm.ensmp.fr/~beucher/wtshed.htmlExamples--------The watershed algorithm is very useful to separate overlapping objects>>> # Generate an initial image with two overlapping circles>>> x, y = np.indices((80, 80))>>> x1, y1, x2, y2 = 28, 28, 44, 52>>> r1, r2 = 16, 20>>> mask_circle1 = (x - x1)**2 + (y - y1)**2 < r1**2>>> mask_circle2 = (x - x2)**2 + (y - y2)**2 < r2**2>>> image = np.logical_or(mask_circle1, mask_circle2)>>> # Now we want to separate the two objects in image>>> # Generate the markers as local maxima of the distance>>> # to the background>>> from scipy import ndimage as ndi>>> distance = ndi.distance_transform_edt(image)>>> from skimage.feature import peak_local_max>>> local_maxi = peak_local_max(distance, labels=image,...                             footprint=np.ones((3, 3)),...                             indices=False)>>> markers = ndi.label(local_maxi)[0]>>> labels = watershed(-distance, markers, mask=image)The algorithm works also for 3-D images, and can be used for example toseparate overlapping spheres.white_tophat(image, selem=None, *args, **kwargs)Return white top hat of an image.The white top hat of an image is defined as the image minus itsmorphological opening. This operation returns the bright spots of the imagethat are smaller than the structuring element.Parameters----------image : ndarrayImage array.selem : ndarray, optionalThe neighborhood expressed as an array of 1's and 0's.If None, use cross-shaped structuring element (connectivity=1).out : ndarray, optionalThe array to store the result of the morphology. If Noneis passed, a new array will be allocated.Returns-------out : array, same shape and type as `image`The result of the morphological white top hat.Examples-------->>> # Subtract grey background from bright peak>>> import numpy as np>>> from skimage.morphology import square>>> bright_on_grey = np.array([[2, 3, 3, 3, 2],...                            [3, 4, 5, 4, 3],...                            [3, 5, 9, 5, 3],...                            [3, 4, 5, 4, 3],...                            [2, 3, 3, 3, 2]], dtype=np.uint8)>>> white_tophat(bright_on_grey, square(3))array([[0, 0, 0, 0, 0],[0, 0, 1, 0, 0],[0, 1, 5, 1, 0],[0, 0, 1, 0, 0],[0, 0, 0, 0, 0]], dtype=uint8)DATA__all__ = ['binary_erosion', 'binary_dilation', 'binary_opening', 'bin...

想看看所有函数有哪些?
dir(skimage.morphology)
['__all__','__builtins__','__doc__','__file__','__name__','__package__','__path__','_convex_hull','_skeletonize','_skeletonize_3d','_skeletonize_3d_cy','_skeletonize_cy','_watershed','ball','binary','binary_closing','binary_dilation','binary_erosion','binary_opening','black_tophat','closing','convex_hull','convex_hull_image','convex_hull_object','cube','diamond','dilation','disk','erosion','grey','greyreconstruct','label','medial_axis','misc','octagon','octahedron','opening','reconstruction','rectangle','remove_small_holes','remove_small_objects','selem','skeletonize','skeletonize_3d','square','star','watershed','white_tophat']

skimage图像处理库相关推荐

  1. python 图像分析自然纹理方向与粗细代码_python skimage图像处理(二)

    python skimage图像处理(二) 图像简单滤波 对图像进行滤波,可以有两种效果:一种是平滑滤波,用来抑制噪声:另一种是微分算子,可以用来检测边缘和特征提取. skimage库中通过filte ...

  2. Python中最常用十大图像处理库详细介绍

    本文主要介绍了一些简单易懂最常用的Python图像处理库 当今世界充满了各种数据,而图像是其中高的重要组成部分.然而,若想其有所应用,我们需要对这些图像进行处理.图像处理是分析和操纵数字图像的过程,旨 ...

  3. pilt图像处理_详解python opencv、scikit-image和PIL图像处理库比较

    进行深度学习时,对图像进行预处理的过程是非常重要的,使用pytorch或者TensorFlow时需要对图像进行预处理以及展示来观看处理效果,因此对python中的图像处理框架进行图像的读取和基本变换的 ...

  4. python图像库_Python常用图像处理库整理

    1. 库简介 深度学习领域,对视频图片样本的处理占了很大一部分比重. 而Python环境下的图像处理库种类较多,无论是精度,速度等方面都有不同的差异,这里予以总结. Python环境下,相关的包有: ...

  5. Python的图像处理库(OpenCV,PIL,matplotlib和scikit-image)

      目前接触过的python图像处理代码涉及到多种的图像库,其中最常用的当属opencv和PIL.惭愧的是,以前只是拿来用,却一直迷惑为什么不同的代码会选择不同的图像库.这些图像库的联系和区别又是什么 ...

  6. Python图像处理【2】探索Python图像处理库

    探索Python图像处理库 0. 前言 1. 利用 scikit-image 绘制图像 2. 使用 SciPy 模块裁剪/调整图像大小 3. 使用 OpenCV 绘制轮廓 3.1 轮廓简介 3.2 绘 ...

  7. python下医学图像处理库的安装问题(更新中)

    1. pip install dipy:DIPY is a python toolbox for analysis of MR diffusion imaging. 2. pip install ni ...

  8. python图形库哪个好_Python下的图像处理库,你要选哪个?

    在进行数字图像处理时,我们经常需要对图像进行读取.保存.缩放.裁剪.旋转.颜色转换等基本操作.在使用python进行编程时,涉及到多个不同的图像处理库的选择,今天我们简单聊一聊这几个库:opencv. ...

  9. Python中常用图像处理库

    Python中常用图像处理库 文章目录 Python中常用图像处理库 1 OpenCV-Python 2 Numpy 3 matplotlib 4 skimage 5 PIL(Python Imagi ...

最新文章

  1. eclipse java调用c 代码吗_linux下通过eclipse开发用java调用c程序的方法
  2. 热烈庆祝“mysql 集群数据库架构成功”
  3. matlab求adc信号的信噪比,关于ADC的信噪比 - pengyouxiaohui的日志 - EETOP 创芯网论坛 (原名:电子顶级开发网) -...
  4. 大学计算机基础课程报告python-基于Python的“大学计算机基础”课程教学设计.doc...
  5. python中的模块和包
  6. web常见几种处理图标方法 【转】
  7. Android屏幕适应详解(一)
  8. 情怀java手机网游_经典端游移植手游 “情怀”赋予老IP全新活力
  9. Ubuntu终端Terminal常用快捷键
  10. C#中LINQ与数据管道
  11. 5.修改本地库/远程仓库的地址
  12. php ldap ad 登录验证,PHP中的LDAP身份验证 – 无需密码即可进行身份验证
  13. uestc--758--P酱的冒险旅途
  14. 矩阵特征值和特征向量matlab,MATLAB计算矩阵特征值和特征向量
  15. 怎么禁止恢复微信聊天记录?学会这几招以备不时之需
  16. 高等数学(第七版)同济大学 习题6-2 (后18题)个人解答
  17. STM32--汇编语言:子程呼叫与无条件跳转指令B、BL、BX和BLX
  18. 古诗词的直译和韵译有什么区别?看看就知道了
  19. 第 13 章 可扩展性设计之 MySQL Replication
  20. [学习笔记]数据与科学训练营之三:统计学

热门文章

  1. 51单片机——定时器2使用
  2. 【自动控制原理笔记】频率特性的几何表示法
  3. html input标签 单选按钮 radio
  4. normalized correlation 归一化相关系数
  5. 反对人工智能的九条意见!
  6. 机器学习 舆情监控_机器学习监控它是什么以及我们缺少什么
  7. matlab ar 函数确阶,matlabar模型阶数
  8. 公众号、小程序、App对比分析
  9. 使用weeklyCalendar实现周历控件
  10. 华为鸿蒙商标图片,燃爆!华为操作系统叫“鸿蒙”!商标可以组成一部“神话史”……...