1

我正在尝试在 Python 中加速一个简单的对称居中图像下采样算法。我已经使用一种天真的方法作为下限基准对其进行了编码,但是我希望它能够更快地工作。

为简单起见,我的图像是一个分辨率为 4608x4608 的圆(我将使用此比例的分辨率),我希望将图像下采样 9 倍(即 512x512)。下面是我生成的代码,它以高分辨率创建图像并将其下采样 9 倍。

所有这些基本上都是从高分辨率映射一个像素。空间到低分辨率空间中的一个(围绕质心对称),并将给定高分辨率区域中的所有像素与低分辨率的一个像素相加。

import numpy as np
import matplotlib.pyplot as plt
import time

print 'rendering circle at high res'

# image dimensions.
dim = 4608

# generate high sampled image.
xx, yy = np.mgrid[:dim, :dim]
highRes = (xx - dim/2) ** 2 + (yy - dim/2) ** 2
print 'render done'

print 'downsampling'
t0 = time.time()

# center of the high sampled image.
cen = dim/2
ds = 9

# calculate offsets.
x = 0
offset = (x-cen+ds/2+dim)/ds

# calculate the downsample dimension.
x = dim-1
dsdim = 1 + (x-cen+ds/2+dim)/ds - offset

# generate a blank downsampled image.
lowRes = np.zeros((dsdim, dsdim))

for y in range(0, dim):
    yy = (y-cen+ds/2+dim)/ds - offset
    for x in range(0, dim):
        xx = (x-cen+ds/2+dim)/ds - offset
        lowRes[yy, xx] += highRes[y, x]

t1 = time.time()
total = t1-t0
print 'time taken %f seconds' % total 

我在我的机器上设置了 BLAS 和 LAPACK 的 numpy ,我知道利用这一点可以获得显着的收益,但是我对如何进行有点困惑。这是我迄今为止的进步。

import numpy as np
import matplotlib.pyplot as plt
import time

print 'rendering circle at high res'

# image dimensions.
dim = 4608

# generate high sampled image.
xx, yy = np.mgrid[:dim, :dim]
highRes = (xx - dim/2) ** 2 + (yy - dim/2) ** 2
print 'render done'

print 'downsampling'
t0 = time.time()

# center of the high sampled image.
cen = dim/2
ds = 9

# calculate offsets.
x = 0
offset = (x-cen+ds/2+dim)/ds

# calculate the downsample dimension.
x = dim-1
dsdim = 1 + (x-cen+ds/2+dim)/ds - offset

# generate a blank downsampled image.
lowRes = np.zeros((dsdim, dsdim))

ar = np.arange(0, dim)
x, y = np.meshgrid(ar, ar)

# calculating symettrically centriod positions.
yy = (y-cen+ds/2+dim)/ds - offset
xx = (x-cen+ds/2+dim)/ds - offset

# to-do : code to map xx, yy into lowRes

t1 = time.time()
total = t1-t0

print 'time taken %f seconds' % total

这个当前版本在我的机器上快了大约 16 倍,但它并不完整。我不确定如何从高分辨率映射新的下采样像素。图像有效。

可能有另一种方法可以加快速度?不确定...谢谢!

4

0 回答 0