简体   繁体   中英

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?

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.

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. If you meant distance change for:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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