Search code examples
pythonnumpyimage-processingpixel-manipulation

Pixel manipulation in Numpy


I want to convert all pixel values 0 instead of the value of 255. Pixel values are kept in Numpy array, namely x and:

x.shape = (100, 1, 256, 256)

How to manipulate arrays with the condition?

I tried the below but the error occured "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"

i=0
for i in x[i]:
    if x[i]==255:
        x[i] = x[i]
    else:
        x[i] ==0

Solution

  • Just use:

    x[x==255] = 0
    

    Test:

    # Repeatable randomness
    np.random.seed(42)
    
    # Synthesise array
    x = np.random.randint(0,256, (100, 1, 256, 256), np.uint8)
    
    # Count number of 255s
    len(np.where(x==255)[0])    # result = 25671
    
    # Make each 255 into 0
    x[x==255] = 0
    
    # Count number of 255s
    len(np.where(x==255)[0])    # result = 0