用 python skimage做图像处理

导言:由于经常需要处理图像,习惯了matlab那么好用的图像处理工具箱,搬到python后有点不知所措了。搜了下python图像处理方面的库,好多PIL的教程,但是无奈的是PIL和numpy等结合不好,而且半天找不到图像处理的函数在哪里,只好作罢;终于搜到了skimage,:-),喜出望外,因为它是和scipy、numpy可以完美结合的,那么就可以很好的使用numpy了。废话不多说,直接上干货吧。

step 1 概览

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

import skimage
help(skimage)

看看输出:

Help on package skimage:

NAME
    skimage - Image Processing SciKit (Toolbox for SciPy)

FILE
    /usr/local/lib/python2.7/dist-packages/skimage/__init__.py

DESCRIPTION
    ``scikit-image`` (a.k.a. ``skimage``) is a collection of algorithms for image
    processing and computer vision.

    The main package of ``skimage`` only provides a few utilities for converting
    between image data types; for most features, you need to import one of the
    following subpackages:

    Subpackages
    -----------
    color
        Color space conversion.
    data
        Test images and example data.
    draw
        Drawing primitives (lines, text, etc.) that operate on NumPy arrays.
    exposure
        Image intensity adjustment, e.g., histogram equalization, etc.
    feature
        Feature detection and extraction, e.g., texture analysis corners, etc.
    filters
        Sharpening, edge finding, rank filters, thresholding, etc.
    graph
        Graph-theoretic operations, e.g., shortest paths.
    io
        Reading, saving, and displaying images and video.
    measure
        Measurement of image properties, e.g., similarity and contours.
    morphology
        Morphological operations, e.g., opening or skeletonization.
    novice
        Simplified interface for teaching purposes.
    restoration
        Restoration algorithms, e.g., deconvolution algorithms, denoising, etc.
    segmentation
        Partitioning an image into multiple regions.
    transform
        Geometric and other transforms, e.g., rotation or the Radon transform.
    util
        Generic utilities.
    viewer
        A simple graphical user interface for visualizing results and exploring
        parameters.

    Utility Functions
    -----------------
    img_as_float
        Convert an image to floating point format, with values in [0, 1].
    img_as_uint
        Convert an image to unsigned integer format, with values in [0, 65535].
    img_as_int
        Convert an image to signed integer format, with values in [-32768, 32767].
    img_as_ubyte
        Convert 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)
    filter (package)
    filters (package)
    future (package)
    graph (package)
    io (package)
    measure (package)
    morphology (package)
    novice (package)
    restoration (package)
    scripts (package)
    segmentation (package)
    setup
    transform (package)
    util (package)
    viewer (package)

FUNCTIONS
    test = _test(doctest=False, verbose=False)
        Run all unit tests.

DATA
    __SKIMAGE_SETUP__ = False
    __version__ = '0.12.3'
    data_dir = '/usr/local/lib/python2.7/dist-packages/skimage/data'
    doctest = <functools.partial object>
    doctest_verbose = <functools.partial object>
    pkg_dir = '/usr/local/lib/python2.7/dist-packages/skimage'
    test_verbose = <functools.partial object>

VERSION
    0.12.3

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

step 2 IO

我们这里看看如何读写图像文件。这个在skimage.io里面。

import skimage, skimage.io
help(skimage.io)
Help on package skimage.io in skimage:

NAME
    skimage.io - Utilities to read and write images in various formats.

FILE
    /usr/local/lib/python2.7/dist-packages/skimage/io/__init__.py

DESCRIPTION
    The following plug-ins are available:

    ========== ==============================================================
    Plugin     Description
    ---------- --------------------------------------------------------------
    pil        Image reading via the Python Imaging Library
    qt         Fast image display using the Qt library
    freeimage  Load images using the FreeImage library
    gtk        Fast image display using the GTK library
    matplotlib Display or save images using Matplotlib
    fits       FITS image reading via PyFITS
    simpleitk  Image reading and writing via SimpleITK
    imageio    Image reading via the ImageIO Library
    imread     Image reading and writing via imread
    tifffile   Load and save TIFF and TIFF-based images using tifffile.py
    gdal       Image reading via the GDAL Library (www.gdal.org)
    ========== ==============================================================

PACKAGE CONTENTS
    _image_stack
    _io
    _plugins (package)
    collection
    manage_plugins
    setup
    sift
    tests (package)
    util

DATA
    WRAP_LEN = 73
    available_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:

NAME
    skimage.morphology

FILE
    /usr/local/lib/python2.7/dist-packages/skimage/morphology/__init__.py

PACKAGE CONTENTS
    _convex_hull
    _greyreconstruct
    _skeletonize
    _skeletonize_3d
    _skeletonize_3d_cy
    _skeletonize_cy
    _watershed
    binary
    convex_hull
    grey
    greyreconstruct
    misc
    selem
    setup
    tests (package)
    watershed

FUNCTIONS
    ball(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 between
        it and the origin is no greater than radius.

        Parameters
        ----------
        radius : int
            The radius of the ball-shaped structuring element.

        Other Parameters
        ----------------
        dtype : data-type
            The data type of the structuring element.

        Returns
        -------
        selem : ndarray
            The structuring element where elements of the neighborhood
            are 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 performs
        faster for binary images.

        The morphological closing on an image is defined as a dilation followed by
        an erosion. Closing can remove small dark spots (i.e. "pepper") and connect
        small bright cracks. This tends to "close" up (dark) gaps between (bright)
        features.

        Parameters
        ----------
        image : ndarray
            Binary input image.
        selem : ndarray, optional
            The 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, optional
            The array to store the result of the morphology. If None,
            is passed, a new array will be allocated.

        Returns
        -------
        closing : ndarray of bool
            The 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 performs
        faster for binary images.

        Morphological dilation sets a pixel at ``(i,j)`` to the maximum over all
        pixels in the neighborhood centered at ``(i,j)``. Dilation enlarges bright
        regions and shrinks dark regions.

        Parameters
        ----------

        image : ndarray
            Binary input image.
        selem : ndarray, optional
            The 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, optional
            The array to store the result of the morphology. If None, is
            passed, a new array will be allocated.

        Returns
        -------
        dilated : ndarray of bool or uint
            The 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 performs
        faster for binary images.

        Morphological erosion sets a pixel at ``(i,j)`` to the minimum over all
        pixels in the neighborhood centered at ``(i,j)``. Erosion shrinks bright
        regions and enlarges dark regions.

        Parameters
        ----------
        image : ndarray
            Binary input image.
        selem : ndarray, optional
            The 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, optional
            The array to store the result of the morphology. If None is
            passed, a new array will be allocated.

        Returns
        -------
        eroded : ndarray of bool or uint
            The 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 performs
        faster for binary images.

        The morphological opening on an image is defined as an erosion followed by
        a dilation. Opening can remove small bright spots (i.e. "salt") and connect
        small dark cracks. This tends to "open" up (dark) gaps between (bright)
        features.

        Parameters
        ----------
        image : ndarray
            Binary input image.
        selem : ndarray, optional
            The 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, optional
            The array to store the result of the morphology. If None
            is passed, a new array will be allocated.

        Returns
        -------
        opening : ndarray of bool
            The 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 minus
        the original image. This operation returns the dark spots of the image that
        are smaller than the structuring element. Note that dark spots in the
        original image are bright spots after the black top hat.

        Parameters
        ----------
        image : ndarray
            Image array.
        selem : ndarray, optional
            The neighborhood expressed as a 2-D array of 1's and 0's.
            If None, use cross-shaped structuring element (connectivity=1).
        out : ndarray, optional
            The array to store the result of the morphology. If None
            is passed, a new array will be allocated.

        Returns
        -------
        opening : array, same shape and type as `image`
           The result of the black to
  • 6
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值