Jaizo
Jaizo

Reputation: 13

How to change color pixels to white pixels

I got a color image as input and I want to check the color information(like [0, 0, 0] - [255, 255, 255]) on the variance. So if the variance is over a certain point I want to change it to white.

So something like that:

for y in range(img.shape[0]):
    for x in range(img.shape[1]):
        if numpy.var(img[y][x]) > 1000:
            img[y][x] = [255, 255, 255]

But I need good performance. So I tried it with the numpy.where() function, but I couldn't find a solution.

Upvotes: 1

Views: 57

Answers (1)

user8408080
user8408080

Reputation: 2468

You can use numpy's indexing for this:

import numpy as np
import matplotlib.pyplot as plt

img = (np.random.rand(100,100,3)*255).astype(int)

img2 = np.copy(img)
img2[np.var(img, 2)>1000] = np.array([255, 255, 255])

fig, ax = plt.subplots(ncols=2)

ax[0].imshow(img)
ax[1].imshow(img2)

The second parameter of np.var is the axis you want to calculate the variance on; in this case the colors.

Result:

enter image description here

Upvotes: 3

Related Questions