2

I have a 2d array that i got from and image, for now it has 0s and 255s, I want to change all the 255s into 1s, this is a very easy task for a for loop.

for i in range(lenX):
    for j in range(lenY):
        if img[i,j]==255:
            img[i,j] = 1

here img is my array. I am pretty sure that there is a simpler way to do it using some kind of numpy function or something. but I looked every where I couldn't find.

If you know how to do this easily.. please help me

2
  • Try this stackoverflow.com/questions/19666626/… Commented Feb 12, 2019 at 7:55
  • You shouldn't use explicit for loops like that because the operation is vectorized. Commented Feb 12, 2019 at 7:56

2 Answers 2

6

This way you can modify matrix with conditions without loops

img[img==255]=1
Sign up to request clarification or add additional context in comments.

Comments

5

Use np.where

import numpy as np 

a = np.array([[1,9,1],[12,15,255],[255,1,245],[23,255,255]]) 
a = np.where(a==255, 1, a)
print(a)

Output:

[[  1   9   1]                                                                                                                                                    
 [ 12  15   1]                                                                                                                                                    
 [  1   1 245]                                                                                                                                                    
 [ 23   1   1]] 

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.