本文由我司收集整编,推荐下载,如有疑问,请与我司联系
numpy:
如何快速转换数组类型
2009/12/11 34762
I find the astype() method of numpy arrays not very efficient. I
have an array containing 3 million of Uint8 point. Multiplying it by a 3x3 matrix takes 2
second, but converting the result from uint16 to uint8 takes another second.
我发现
numpy
数组的
astype()
方法不是很有效。我有一个包含
300
万个
Uint8
点的
数组。乘以一个
3x3
矩阵需要
2
秒,但是把结果从
uint16
转换成
uint8
需要另一
秒。
More precisely :
更准确地说应该是
:
print time.clock() imgarray = np.dot(imgarray, M)/255 print time.clock() imgarray =
imgarray.clip(0, 255) print time.clock() imgarray = imgarray.astype(‘B’) print time.clock()
dot product and scaling takes 2 sec clipping takes 200 msec type conversion takes 1 sec
点积和缩放需要
2
秒的剪辑需要
200
秒的类型转换需要
1
秒
Given the time taken by the other operations, I would expect astype to be faster. Is there
a faster way to do type conversion, or am I wrong when guesstimating that type conversion
should not be that hard ?
考虑到其他操作所花费的时间,我预计
astype
会更快。是否有一种更快的方式来
进行类型转换,或者当我猜测类型转换不应该那么困难时,我错了吗
?
Edit : the goal is to save the final 8 bit array to a file
编辑
:
目标是将最后的
8
位数组保存到一个文件中
24
When you use imgarray = imgarray.astype(‘B’), you get a copy of the array, cast to the
specified type. This requires extra memory allocation, even though you immediately flip
imgarray to point to the newly allocated array.
当您使用
imgarray = imgarray.astype(‘B’)
时,您将获得该数组的副本,并将其转换
为指定的类型。这需要额外的内存分配,纵然您立即翻转
imgarray
来指向新分配的