Subscribe & download the code for the article "Image Thresholding with OpenCV and Python".
(You'll need to confirm your subscription to get the code)