2017-04-23 59 views
0

我在https://fsix.github.io/mnist/Deskewing.html上找到了如何去偏移MNIST數據集的圖像。它似乎工作。我的問題是,在去校正每個像素之前,它的值介於0和1之間。但是,在對圖像進行校正之後,值不再介於0和1之間。它們可以是負數,可以大於1.這怎麼解決?Deskew MNIST圖像

下面是代碼:

def moments(image): 
    c0,c1 = np.mgrid[:image.shape[0],:image.shape[1]] # A trick in numPy to create a mesh grid 
    totalImage = np.sum(image) #sum of pixels 
    m0 = np.sum(c0*image)/totalImage #mu_x 
    m1 = np.sum(c1*image)/totalImage #mu_y 
    m00 = np.sum((c0-m0)**2*image)/totalImage #var(x) 
    m11 = np.sum((c1-m1)**2*image)/totalImage #var(y) 
    m01 = np.sum((c0-m0)*(c1-m1)*image)/totalImage #covariance(x,y) 
    mu_vector = np.array([m0,m1]) # Notice that these are \mu_x, \mu_y respectively 
    covariance_matrix = np.array([[m00,m01],[m01,m11]]) # Do you see a similarity between the covariance matrix 
    return mu_vector, covariance_matrix 

def deskew(image): 
    c,v = moments(image) 
    alpha = v[0,1]/v[0,0] 
    affine = np.array([[1,0],[alpha,1]]) 
    ocenter = np.array(image.shape)/2.0 
    offset = c-np.dot(affine,ocenter) 
    return interpolation.affine_transform(image,affine,offset=offset) 

回答

1

可以將圖像只是歸一化爲範圍偏斜過程後在0和1之間。

img = deskew(img) 
img = (img - img.min())/(img.max() - img.min()) 

請參閱this question

要在deskew功能結合這一點,你可以把它改寫這樣的:

def deskew(image): 
    c,v = moments(image) 
    alpha = v[0,1]/v[0,0] 
    affine = np.array([[1,0],[alpha,1]]) 
    ocenter = np.array(image.shape)/2.0 
    offset = c-np.dot(affine,ocenter) 
    img = interpolation.affine_transform(image,affine,offset=offset) 
    return (img - img.min())/(img.max() - img.min())