2

Note that I have read answers to questions of the same issue but no one is like mine.

I loaded a picture in OpenCV and displayed it. Everything is fine.

Now I want to set black pixels to blue, so I run this:

for i in range(image.shape[0]):
    for j in range(image.shape[1]):
       if image[i,j,0]==0 and image[i,j,1]==0 and image[i,j,2]==0:
          image[i,j,0]=255

I got this error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Nota Bene:

  • The notations image[i,j,0], image[i,j,1] and image[i,j,2] underline the value of the channel of a pixel (BGR= Blue Green Red) so it is not an array as this error message says. So strange if Python does not understand itself.

  • When I run print image[i,j,x], with x =0,1,2 I get normal behavior for random values of i and j. That is, I get the values of those 3 channels correctly.

KillianDS
  • 16,936
  • 4
  • 61
  • 70
  • Try replacing your condition check with this: `if (image[i,j,0]==0) & (image[i,j,0]==0) & (image[i,j,0]==0):` I think the problem here is that when comparing arrays you have to use the bitwise operators, additonally you have to use brackets because of operator precedecnce – EdChum Mar 06 '15 at 14:16
  • To give some context around EdChum's answer: http://stackoverflow.com/questions/10062954/valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous – Yannick Meeus Mar 06 '15 at 14:16
  • @EdChum I did what you said, but trust me it tells me exactly the same error message –  Mar 06 '15 at 14:18
  • @YannickMeeus Thanks. I did but same error. Also, note that image[i,j,0] for example is not an array but just the first color channel of a pixel i, j (blue) –  Mar 06 '15 at 14:20
  • 2
    EdChum is definitely right about this, so there may be something up with your array. Have you tried `print image[3,3,0], image[3,3,1], image[3,3,2]` for example. (Note the different indexes on the last axis: in your question they're all 0. – xnx Mar 06 '15 at 14:24
  • @xnx it is just a typo, thank you, in my original program it is as i edited it now, and the printing works fine for random values of i and j –  Mar 06 '15 at 14:29
  • @KillianDS Thank you. But I had this issue since yesterday morning and tried all what I could read similar to my issue here, so I asked a moment ago –  Mar 06 '15 at 14:39
  • What line does the traceback point to? – Robert Kern Mar 06 '15 at 14:54
  • @RobertKern thank you. The trackedback point is the line where there is `if` –  Mar 06 '15 at 14:56

1 Answers1

1

Try this:

import numpy as np

image[np.all(image == 0, axis=-1)] = [255, 0, 0]

Here you check only the Z axis using numpy operations, and replace it with blue for which the pixel channels are all 0. It is an infinity quicker (at least for large images) and is also less devious.

Sander
  • 591
  • 6
  • 16