2021-08-04
作者:互联网
利用Numpy分割矩阵
应用场景:滑动窗口计算
import numpy as np
import re
def window(array, width, height):
"""
将array分割成若干小窗口
"""
# 判断是否符合条件
_rowCount, _colCount = array.shape
if _rowCount % height or _colCount % width:
raise ValueError('please input suitable width/height value')
# 计算最终生成shape
rowCount, colCount = int(_rowCount / height), int(_colCount / width)
# 字节数
bytesN = int(int(re.match('[a-zA-Z]+(\d+)', str(array.dtype)).group(1)) / 8)
# 生成目标矩阵
target = np.lib.stride_tricks.as_strided(array, shape=(rowCount, colCount, height, width), strides=(height * _colCount * bytesN, width * bytesN, *array.strides))
print(target)
return target
window(np.array([i for i in range(1, 82)]).reshape(9, 9) / 1.0, 3, 3)
运行结果
[[[[ 1. 2. 3.]
[10. 11. 12.]
[19. 20. 21.]]
[[ 4. 5. 6.]
[13. 14. 15.]
[22. 23. 24.]]
[[ 7. 8. 9.]
[16. 17. 18.]
[25. 26. 27.]]]
[[[28. 29. 30.]
[37. 38. 39.]
[46. 47. 48.]]
[[31. 32. 33.]
[40. 41. 42.]
[49. 50. 51.]]
[[34. 35. 36.]
[43. 44. 45.]
[52. 53. 54.]]]
[[[55. 56. 57.]
[64. 65. 66.]
[73. 74. 75.]]
[[58. 59. 60.]
[67. 68. 69.]
[76. 77. 78.]]
[[61. 62. 63.]
[70. 71. 72.]
[79. 80. 81.]]]]
标签:04,rowCount,int,08,height,width,colCount,2021,array 来源: https://blog.csdn.net/weixin_44092702/article/details/120750091