La méthode des centres mobiles

In [177]:
import numpy as np
import scipy.ndimage as nd
import matplotlib.pyplot as plt
In [178]:
%matplotlib inline
In [179]:
tout = nd.imread("BasesImages.jpg")

plt.imshow(tout)
plt.show()
In [180]:
def bruit(f):
    n1, n2 = f.shape
    bruit = np.random.randn(n1,n2) # gaussian
    bruit = bruit - bruit.min()
    bruit = bruit/bruit.max()
    return f.max()*bruit
In [181]:
luminance = 0.2126*tout[:,:,0] + 0.7152*tout[:,:,1] + 0.0722*tout[:,:,2]
luminance = luminance + 0.5*bruit(luminance)

plt.imshow(luminance, cmap=plt.cm.gray)
plt.show()
In [182]:
def get_f(image,j):
    #j = 9 # nombre
    if j < 5: 
        i1 = (j+1)*94 + j*24
        i2 = i1 + 85
        f = image[60:150,i1:i2]
    else:
        i1 = (j-5+1)*94 + (j-5)*24
        i2 = i1 + 85
        f = image[260:350,i1:i2]
    return f*1./f.max()
In [183]:
def centres_mobiles(H):
    n = H.size
    s = np.int(0.1*n)
    s_old = 0

    while np.abs(s-s_old) > 0:
        g1 = np.sum(H[0:s]*np.linspace(0,s,s))/np.sum(H[0:s])
        g2 = np.sum(H[s+1:n]*np.linspace(s+1,n,n-s-1))/np.sum(H[s+1:n])
        s_old = s
        s = np.int((g1+g2)/2)
        print g1, g2, s
        
    return s, np.int(g1), np.int(g2)
In [184]:
f = get_f(luminance,8)
H = nd.histogram(f,0,1,100)
s, g1, g2 = centres_mobiles(H)
fs = np.sign(f - s*1./H.size)

plt.figure(figsize=(10,3))
plt.subplot(1,3,1)
plt.imshow(f, cmap=plt.cm.gray)
plt.title("image brute")
plt.subplot(1,3,2)
plt.plot(H)
plt.title("histogramme")
v = np.linspace(0,0.5*H.max(),2)
plt.plot(v*0+g1,v, ":", color ="black", label="g1")
plt.plot(v*0+g2,v, ":", color ="black", label="g2")
plt.plot(v*0+s,v, color ="black", label="s")
plt.legend()
plt.subplot(1,3,3)
plt.imshow(fs, cmap=plt.cm.gray)
plt.title("image binaire")
plt.show()
8.86666666667 27.9549747881 18
15.146192664 34.9225911186 25
18.4688899552 49.8662839286 34
19.699100104 58.6609887295 39
20.1958407886 61.7371964855 40
20.2679964136 62.2890864109 41
20.3706136869 62.977416804 41
In [ ]: