Ajinkya
Ajinkya

Reputation: 1867

Convert BGR channels apart from (1,1,1) and (0,0,0) to white (255,255,255)

I have a input image from which I have to convert all BGR channels which do not belong to [0,0,0] and [1,1,1] to white [255,255,255].

I made a code which can convert all channels except [0,0,0] to white.

import numpy as np
import cv2

for i in range (1,5):
    im = cv2.imread(str(i)+'.png')
    im[np.any(im != [0, 0, 0], axis=-1)] = [255,255,255]
    cv2.imwrite('a'+str(i)+'.png', im)

My aim is to convert all channels except [0,0,0] and [1,1,1] to white.To do that I made following changes to the code.

import numpy as np
import cv2

for i in range (1,5):
    im = cv2.imread(str(i)+'.png')
    im[np.any(im != [0, 0, 0] & im != [1,1,1], axis=-1)] = [255,255,255]
    cv2.imwrite('a'+str(i)+'.png', im)

I get this error:

Traceback (most recent call last):
  File "convert.py", line 6, in <module>
    im[np.any(im != [0, 0, 0] & im != [1,1,1], axis=-1)] = [255,255,255]
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

How to convert all image to white [255,255,255] except [0,0,0] and [1,1,1] pixels by changing the above code ?

Upvotes: 1

Views: 122

Answers (1)

gmds
gmds

Reputation: 19885

Operator precedence.

& has higher precedence than == and !=, so you need parentheses to make this work:

 im[np.any((im != [0, 0, 0]) & (im != [1, 1, 1]), axis=-1)] = [255, 255, 255]

Upvotes: 2

Related Questions