2

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.

7
  • 1
    What does modify() exactly do? It is easy to give an answer to this question, but we can only give an efficient answer if we know what modify() does. Commented Oct 14, 2011 at 13:13
  • def modify(px): r,g,b = px if r == max(r,g,b) and r > 125 and g < 70 and b < 110: return (255,0,0) else: return (255,255,255) Commented Oct 14, 2011 at 13:16
  • There's a bracket missing, no? Commented Oct 14, 2011 at 13:18
  • Please add this to your question. Commented Oct 14, 2011 at 13:19
  • 1
    @Rabarberski: It's relevant to give an efficient answer. Just time the two versions given in my answer for an image of -- say -- 2000x2000 pixels. You'll see the vectorised version is orders of magnitude faster. Python loops over every single pixel are usually to slow for image processing. Commented Oct 14, 2011 at 13:33

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.