简体   繁体   English

如何根据条件更改像素值

[英]How to change pixel value based on a condition

The image is 1920 by 1080. How can I change the value of a pixel when a channel value is higher than the other?图像为 1920 x 1080。当通道值高于另一个时,如何更改像素的值?

Here is what I did.这就是我所做的。

y_range = 1080
for y in range(y_range):
    x = 0
    while x < 1920:

        green_value = img[y, x][1]
        red_value = img[y, x][2]
        diff = int(red_value) - int(green_value)

        if diff < 5:
            img[y, x] = [0, 0, 0]

        x = x + 1

Is there a more efficient way than iterating on each pixel?有没有比迭代每个像素更有效的方法?

Don't use any loop for this, use ndarray capability and logical indexing.不要为此使用任何循环,使用ndarray功能和逻辑索引。

What you want to achieve is something like:您想要实现的目标是:

d = img[:,:,2] - img[:,:,1]    # Difference of color channels
q = d < 5                      # Threshold criterion
img[q] = [0,0,0]               # Overwrite data based on threshold

Provided your image is in BGR format and you want signed difference between Red and Green channels.如果您的图像是 BGR 格式,并且您想要红色和绿色通道之间的签名差异。 If you meant distance change for:如果您的意思是距离变化:

d = np.abs(img[:,:,2] - img[:,:,1])    # Distance between color channels

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

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