Search code examples
pythonopencvcolorsrgb

How to change all the black pixels to white (OpenCV)?


I am new to OpenCV and I do not understand how to traverse and change all the pixels of black with colour code exact RGB(0,0,0) to white colour RGB(255,255,255). Is there any function or way to check all the pixel and if RGB(0,0,0) the make it to RGB(255,255,255).


Solution

  • Assuming that your image is represented as a numpy array of shape (height, width, channels) (what cv2.imread returns), you can do:

    height, width, _ = img.shape
    
    for i in range(height):
        for j in range(width):
            # img[i, j] is the RGB pixel at position (i, j)
            # check if it's [0, 0, 0] and replace with [255, 255, 255] if so
            if img[i, j].sum() == 0:
                img[i, j] = [255, 255, 255]
    

    A faster, mask-based approach looks like this:

    # get (i, j) positions of all RGB pixels that are black (i.e. [0, 0, 0])
    black_pixels = np.where(
        (img[:, :, 0] == 0) & 
        (img[:, :, 1] == 0) & 
        (img[:, :, 2] == 0)
    )
    
    # set those pixels to white
    img[black_pixels] = [255, 255, 255]