Python Opencv - Cannot change pixel value of a picture

I think this should work. :) (I used numpy just to get width and height values - you dont need this)

import cv2

img=cv2.imread("cvlogo.png")
img=cv2.resize(img, (300,300))
height, width, channels = img.shape

white = [255,255,255]
black = [0,0,0]

for x in range(0,width):
    for y in range(0,height):
        channels_xy = img[y,x]
        if all(channels_xy == white):    
            img[y,x] = black

        elif all(channels_xy == black):
            img[y,x] = white

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

I am not very experienced, but I would do it using numpy.where(), which is faster than the loops.

import cv2
import numpy as np
import matplotlib.pyplot as plt

# Read the image
original_image=cv2.imread("cvlogo.png")
# Not necessary. Make a copy to plot later
img=np.copy(original_image)

#Isolate the areas where the color is black(every channel=0) and white (every channel=255)
black=np.where((img[:,:,0]==0) & (img[:,:,1]==0) & (img[:,:,2]==0))
white=np.where((img[:,:,0]==255) & (img[:,:,1]==255) & (img[:,:,2]==255))

#Turn black pixels to white and vice versa
img[black]=(255,255,255)
img[white]=(0,0,0)

# Plot the images
fig=plt.figure()
ax1 = fig.add_subplot(1,2,1)
ax1.imshow(original_image)
ax1.set_title('Original Image')
ax2 = fig.add_subplot(1,2,2)
ax2.imshow(img)
ax2.set_title('Modified Image')
plt.show()

enter image description here


This is also a method of solving this problem. CREDITS:ajlaj25

    import cv2


    img=cv2.imread("cvlogo.png")
    img=cv2.resize(img, (300,300))
    height, width, channels = img.shape

    print(height,width,channels)

    for x in range(0,width):
        for y in range(0,height):
            if img[x,y,0] == 255 and img[x,y,1] == 255 and img[x,y,2] == 255:            
                img[x,y,0] = 0
                img[x,y,1] = 0
                img[x,y,2] = 0

            elif img[x,y,0] == 0 and img[x,y,1] == 0 and img[x,y,2] == 0:
                img[x,y,0] = 255
                img[x,y,1] = 255
                img[x,y,2] = 255

img[x,y] denotes the channel values - all three: [ch1,ch2,ch3] - at the x,y coordinates. img[x,y,0] is the ch1 channel's value at x,y coordinates. **

x and y denotes pixels location not RGB values of pixel .So, img[x,y,0] is the ch1 channel's value at x,y coordinates

**

    cv2.imshow('Coverted Image',img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()