1 | initial version |
The global optimal threshold can be achieved using Otsu's method, i.e.
int best_threshold = cv::threshold(img, out, 1, 255, cv::THRESH_BINARY + cv::THRESH_OTSU);
Your image thresholded using Otsu:
However, what you probably need is a local thresholding method, e.g. the binarization method of Sauvola et. al or Bradley et al. (just search for binarization with the author name and you will find enough material). However note that also then it may happen that you need to tune parameters of these methods.