Python在块大小上应用图像阈值?

时间:2015-03-20 19:25:12

标签: python image-processing threshold

我有一个2D数组,如下所示:

[[118 127 133 ..., 213 211 211]
 [125 128 130 ..., 213 213 213]
 [119 124 130 ..., 214 213 213]
 ...,
 [ 36  54  44 ..., 109 101 101]
 [ 37  52  47 ..., 112 101 101]
 [ 39  50  51 ..., 104  99  99]]

我需要在本地矩阵上应用一个阈值,并且不重叠它们。我需要将这个2D矩阵分解成更小的2D矩阵。然后为较小的2D矩阵计算新的阈值,并将阈值应用于较小的2D矩阵,并对所有较小的矩阵执行相同的操作。我最终必须把它们结合起来。是否有任何python函数可以轻松完成此操作?谢谢。

修改

import sys
from numpy import *

import scipy.misc
from matplotlib import pyplot

def otsu1( hist, total ):

    no_of_bins = len( hist ) # should be 256

    intra_class_variances = []

    for threshold in range( 0, no_of_bins ):
        # first we try to find the weight and variance on the background
        sum_background      = float(sum( hist[0:threshold] ))
        weight_background   = sum_background / total
        mean_background     = 0.0
        variance_background = 0.0

        # print weight_background

        if sum_background > 0.0: # avoid division by zero
            for x in range( 0, threshold ):
                mean_background += x * hist[x]
            mean_background /= sum_background

            for x in range( 0, threshold ):
                variance_background += (x - mean_background) ** 2 * hist[x]
            variance_background /= sum_background   


        # then we do it for the foreground
        sum_foreground      = float(sum( hist[threshold:no_of_bins] ))
        weight_foreground   = sum_foreground / total
        mean_foreground     = 0.0
        variance_foreground = 0.0

        if sum_foreground > 0.0:
            for x in range( threshold, no_of_bins ):
                mean_foreground += x * hist[x]
            mean_foreground /= sum_foreground

            for x in range( threshold, no_of_bins ):
                variance_foreground += (x - mean_foreground) ** 2 * hist[x]
            variance_foreground /= sum_foreground   

        # print variance_foreground, mean_foreground

        # find the variances within these two classes
        intra_class_variances.append( weight_background * variance_background + weight_foreground * variance_foreground )

    print argmin( intra_class_variances ) - 1

    # use the threshold that has the minimum intra class variance
    return argmin( intra_class_variances ) - 1


def main():
    img = scipy.misc.imread( 'Otsu_test_1.jpg' )
    # print img
    # resize to a more managable size
    # img = scipy.misc.imresize( img, (1944 / 4, 2592 / 4) ) 

    # convert to grayscale
    # grayscale = img.dot( [0.299, 0.587, 0.144] ) 
    rows, cols = shape( img )

    # create 256 bins histogram
    hist = histogram( img, 256 )[0]
    # print len(hist)
    # print hist

    # apply the otsu thresholding
    thresh = otsu1( hist, rows * cols )
    # print thresh

    figure  = pyplot.figure( figsize=(14, 6) )
    figure.canvas.set_window_title( 'Otsu thresholding' )

    axes    = figure.add_subplot(121)
    axes.set_title('Original')
    axes.get_xaxis().set_visible( False )
    axes.get_yaxis().set_visible( False )
    axes.imshow( img, cmap='Greys_r' )

    axes    = figure.add_subplot(122)
    axes.set_title('Otsu thresholding')
    axes.get_xaxis().set_visible( False )
    axes.get_yaxis().set_visible( False )
    axes.imshow( img >= thresh, cmap='Greys_r' )

    pyplot.show()

if __name__ == '__main__':
    main()

Otsu's Threshold

x = blockshaped(img, 4, 10)

for i, j in enumerate(x):
    hist = np.histogram(j, bins=256)[0]
    otsu_thres = otsu_threshold(hist, size)
    print otsu_thres
    x[i] = j >= otsu_thres

p = unblockshaped(x, 188, 250)

0 个答案:

没有答案