Search code examples
pythonopencvimage-processingimage-thresholding

What does opencv threshold THRESH_BINARY do on colored images?


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


Solution

  • 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).