Skip to content Skip to sidebar Skip to footer

Change Every Value In A Numpy Array With A Condition

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): f

Solution 1:

This way you can modify matrix with conditions without loops

img[img==255]=1

Solution 2:

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]]

Post a Comment for "Change Every Value In A Numpy Array With A Condition"