Пример #1
0
def binarization(image_name, plot=False):
    # remove the noise
    img = cv.GaussianBlur(cv.imread(image_name, 0), (5, 5), 0)

    # compute histogram
    values = img.flatten()
    hist, bins = np.histogram(values, range(257))

    # normalize to get probabilities of each intensity level
    norm_hist = hist / np.sum(hist)

    # p1, p2 - probabilities of the two classes separated by a threshold t
    # m1, m2 - means of these two classes
    # v - inter-class variance
    thresh = -1
    max_v = -1
    for t in range(256):
        p1 = np.sum(norm_hist[:t])
        p2 = np.sum(norm_hist[t:])
        m1 = np.sum([i
                     for i in range(t)] * hist[:t]) / p1 if p1 != 0 else np.nan
        m2 = np.sum([i for i in range(t, 256)] *
                    hist[t:]) / p2 if p2 != 0 else np.nan

        v = p1 * p2 * (m1 - m2)**2
        if v > max_v:
            thresh = t
            max_v = v

    if plot:
        plot_comparison(img, thresh, "Own Otsu's thresholding", otsu=True)

    res = np.where(img > thresh, 255, 0)

    return thresh, res
Пример #2
0
def otsu_thresholding_filtered(image_name, plot=False):
    # Additionally image is filtered with a 5x5 gaussian kernel to remove the noise
    img = cv.imread(image_name, 0)
    blur = cv.GaussianBlur(img, (5, 5), 0)
    image, thresh = cv.threshold(blur, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
    if plot:
        plot_comparison(img, thresh, "Otsu's thresholding filtered")
    return thresh
Пример #3
0
def otsu_thresholding(image_name, plot=False):
    # Automatically calculates a threshold value from image histogram
    # (for bimodal images, otherwise binarization is not accurate)

    img = cv.imread(image_name, 0)
    image, thresh = cv.threshold(img, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
    if plot:
        plot_comparison(img, thresh, "Otsu's thresholding")
    return thresh
Пример #4
0
def adaptive_gaussian_thresholding(image_name, block_size, plot=False):
    #  The threshold value is a gaussian-weighted sum of the neighbourhood values minus the constant C

    img = cv.imread(image_name, 0)
    # blockSize determines the size of the neighbourhood area

    thresh = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, blockSize=block_size, C=5)
    if plot:
        plot_comparison(img, thresh, "Adaptive gaussian thresholding")
    return thresh
Пример #5
0
def global_thresholding(image_name, plot=False):
    img = cv.imread(image_name, 0)
    image, thresh = cv.threshold(img, 127, 255, cv.THRESH_BINARY)
    if plot:
        plot_comparison(img, thresh, "Global thresholding")
    return thresh