简体   繁体   English

在 Python 中根据条件替换图像像素颜色

[英]Replace image pixel color on condition in Python

I have an RGBA image where I have to find if any pixel has red value < 150 and to replace such pixels to black.我有一个 RGBA 图像,我必须在其中查找是否有任何像素的红色值 < 150 并将这些像素替换为黑色。 I am using following code for this:我为此使用以下代码:

import numpy as np
imgarr = np.array(img)
for x in range(imgarr.shape[0]):
    for y in range(imgarr.shape[1]):
        if imgarr[x, y][0] < 150:    # red value < 150
            imgarr[x, y] = (0,0,0,255)

However, this is a slow loop and I am sure it can be optimized using some function such as numpy.where , but I am not able to fit it in this code.但是,这是一个缓慢的循环,我确信可以使用诸如numpy.where 之类的函数对其进行优化,但我无法将其放入此代码中。 How can this be solved?如何解决这个问题?

For one channel image, we can do as follow对于一个通道图像,我们可以这样做

out_val = 0
gray = cv2.imread("colour.png",0)

gray[gray<value] = out_val

Use np.where with the mask of comparison against the threshold -使用np.where与阈值进行比较的掩码 -

img = np.asarray(img)
imgarr = np.where(img[...,[0]]<150,(0,0,0,255),img)

We are using img[...,[0]] to keep the number of dims as needed for broadcasted assignment with np.where .我们正在使用img[...,[0]]来根据需要使用np.where保持广播分配的昏暗数量。 So, another way would be to use img[...,0,None]<150 to get the mask that keeps dims.所以,另一种方法是使用img[...,0,None]<150来获得保持暗淡的掩码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM