scikit image - a crash course on NumPy for images

本文用来学习scikit-image的官方文档的a crash course on NumPy for images原链接

A crash course on NumPy for images

scikit-image是以NumPy数组的方式来操作图像。因此图像很大一部分的操作将是使用NumPy:

1
2
3
4
>>> from skimage import data
>>> camera = data.camera()
>>> type(camera)
<type 'numpy.ndarray'>

检索图像的几何以及像素数:

1
2
3
4
>>> camera.shape
(512, 512)
>>> camera.size
262144

检索关于灰度值的统计信息:

1
2
3
4
>>> camera.min(), camera.max()
(0, 255)
>>> camera.mean()
118.31400299072266

代表图片的NumPy数组可以是浮点数类型的不同整数。查看Image data type and what the mean获取关于这些类型的更多信息,以及scikit-image如何处理它们。

NumPy indexing

NumPy indexing能够被用来查找像素值和修改像素值。

1
2
3
4
5
>>> # Get the value of the pixel on the 10th row and 20th column
>>> camera[10, 20]
153
>>> # Set to black the pixel on the 3rd row and 10th column
>>> camera[3, 10] = 0

注意:在NumPy中,第一个维度(camera.shape[0])对应于行,第二个维度(camera.shape[1])对应于列,使用原点(camerap[0, 0])对应左上角。这符合矩阵/线性代数符号,但是与笛卡尔(x, y)坐标相反。查看Coordinate conventions笛卡尔惯例获取更多细节。

除了某个单独节点,还可以访问或修改整个像素集合,使用的是不同的NumPy的索引功能。
切片:

1
2
>>> # Set to black the ten first lines
>>> camera[:10] = 0

mask(那些使用boolean遮盖的索引):

1
2
3
>>> mask = camera < 87
>>> # Set to "white" (255) pixels where mask is True
>>> camera[mask] = 255

花式索引(使用索引集的索引)

1
2
3
>>> inds_r = np.arange(len(camera))
>>> inds_c = 4 * inds_r % len(camera)
>>> camera[inds_r, inds_c] = 0

对于选择一组像素来进行进一步的操作来说,使用mask是尤其有用的。mask可以是任何相同形状的boolean数组。这能够被用来定义一个有趣的区域,就像一块磁盘:???这一段怎么理解

1
2
3
4
5
>>> nrows, ncols = camera.shape
>>> row, col = np.ogrid[:nrows, :ncols]
>>> cnt_row, cnt_col = nrows / 2, ncols / 2
>>> outer_disk_mask = ((row - cnt_row)**2 + (col - cnt_col)**2 > (nrows / 2)**2)
>>> camera[outer_disk_mask] = 0

plot_camera_numpy_11
布尔类型的算数能够被用来定义更加复杂的masks:

1
2
3
4
>>> lower_half = row > cnt_row
>>> lower_half_disk = np.logical_and(lower_half, outer_disk_mask)
>>> camera = data.camera()
>>> camera[lower_half_disk] = 0

Color images

以上所有都是色彩图像的真实情况:一张色彩图片就是一个NumPy数组,并且带有额外的通道信息:

1
2
3
4
5
>>> cat = data.chelsea()
>>> type(cat)
<type 'numpy.ndarray'>
>>> cat.shape
(300, 451, 3)

这展示了cat是一个300*451像素的图片,并且使用了三个通道(红、绿和蓝)。像之前一样,我们能够得到并设置像素值:

1
2
3
4
5
6
>>> cat[10, 20]
array([151, 129, 115], dtype=uint8)
>>> # set the pixel at row 50, column 60 to black
>>> cat[50, 60] = 0
>>> # set the pixel at row 50, column 61 to green
>>> cat[50, 61] = [0, 255, 0] # [red, green, blue]

numpy images 1

Coordinate conventiions (坐标惯例)

因为我们使用NumPy数组来代表图片,因此我们的坐标必须响应的匹配。两维(2D)的灰度图片(类似上面的camera)是通过行和列来进行索引的(缩写为row, col或 r, c),使用最低的两个元素(0, 0)来表示左上角。在library的其他部分中,你将会看到rr和cc,用来引用行和列的坐标列表。我们将其与(x,y)区分开来,(x, y)通常标识标准的笛卡尔坐标,其中x是标准水平坐标,y是垂直坐标,原点为右下。
在彩色(或多个通道)图片的例子中,最后一个维度包含了色彩信息,并使用channel或ch来表示。
最后,对于3D图片,诸如视频、磁共振丞相扫描或共聚焦显微镜,我们