python - 图像数据的 numpy 形状的维度顺序是什么?

标签 python python-2.7 numpy scipy shapes

我正在使用 nibabel 库从 nii 文件加载数据。我在 http://nipy.org/nibabel/gettingstarted.html 阅读了 lib 的文档, 并发现

This information is available without the need to load anything of the main image data into the memory. Of course there is also access to the image data as a NumPy array

这是我加载数据及其形状的代码

import nibabel as nib
img = nib.load('example.nii')
data = img.get_data()
data = np.squeeze(data)
data = np.copy(data, order="C")
print data.shape

我得到了结果

128, 128, 64

什么是数据形状的顺序?是 WidthxHeightxDepth 吗?我的输入必须排列为 depth, height, width。所以我将使用 input=data.transpose(2,0,1)。这样对吗?谢谢大家

更新:我发现 Numpy 会按顺序读取图像 Height x Width x Depth 作为引用 http://www.python-course.eu/images/axis.jpeg

最佳答案

好的,这是我的看法:

使用 scipy.ndimage.imread('img.jpg', mode='RGB'),生成的数组将始终具有以下顺序:(H, W, D) 即(高度、宽度、深度),因为 numpy 对 ndarrays 使用的术语 (axis=0, axis=1, axis=2) 或类似的 (Y, X, Z) 如果有人想在 3 个维度上进行可视化。

# read image
In [21]: img = scipy.ndimage.imread('suza.jpg', mode='RGB')

# image shape as (H, W, D)
In [22]: img.shape
Out[22]: (634, 1366, 3)

# transpose to shape as (D, H, W)
In [23]: tr_img = img.transpose((-1, 0, 1))    

In [23]: tr_img.shape
Out[23]: (3, 634, 1366)

如果您将 img_shape 视为一个元组,

#  index    (0,   1,    2)
img_shape = (634, 1366, 3)
# or index  (-3,  -2,  -1)

选择一种便于内存的方式。


注意:scipy.ndimage.imread() API has been removed since Scipy 1.2.0 .所以,现在推荐使用imageio.imread() ,它读取图像并返回 Array,它是 numpy 数组的一个子类,遵循上面讨论的相同约定。

# read image
$ img = imageio.imread('suza.jpg', format='jpg')

# convert the image to a numpy array
$ img_np = np.asarray(img)

PS:还应该注意的是,像 tensorflow 这样的库也(几乎)遵循与 numpy 相同的约定。

tf.image_decode_jpeg()返回:

A Tensor of type uint8. 3-D with shape [height, width, channels]

关于python - 图像数据的 numpy 形状的维度顺序是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43272848/

相关文章:

python - 由于系统 Python 2.7 的要求,Pygame 安装失败,即使我有 Python 2.7

python-2.7 - 计算图中的多条边(python)

python - 生成没有上限的随机整数

python - 在 matplotlib 图形中绘制平滑曲线

python - 不可能的原因 `PyDict_DelItem`

python - 使用空格或 : 分割函数

python - SciPy 的 ctypes Fibonacci 示例无法运行,并出现 "array must have data type int64"错误

python - django rest auth 返回 AnonymousUser

python - 如何将 python 2.7 中的 bytearray 转换为十进制字符串?

python - 使用 numpy lstsq 计算残差