Python 如何在这个numpy迭代中提高效率?
我正在做一个关于通过抖动将灰度图像转换为1位二进制图像的作业。我正在尝试一个简单的4x4矩阵,它将使图像比原始图像大16倍Python 如何在这个numpy迭代中提高效率?,python,image-processing,numpy,python-imaging-library,Python,Image Processing,Numpy,Python Imaging Library,我正在做一个关于通过抖动将灰度图像转换为1位二进制图像的作业。我正在尝试一个简单的4x4矩阵,它将使图像比原始图像大16倍 dithering_matrix = array([[ 0, 8, 2, 10], [12, 4, 14, 6], [ 3, 11, 1, 9], [15, 7, 13, 5]], dtype=uint8
dithering_matrix = array([[ 0, 8, 2, 10],
[12, 4, 14, 6],
[ 3, 11, 1, 9],
[15, 7, 13, 5]], dtype=uint8)
split_num = dithering_matrix.size + 1
我在im
ndarray上读了一张512x512图像,并做了以下事情:
output = list()
for row in im:
row_output = list()
for pixel in row:
pixel_matrix = ((pixel / (256 / split_num)) > dithering_matrix) * 255
row_output.append(pixel_matrix)
output.append( hstack( tuple(row_output) ) )
output_matrix = vstack( tuple(output) )
我发现输出需要8-10秒,我认为上面的im
循环花费了很多时间。在某些软件中,相同的操作通常在闪存中完成。那么有可能提高效率吗
更新: @伊格纳西奥·巴斯克斯·艾布拉姆斯 我不喜欢profiler:(我尝试了cProfile,结果很奇怪
1852971 function calls (1852778 primitive calls) in 9.127 seconds
Ordered by: internal time
List reduced from 561 to 20 due to restriction <20>
ncalls tottime percall cumtime percall filename:lineno(function)
1 6.404 6.404 9.128 9.128 a1.1.py:10(<module>)
513 0.778 0.002 0.778 0.002 {numpy.core.multiarray.concatenate
}
262144 0.616 0.000 1.243 0.000 D:\Python27\lib\site-packages\nump
y\core\shape_base.py:6(atleast_1d)
262696 0.260 0.000 0.261 0.000 {numpy.core.multiarray.array}
262656 0.228 0.000 0.487 0.000 D:\Python27\lib\site-packages\nump
y\core\numeric.py:237(asanyarray)
515 0.174 0.000 1.419 0.003 {map}
527019 0.145 0.000 0.145 0.000 {method 'append' of 'list' objects
}
1852971个函数调用(1852778个基元调用)只需9.127秒
订购人:内部时间
由于限制,名单从561个减少到20个
ncalls tottime percall cumtime percall文件名:lineno(函数)
1 6.404 6.404 9.128 9.128 a1.1.py:10()
513 0.778 0.002 0.778 0.002{numpy.core.multiarray.concatenate
}
262144 0.616 0.000 1.243 0.000 D:\Python27\lib\site packages\nump
y\core\shape\u base.py:6(至少1d)
262696 0.260 0.000 0.261 0.000{numpy.core.multiarray.array}
262656 0.228 0.000 0.487 0.000 D:\Python27\lib\site packages\nump
y\core\numeric.py:237(asanyarray)
515 0.174 0.000 1.419 0.003{map}
527019 0.145 0.000 0.145 0.000{“列表”对象的“附加”方法
}
a1.1.py的第10行是numpy import*(之前的所有注释)的第一行,这让我很困惑。如果您使用将每个像素转换为4x4子矩阵,这将使您能够摆脱Python循环:
im2 = np.kron(im, np.ones((4,4)))
dm2 = np.tile(dithering_matrix,(512,512))
out2 = ((im2 / (256 / split_num)) > dm2) * 255
在我的机器上,这大约比您的版本快20倍。im2不会用于后续计算。打字错误?