ITK has around a dozen of filters that will automatically select a threshold based on the image’s intensity histogram:
https://itk.org/Doxygen/html/group__ITKThresholding.html