1

I have a boolean numpy array which I need to convert it to binary, therefore where there is true it should be 255 and where it is false it should be 0.

Can someone point me out how to write the code?

1
  • 1
    That seems to be an odd way to define binary. Commented Jul 18, 2020 at 6:00

4 Answers 4

2
x = np.array([True, False, True, True, False]) 
x.astype(int)*255    
1

Example:

BA = np.random.randint(0,2,10,dtype=bool)
BA
# array([False,  True,  True,  True, False,  True, False,  True,  True,
#         True])

Method 1 (faster):

-BA.view('u1')
# array([  0, 255, 255, 255,   0, 255,   0, 255, 255, 255], dtype=uint8)

Method 2 (safer):

-BA.astype('u1')
# array([  0, 255, 255, 255,   0, 255,   0, 255, 255, 255], dtype=uint8)
1

just multiply by 255

In [81]: arr = np.array([True, False, True, False],dtype=bool)

In [82]: arr * 255
Out[82]: array([255,   0, 255,   0])
0

Let x be your data in numpy array Boolean format.

Try

np.where(x,255,0)

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.