简体   繁体   中英

How to apply a function to each 3rd axis element in a numpy array?

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.

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM