def threshold_yen(image, nbins=256):
 (hist, bin_centers) = histogram(image.ravel(), nbins)
 if (bin_centers.size == 1):
  return bin_centers[0]
 pmf = (hist.astype(np.float32) / hist.sum())
 P1 = np.cumsum(pmf)
 P1_sq = np.cumsum((pmf ** 2))
 P2_sq = np.cumsum((pmf[::(-1)] ** 2))[::(-1)]
 crit = np.log((((P1_sq[:(-1)] * P2_sq[1:]) ** (-1)) * ((P1[:(-1)] * (1.0 - P1[:(-1)])) ** 2)))
 return bin_centers[crit.argmax()]

def threshold_yen ( image , nbins = 256 ) : ( hist , bin_centers ) = histogram ( image . ravel ( ) , nbins ) if ( bin_centers . size == 1 ) : return bin_centers [ 0 ] pmf = ( hist . astype ( np . float32 ) / hist . sum ( ) ) P1 = np . cumsum ( pmf ) P1_sq = np . cumsum ( ( pmf ** 2 ) ) P2_sq = np . cumsum ( ( pmf [ : : ( - 1 ) ] ** 2 ) ) [ : : ( - 1 ) ] crit = np . log ( ( ( ( P1_sq [ : ( - 1 ) ] * P2_sq [ 1 : ] ) ** ( - 1 ) ) * ( ( P1 [ : ( - 1 ) ] * ( 1.0 - P1 [ : ( - 1 ) ] ) ) ** 2 ) ) ) return bin_centers [ crit . argmax ( ) ]
return threshold value based on yens method .