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

Sociopath
  • 13,068
  • 19
  • 47
  • 75
Eshaka
  • 974
  • 1
  • 14
  • 38
  • Try this https://stackoverflow.com/questions/19666626/replace-all-elements-of-python-numpy-array-that-are-greater-than-some-value – run-out Feb 12 '19 at 07:55
  • You shouldn't use explicit for loops like that because the operation is vectorized. – gunesevitan Feb 12 '19 at 07:56

2 Answers2

6

This way you can modify matrix with conditions without loops

img[img==255]=1
Martin
  • 3,333
  • 2
  • 18
  • 39
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]] 
Sociopath
  • 13,068
  • 19
  • 47
  • 75