code: def otsu_threshold(img, nbins=256):
      """
      Implementation of otsu thresholding
  
      :param img:
      :param nbins:
      :return:
      """
      hist, bin_edges = np.histogram(img.ravel(), bins=nbins)
      hist = hist.astype(float)
      half_bin_size = (bin_edges[1] - bin_edges[0]) * 0.5
      bin_centers = bin_edges[:-1] + half_bin_size
  
      weight_1 = np.copy(hist)
      mean_1 = np.copy(hist)
      weight_2 = np.copy(hist)
      mean_2 = np.copy(hist)
      for i in range(1, hist.shape[0]):
          weight_1[i] = weight_1[i - 1] + hist[i]
          mean_1[i] = mean_1[i - 1] + hist[i] * bin_centers[i]
  
          weight_2[-i - 1] = weight_2[-i] + hist[-i - 1]
          mean_2[-i - 1] = (
              mean_2[-i] + hist[-i - 1] * bin_centers[-i - 1]
          )
  
      target_max = 0
      threshold = bin_centers[0]
      for i in range(0, hist.shape[0] - 1):
          ratio_1 = mean_1[i] / weight_1[i]
          ratio_2 = mean_2[i + 1] / weight_2[i + 1]
          target = (
              weight_1[i] * weight_2[i + 1] * (ratio_1 - ratio_2) ** 2
          )
          if target > target_max:
              target_max, threshold = target, bin_centers[i]
      return threshold
  
imports: from __future__ import absolute_import
  from __future__ import division
  from __future__ import print_function
  import datetime
  import os
  import re
  from functools import partial
  import numpy
  import tensorflow
  from scipy import ndimage
  from six import string_types
label_desc: Use image node_id 13 for calling a global function with example usage: otsu_threshold(img, nbins) and returns: threshold