No account yet ?
Tested in Anaconda and Python 3.7
import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg from skimage.exposure import histogram def _validate_image_histogram(image, hist, nbins=None): if image is None and hist is None: raise Exception("Either image or hist must be provided.") if hist is not None: if isinstance(hist, (tuple, list)): counts, bin_centers = hist else: counts = hist bin_centers = np.arange(counts.size) else: counts, bin_centers = histogram( image.ravel(), nbins, source_range='image' ) return counts.astype(float), bin_centers def threshold_yen(image=None, nbins=256, *, hist=None): counts, bin_centers = _validate_image_histogram(image, hist, nbins) if bin_centers.size == 1: return bin_centers[0] pmf = counts.astype(np.float32) / counts.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()] if __name__ == '__main__': imgfile = 'cat.jpg' img = None try: img = cv2.imread(imgfile) img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) except cv2.error: print("Add image to args or in the code.") exit() binary_image = img > threshold_yen(img) plt.imshow(binary_image, cmap='gray') plt.axis('off') plt.show() mpimg.imsave('YenThresholding.jpg', binary_image, cmap='gray')
ThreshImages - GitHub
Welcome, my name is Eric Soupet and I am the administrator of the site elodees.com. elodees.com is a state of the art of Artificial Intelligence and aims to be collaborative, you can now offer content such as articles, events, tutorials, ... so don't hesitate !
Platform images credit : Pixabay - Pixabay License | Pexels - Pexels License