作者: Emmanuelle Gouillart
scikit-image是专注于图像处理的Python包,并且使用原生的Numpy数组作为图像对象。本章描述如何在不同图像处理任务上使用scikit-image
,并且保留了其他科学Python模块比如Numpy和Scipy的链接。
也可以看一下:对于基本图像处理,比如图像剪切或者简单过滤,大量简单操作可以用Numpy和SciPy来实现。看一下使用Numpy和Scipy图像操作和处理部分。
注意,在阅读本章之前你应该熟悉前面章节的内容,比如基础操作,比如面具和标签作为先决条件。
章节内容
scikit-image
和 SciPy
生态系统scikit-image
能发现什么图像是NumPy的数组np.ndarray
图像: | np.ndarray |
---|---|
像素: | array values: a[2, 3] |
渠道: | array dimensions |
图像编码: | dtype (np.uint8, np.uint16, np.float) |
过滤器: | functions (numpy, skimage, scipy) |
%matplotlib inline
import numpy as np
check = np.zeros((9, 9))
check[::2, 1::2] = 1
check[1::2, ::2] = 1
import matplotlib.pyplot as plt
plt.imshow(check, cmap='gray', interpolation='nearest')
<matplotlib.image.AxesImage at 0x105717610>
最新版的scikit-image
包含在大多数的科学Python发行版中,比如,Anaconda或Enthought Canopy。它也包含在 Ubuntu/Debian。
import skimage
from skimage import data # 大多数函数在子包中
大多数scikit-image
函数用NumPy ndarrays作为参数
camera = data.camera()
camera.dtype
dtype('uint8')
camera.shape
(512, 512)
from skimage import restoration
filtered_camera = restoration.denoise_bilateral(camera)
type(filtered_camera)
numpy.ndarray
其他Python包也可以用于图像处理,并且使用Numpy数组:
同时,强大的图形处理库有Python封装:
(但是,他们没有那么Pythonic也没有Numpy友好,在一定范围)。
例子库 (就像在 matplotlib 或 scikit-learn): http://scikit-image.org/docs/stable/auto_examples/ 不同类的函数,从基本的使用函数到高级最新算法。
过滤器: 函数将图像转化为其他图像。
数据简化函数: 计算图像直方图、局部极值位置、角。
其他动作: I/O, 可视化,等。
I/O: skimage.io
from skimage import io
读取文件: skimage.io.imread()
import os
filename = os.path.join(skimage.data_dir, 'camera.png')
camera = io.imread(filename)
支持所有被Python Imaging Library(或者imread
plugin
关键词提供的任何I/O插件)的数据格式。
也支持URL图片路径:
logo = io.imread('http://scikit-image.org/_static/img/logo.png')
存储文件:
io.imsave('local_logo.png', logo)
camera = data.camera()
camera.dtype
dtype('uint8')
camera_multiply = 3 * camera
可用不同的整型大小: 8-, 16- 或 32-字节, 有符号或无符号。
一个重要的 (如果有疑问的话) skimage
惯例: 图像浮点支持在[-1, 1] (与所以浮点图像相对)
from skimage import img_as_float
camera_float = img_as_float(camera)
camera.max(), camera_float.max()
(255, 1.0)
一些图像处理程序需要应用在浮点数组上,因此,输出的数组可能类型和数据范围都与输入数组不同
try:
from skimage import filters
except ImportError:
from skimage import filter as filters
camera_sobel = filters.sobel(camera)
camera_sobel.max()
0.5915023652179584
import scipy
face = scipy.misc.face()
face.shape
(768, 1024, 3)
skimage.color中包含转换不同颜色空间(RGB、HSV、LAB 等)的程序: color.rgb2hsv
、color.lab2rgb等。检查一下文档字符串了解一下输入图像期望的dtype。
3D 图像
skimage
的大多数函数可以接受3D图像作为参数。看一些文档字符串确认一下函数是否可以被用于3D图像(例如MRI或CT图像)。
练习
在硬盘上打开一个颜色图像作为Numpy数组。
找一个图像函数计算图像的直方图,并且打印每个颜色通道的直方图。
目的: 降噪、特征 (边缘) 抽取 ...
本地过滤器用一个函数替换像素临近像素的值。这个函数可以是线性或非线性的。
临近: 方块 (选择大小)、磁盘、或更复杂的结构化元素。
An important (if questionable) skimage convention: float images are supposed to lie in [-1, 1] (in order to have comparable contrast for all float images)
3.3.1. Introduction and concepts
Images are NumPy’s arrays np.ndarray