What does opencv threshold THRESH_BINARY do on colored images?

2.7k views Asked by At

The documentation on THRESH_BINARY says:

dst(x,y) = maxval if src(x,y) > thresh else 0

Which to me does not imply that this won't work on colored images. I expected a two color output even when applied to a colored image, but the output is multicolor. Why? How can that be when the possible values the pixel x,y is assinged are maxval and 0 only?

Example:

from sys import argv
import cv2
import numpy as np

img = cv2.imread(argv[1])

ret, threshold = cv2.threshold(img, 120, 255, cv2.THRESH_BINARY)

cv2.imshow('threshold', threshold)
cv2.imshow('ori', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

enter image description here

2

There are 2 answers

0
Andrey  Smorodov On BEST ANSWER

Thresholding applied to each color channel, separately. If less tahn threshold then color channel set to 0, if not then to maxval. Channels processed independently, that's why result is color image with several colors. The colors you can get are: (0,0,0), (255,0,0), (0,255,0), (255,255,0), (0,0,255),(255,0,255), (0,255,255) and (255,255,255).

0
zindarod On

Suppose you've pixel from 3 channel RGB image with values rgb(66, 134, 244). Now suppose you give thresh value 135. What do you think will happen?

r = 66
g = 134
b = 244

if(r > thresh) r = 255 else r = 0; // we have r = 0
if(g > thresh) g = 255 else g = 0; // we have g = 0
if(b > thresh) b = 255 else b = 0; // we have b = 255

New pixel value is rgb(0, 0, 255). Since your image is an RGB color image, now the pixel color is BLUE instead of WHITE.