python - 将 numpy 3-d 数组拆分为较小 3-d 数组的 2-d 数组
问题描述
我目前将图像作为具有 3 个通道(RGB)的 numpy 数组。我想将其有效地拆分为一个由较小的 3-d 子数组组成的 2-d 数组。例如,如果我的图像形状为 (100, 100, 3),我想将其转换为 10 x 10 数组,其中元素是 (10, 10, 3) 图像(子图像),同时保持空间方向。图像的高度和宽度将始终相等。
我也想扭转整个操作。
如果这很难做到,有没有办法将其转换为行或列顺序的 4-d 数组,而元素仍然相同?
有没有一种有效的方法可以使用 numpy 方法来做到这一点?
解决方案
您可以使用 strides 来拆分数组:
image = np.arange(30000).reshape(100,100,3)
sub_shape = (10,10,3)
#divide the matrix into sub_matrices of subshape
view_shape = tuple(np.subtract(image.shape, sub_shape) + 1) + sub_shape
strides = image.strides + image.strides
sub_matrices = np.squeeze(np.lib.stride_tricks.as_strided(image,view_shape,strides)[::sub_shape[0],::sub_shape[1],:])
sub_matrices
形状:
(10, 10, 10, 10, 3)
sub_matrices[i,j,:,:,:]
是[i,j]
第-个子数组。
或者,您可以重塑图像:
sub_shape = (10,10,3)
sub_matrices = np.swapaxes(image.reshape(image.shape[0]/sub_shape[0],sub_shape[0],image.shape[1]/sub_shape[1],sub_shape[1],image.shape[3]), 1, 2)
又sub_matrices[i,j,:,:,:]
是第[i,j]
-th 个子数组。
推荐阅读
- algorithm - 在道路上保持正确的车道
- css - 仅为页面的某些部分(div)定义不同数量的 Bootstrap 4 列?
- postgresql - Postgres 表空间大小和减少
- django - Reactjs - 来自 JWT 令牌的当前用户
- java - 在 Locale.getAvailableLocales() 中找不到“ta_IN”,用于 Struts 2 中的多语言支持
- forms - 扩展 bootstrap_3_layout.html.twig 表单主题
- jboss - JBoss 7 (EAP 6) CLI 配置:在受支持的属性中找不到“队列地址”:[选择器、条目、持久]
- containers - 从有序记录集中删除一个元素 Ada
- javascript - jQuery getJSON, Autocomplete Uncaught TypeError: Cannot read property 'label' of undefined via MVC C#
- windows - 如何为 Windows 创建自定义单字节字符集?