python - 如何在numpy数组中添加维度?(125, 125) 到 (125, 125, 1)
问题描述
我正在使用 OpenCV python 加载图像作为灰度图像,因为图像的形状是(125, 125)
. 但是,我需要形状是(125, 125, 1)
1 表示通道数( 1 因为它是灰度的)。
img = cv2.imread('/path/to/image.png', 0)
print(img.shape)
# prints (125, 125)
现在,我需要将img
的形状转换为(125, 125, 1)
解决方案
尝试np.expand_dims
:
In [1]: import numpy as np
In [2]: img = np.ones((125, 125))
In [3]: img.shape
Out[3]: (125, 125)
In [4]: img = np.expand_dims(img, axis=-1)
In [5]: img.shape
Out[5]: (125, 125, 1)
推荐阅读
- android - CSS scale() 不适用于 Android Chrome 70 和其他版本
- ruby - Rake 和 Ansible 有什么区别?
- ios - 如果我没有 nstring 直接显示它,如何在 UITextView 中显示 HTML 文件?
- python - 在 Python 中实现事件处理程序
- javascript - AJAX 调用在脚本的其余部分后完成
- python-3.x - 将特定字符串更改为多维数组中的浮点数
- python - 如何使用 ssh 在远程机器上运行 python 脚本
- aurelia - 动态提供 Aurelia 视图模型实例
- tensorflow - 指定的输出数组“TFlite_Detection_PostProcess”不是由该图中的任何操作产生的”,即使它存在于图中
- java - Thymeleaf 内容助手不使用 Spring Boot