gpt4 book ai didi

使用 numpy 快速降低图像分辨率的 Python 代码

转载 作者:太空宇宙 更新时间:2023-11-03 17:52:46 26 4
gpt4 key购买 nike

下面的代码通过将小像素合并为较大像素来降低 2D numpy 数组(图像)的分辨率。我想知道它是否可以做得更快,或者是否有更快的替代方案。此外,任何一般建议都会受到赞赏。例如,如果有一个代码速度相似,但生成更平滑的缩小图像(例如通过使用样条线)

import numpy as np

def reduce_img ( img, bin_fac=1 ):
assert( len( img.shape ) == 2 )
imgX0 = img.shape[0] # slow axis
imgX1 = img.shape[1] # fast axis

r0 = imgX0 % bin_fac
r1 = imgX1 % bin_fac

img = np.copy( img) [:imgX0 - r0, :imgX1-r1]
# bin the fast axis
img_C = img.ravel(order='C')
img = np.average( [ img_C[i::bin_fac] for i in xrange( bin_fac ) ],axis=0)
img = img.reshape( (imgX0-r0, (imgX1-r1)/bin_fac ) , order='C')

# bin the slow axis
img_F = img.ravel(order='F')
img = np.average( [ img_F[i::bin_fac] for i in xrange( bin_fac ) ],axis=0)
img = img.reshape( ((imgX0-r0)/bin_fac, (imgX1-r1)/bin_fac ), order='F' )

return img

这是一个结果

>> from pylab import *
>> imshow( img )
>> show()

test image

>> img_r = reduce_img( img, bin_fac = 7 )
>> imshow( img_r )
>> show()

test image reduced

>> %timeit( reduce_img( img, bin_fac=7)  )
1000 loops, best of 3: 655 µs per loop

最佳答案

我首先要提到的是,您的分箱方式似乎相当不寻常,我想这就是@ljetibo 在评论中所指的内容。在“优化”演讲之后我会再回到这个话题。

首先,您可以通过删除对 np.copy 的多余调用来稍微改进您的代码,因为您只是重新绑定(bind) img 到传入的 img View 。 ravel 操作将返回一个副本,除非图像形状是分箱因子 bin_fac 的倍数。

现在,虽然列表推导速度很快,但您正在从可能不连续的列表重新创建 numpy 数组,这意味着您再次将内存从一个位置复制到另一个位置。这些都是会降低效率的操作。

您可能感兴趣的只是在原始图像上生成高内存效率的 View 。这就是 as_strided 发挥作用的地方:

from numpy.lib.stride_tricks import as_strided

def strided_rescale(g, bin_fac):
strided = as_strided(g,
shape=(g.shape[0]//bin_fac, g.shape[1]//bin_fac, bin_fac, bin_fac),
strides=((g.strides[0]*bin_fac, g.strides[1]*bin_fac)+g.strides))
return strided.mean(axis=-1).mean(axis=-1) # order is NOT important! See notes..

时序考虑表明,这通常比原始方法要快一些,随着分箱因子的增加,性能会有所提高:

In [263]: stp = 'from __main__ import img, strided_rescale, reduce_img'

In [264]: for n in range(1,21):
a = timeit.timeit(stmt='strided_rescale(img, {})'.format(n), setup=stp, number=100)
b = timeit.timeit(stmt='reduce_img(img, {})'.format(n), setup=stp, number=100)
c = b*1./a
d = np.ptp(strided_rescale(img, n) - reduce_img(img,n))
print('{a:7f} | {b:7f} | {c:1.4f} | {d:1.4g}'.format(**locals()))
.....:
0.124911 | 0.277254 | 2.2196 | 0
0.303813 | 0.171833 | 0.5656 | 0
0.217745 | 0.188637 | 0.8663 | 0
0.162199 | 0.139770 | 0.8617 | 0
0.132355 | 0.138402 | 1.0457 | 0
0.121542 | 0.160275 | 1.3187 | 0
0.102930 | 0.162041 | 1.5743 | 0
0.090694 | 0.138881 | 1.5313 | 2.384e-07
0.097320 | 0.174690 | 1.7950 | 1.788e-07
0.082376 | 0.155261 | 1.8848 | 2.384e-07
0.084228 | 0.178397 | 2.1180 | 2.98e-07
0.070411 | 0.181175 | 2.5731 | 2.98e-07
0.075443 | 0.175605 | 2.3277 | 5.96e-08
0.068964 | 0.182602 | 2.6478 | 5.96e-08
0.067155 | 0.168532 | 2.5096 | 1.192e-07
0.056193 | 0.195684 | 3.4824 | 2.98e-07
0.063575 | 0.206987 | 3.2558 | 2.98e-07
0.078850 | 0.187697 | 2.3804 | 2.384e-07
0.053072 | 0.168763 | 3.1799 | 2.384e-07
0.047512 | 0.151598 | 3.1907 | 1.788e-07
# time a | time b | b/a | peak-to-peak: check if both arrays are the same

我相信观察到的数组相等性的微小差异是由于复制操作造成的,在复制操作中,您从 numpy 数据类型返回到普通的 Python float ,反之亦然。不过我对此并不是 100% 确定。

现在优化讨论已经结束,让我们回到您的分箱方法。在当前的实现中,您已将图像分割为方形、不重叠的区域。对于这个故事的其余部分,这些子矩阵不必是正方形的,它们可以是矩形的(如果可以改变图像的纵横比),并且结论仍然有效。因此,在每个子矩阵中,您将取行方向平均值,然后取所得列向量的平均值。可以很容易地从数学角度证明这与对整个子矩阵求平均值相同。这是个好消息,因为这意味着在上面显示的 strided_rescale 函数中,您可以简单地将 return 语句替换为:

return gstr.mean(axis=(-2,-1))

这将给你带来另一个(小)速度提升。

我认为建议使用 scipy.misc.imresize是一个非常好的方法,直到我在 dtype != np.uint8 的 ndarrays 上尝试它。即使如此,也必须正确选择 mode 参数,并且它似乎只采用子矩阵的左上角:

In [39]: a = np.arange(16, dtype=np.uint8).reshape(4,4)

In [40]: a
Out[40]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]], dtype=uint8)

In [41]: imresize(a, (2,2), mode='P')
Out[41]:
array([[ 0, 2],
[ 8, 10]], dtype=uint8)

In [42]: imresize(a, (2,2), mode='L')
Out[42]:
array([[0, 1],
[6, 7]], dtype=uint8)

这可能不是您想要的。所以 stride_tricks 对于实际的分箱效果很好。如果您想要平滑调整大小行为(例如通过使用样条插值),您将关注Python图像库以及所有在幕后使用它的函数,例如OpenCV,它还提供调整大小行为 summarized in this post .

关于使用 numpy 快速降低图像分辨率的 Python 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28906298/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com