遍历一个numpy数组并在每个元素上进行操作 [英] Iterating over a numpy array and operating on each element
问题描述
我有一个大小为8x8的numpy数组. 这是numpy数组:
I have a numpy array of size 8x8. Here is the numpy array:
QuantTable = np.array([[16, 11 ,10, 16, 24, 40, 51, 61],
[12, 12, 14, 19, 26, 58, 60, 55],
[14, 13, 16, 24, 40, 57, 69, 56],
[14, 17, 22, 29, 51, 87, 80, 62],
[18, 22, 37, 29, 51, 87, 80, 62],
[24, 35, 55, 64, 81, 109, 103, 77],
[49, 64, 78, 87, 103, 121, 120, 101],
[72, 92, 95, 98, 112, 100, 103, 99]])
我想对数组中的元素执行操作. 我创建了一个接受比例因子值和Numpy Array的函数. 在这里:
I would like to perform the operations on the elements in the array. I have created a function that accepts a scaling factor value and a Numpy Array. Here it is:
def quantizationTable(Qval, QuantTable):
if Qval < 50:
scalingFactor = 5000/Qval
for x in range(QuantTable):
for y in range(QuantTable):
QuantTable[x][y] = ((scalingFactor * QuantTable[x][y] + 50/100)
if QuantTable[x][y] == 0:
QuantTable[x][y] = 1
return QuantTable
else:
scalingFactor = 200 - 2(Qval)
for x in range(QuantTable):
for y in range(QuantTable):
QuantTable[x][y] = ((scalingFactor * QuantTable[x][y] + 50/100)
if QuantTable[x][y] == 0:
QuantTable[x][y] = 1
return QuantTable
我在遍历numpy数组和执行我的操作时遇到了麻烦.我正在尝试应用公式 ((缩放因子值* numpy数组的元素+ 50)/100)到numpy数组的每个元素,并返回修改后的数组. 有人可以帮忙吗?
I am having trouble iterating over the numpy array and performing my operations. I am trying to apply the formula ((Scaling factor value * element of numpy array + 50)/100) to every element of the numpy array and return the modified array. Can someone please help?
推荐答案
只需删除循环和索引. Numpy会自动广播这些操作.另外,您的很多代码都可以从if...else
语句中删除.
Just remove the loops, and the indexing. Numpy automatically broadcasts those operations. Also, a lot of your code can be taken out of the if...else
statements.
def quantizationTable(Qval, QuantTable):
QuantTable = np.asarray(QuantTable, dtype=np.float32)
if int(Qval) < 50:
scalingFactor = 5000 / Qval
else:
scalingFactor = 200 - 2 * Qval # confirm that this is what you want?
QuantTable *= scalingFactor + 0.5
QuantTable[QuantTable == 0] = 1
return QuantTable
这篇关于遍历一个numpy数组并在每个元素上进行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!