如何将函数应用于 numpy 数组中的每个第三轴元素?

发布于 2024-12-10 04:57:46 字数 403 浏览 0 评论 0原文

如果我有一个像这样的 numpy 数组:

[[[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] 条目并修改它?

# a = numpy array
for x in a:
    for y in x:
        y = modify(y)

我想要实现的是修改已转换为 numpy 数组的 PIL 图像中的每个(r,g,b)像素。

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]]]

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)

What I'd like to achieve is modifying each (r,g,b) pixel in a PIL image that was converted to a numpy array.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

雨的味道风的声音 2024-12-17 04:57:46

对你的问题的一个简单回答是

for row in a:
    for item in row:
        item[:] = modify(item)

,但这不会很有效。有效的解决方案应该避免对所有像素进行 Python 循环。 (这就是 NumPy 的全部内容——矢量化你的代码!)手头的情况的矢量化版本将是

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

A simple answer to your question is

for row in a:
    for item in row:
        item[:] = modify(item)

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
掀纱窥君容 2024-12-17 04:57:46

y 有你的 RGB 数组,不是吗?

for row in a:
    for px in row:
        px[0] = 255 - px[0]
        px[1] = 255 - px[1]
        px[2] = 255 - px[2]

或者更一般地说:

for row in a:
    for px in row:
        n = modify(px)
        px[0] = n[0]
        px[1] = n[1]
        px[2] = n[2]

y there is your rgb array, isn't it?

for row in a:
    for px in row:
        px[0] = 255 - px[0]
        px[1] = 255 - px[1]
        px[2] = 255 - px[2]

or more generally:

for row in a:
    for px in row:
        n = modify(px)
        px[0] = n[0]
        px[1] = n[1]
        px[2] = n[2]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文