Deskew MNIST图像

时间:2017-04-23 23:35:21

标签: python image-processing mnist skew

我在https://fsix.github.io/mnist/Deskewing.html上发现了如何去除MNIST数据集的图像。它似乎工作。我的问题是,在去偏移之前,每个像素的值都在0和1之间。但是在对图像进行校正后,值不再在0和1之间。它们可以是负数,也可以大于1.如何解决这个问题?

以下是代码:

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)

您可以在偏移过程后将图像标准化为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())