PolarBear10
PolarBear10

Reputation: 2305

Replace image pixel color based on channel condition in Python

I have an RGB image, how can I change the pixel color to either white or black based on comparing the red and blue channel values of the same pixel?

if r_pixel > g_pixel:
    # make pixel white
else:
    # Make pixel black

Here is what I have tried:

img = cv2.imread("car.jpg")
b,g,r = cv2.split(img)
new = np.subtract(r , g)

The output is a strictly white and black image (0 or 255).

Upvotes: 1

Views: 1602

Answers (2)

Mark Setchell
Mark Setchell

Reputation: 207375

I would use np.where() to pick 255 or 0 at each pixel depending on the condition:

import cv2
import numpy as np

# Load image
img = cv2.imread('colorwheel.jpg')

# Wherever R>G, make result white, and black elsewhere
res = np.where(img[...,2]>img[...,1], 255, 0).astype(np.uint8)

# ALTERNATIVE SOLUTION FOLLOWS

# Or you could generate a Boolean (True/False) array and multiply by 255 to get the same result
res = ((img[...,2]>img[...,1]) * 255 ).astype(np.uint8)

Input

enter image description here

Result

enter image description here

Upvotes: 3

Gil Pinsky
Gil Pinsky

Reputation: 2493

You can slice the required channels first as shown below, then compare both channels and cast the result from boolean to uint8, then squeeze the singleton channel and multiply by 255:

r = img[:,:,2:]
g = img[:,:,1:2]
new = 255*np.squeeze(r>g,axis=2).astype('uint8')

Upvotes: 1

Related Questions