code: def otsu (img, bins=64):
      r
      # cast bins parameter to int
      bins = int(bins)
      
      # cast img parameter to scipy arrax
      img = numpy.asarray(img)
      
      # check supplied parameters
      if bins <= 1:
          raise AttributeError('At least a number two bins have to be provided.')
      
      # determine initial threshold and threshold step-length
      steplength = (img.max() - img.min()) / float(bins)
      initial_threshold = img.min() + steplength
      
      # initialize best value variables
      best_bcv = 0
      best_threshold = initial_threshold
      
      # iterate over the thresholds and find highest between class variance
      for threshold in numpy.arange(initial_threshold, img.max(), steplength):
          mask_fg = (img >= threshold)
          mask_bg = (img < threshold)
          
          wfg = numpy.count_nonzero(mask_fg)
          wbg = numpy.count_nonzero(mask_bg)
          
          if 0 == wfg or 0 == wbg: continue
          
          mfg = img[mask_fg].mean()
          mbg = img[mask_bg].mean()
          
          bcv = wfg * wbg * math.pow(mbg - mfg, 2)
          
          if bcv > best_bcv:
              best_bcv = bcv
              best_threshold = threshold
          
      return best_threshold
docs: r"""
      Otsu's method to find the optimal threshold separating an image into fore- and background.
      
      This rather expensive method iterates over a number of thresholds to separate the
      images histogram into two parts with a minimal intra-class variance.
      
      An increase in the number of bins increases the algorithms specificity at the cost of
      slowing it down.
      
      Parameters
      ----------
      img : array_like
          The image for which to determine the threshold.
      bins : integer
          The number of histogram bins.
          
      Returns
      -------
      otsu : float
          The otsu threshold to separate the input image into fore- and background.