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?
Advertisement
Answer
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