如何将函数应用于numpy数组中的每个第3轴元素? [英] How to apply a function to each 3rd axis element in a numpy array?
本文介绍了如何将函数应用于numpy数组中的每个第3轴元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个像这样的numpy数组:
If I have a numpy array like so:
[[[137 153 135]
[138 154 136]
[138 153 138]
...,
[134 159 153]
[136 159 153]
[135 158 152]]
...,
[ 57 44 34]
[ 55 47 37]
[ 55 47 37]]]
如何对每个[000 000 000]个条目应用一个函数,对其进行修改?
How can I apply a function to each [000 000 000] entry, modifying it?
# a = numpy array
for x in a:
for y in x:
y = modify(y)
我想要实现的是修改PIL图像中的每个(r,g,b)像素,这些像素已转换为numpy数组.
What I'd like to achieve is modifying each (r,g,b) pixel in a PIL image that was converted to a numpy array.
推荐答案
一个简单的答案是
for row in a:
for item in row:
item[:] = modify(item)
但是,这并不是很有效.一个有效的解决方案应避免Python在所有像素上循环. (这就是NumPy的全部意义-向量化您的代码!)手头案件的向量化版本将是
This won't be very efficient, though. An efficient solution should avoid Python loops over all pixels. (That's somehow what NumPy is all about -- vectorise your code!) A vectorised version for the case at hand would be
r, g, b = a[..., 0], a[..., 1], a[..., 2]
new_a = numpy.empty_like(a)
new_a.fill(255)
new_a[(r != a.max(axis=2)) | (r <= 125) | (g >= 70) | (b >= 110), 1:] = 0
这篇关于如何将函数应用于numpy数组中的每个第3轴元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文