【发布时间】:2015-07-18 11:57:35
【问题描述】:
问:如何加快速度?
下面是我对 Matlab 的 im2col 'sliding' 的实现,它具有返回每第 n 列的附加功能。该函数获取一个图像(或任何 2 个暗淡数组)并从左到右、从上到下滑动,选取给定大小的每个重叠子图像,并返回一个其列是子图像的数组。
import numpy as np
def im2col_sliding(image, block_size, skip=1):
rows, cols = image.shape
horz_blocks = cols - block_size[1] + 1
vert_blocks = rows - block_size[0] + 1
output_vectors = np.zeros((block_size[0] * block_size[1], horz_blocks * vert_blocks))
itr = 0
for v_b in xrange(vert_blocks):
for h_b in xrange(horz_blocks):
output_vectors[:, itr] = image[v_b: v_b + block_size[0], h_b: h_b + block_size[1]].ravel()
itr += 1
return output_vectors[:, ::skip]
示例:
a = np.arange(16).reshape(4, 4)
print a
print im2col_sliding(a, (2, 2)) # return every overlapping 2x2 patch
print im2col_sliding(a, (2, 2), 4) # return every 4th vector
返回:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
[[ 0. 1. 2. 4. 5. 6. 8. 9. 10.]
[ 1. 2. 3. 5. 6. 7. 9. 10. 11.]
[ 4. 5. 6. 8. 9. 10. 12. 13. 14.]
[ 5. 6. 7. 9. 10. 11. 13. 14. 15.]]
[[ 0. 5. 10.]
[ 1. 6. 11.]
[ 4. 9. 14.]
[ 5. 10. 15.]]
性能不是很好,特别是考虑到我是否调用im2col_sliding(big_matrix, (8, 8))(62001 列)或im2col_sliding(big_matrix, (8, 8), 10)(6201 列;仅保留每 10 个向量)将花费相同的时间 [其中 big_matrix 的大小256 x 256]。
我正在寻找任何想法来加快速度。
【问题讨论】:
-
this 回答对您有帮助吗?或者您是否专门寻找您的代码的加速?
-
@ljetibo 我已经查看并使用了该帖子中接受的答案,但没有将其扩展为我想要的。我愿意接受任何解决方案。
标签: python performance python-2.7 image-processing numpy