Logo elodees  elodees

A caring AI for a better world













Only alphabetic characters accented or not as well as the space are accepted

Logo IA




Otsu thresholding





No account yet ?

Sign up to access all content
















OtsuThresholding - GitHub



download

license : MITlicenseMIT  Copyright (c) 2016 dandavis


GitHub





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_otsu(image=None, nbins=256, *, hist=None):
 
    if image is not None:
        first_pixel = image.ravel()[0]
        if np.all(image == first_pixel):
            return first_pixel
 
    counts, bin_centers = _validate_image_histogram(image, hist, nbins)
 
    # class probabilities for all possible thresholds
    weight1 = np.cumsum(counts)
    weight2 = np.cumsum(counts[::-1])[::-1]
 
    # class means for all possible thresholds
    mean1 = np.cumsum(counts * bin_centers) / weight1
    mean2 = (np.cumsum((counts * bin_centers)[::-1]) / weight2[::-1])[::-1]
 
    variance12 = weight1[:-1] * weight2[1:] * (mean1[:-1] - mean2[1:]) ** 2
 
    idx = np.argmax(variance12)
    threshold = bin_centers[idx]
 
    return threshold
 
 
if __name__ == '__main__':
 
    imgfile = 'cat-threshimages.jpg'
    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_otsu(img)
    plt.imshow(binary_image, cmap='gray')
    plt.axis('off')
    plt.show()
 
    mpimg.imsave('CatOtsuThresholding.jpg', binary_image, cmap='gray')
 


ThreshImages - GitHub



Free image provided by pexel.com
Free image provided by pexel.com










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