from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

# Load image
x = Image.open("image.jpg","r")

# Convert black and white jpg image to array
y = np.asarray(x.getdata(),dtype=np.float64).reshape(x.size[1],x.size[0])

#Plot image
#plt.imshow(y,cmap=plt.cm.gray_r,interpolation="nearest")
#plt.show()

# Normalize the array within the range 0 and 1 for machine learning purposes
# Float allowed
def normalize(a):
    m = min(a)
    M = max(a)
    i = 0
    while i < len(a):
        a[i] = (a[i]-m)/(M-m)
        i += 1
    return a

def normalizeArray(b):
    for k in range(len(b)):
        b[k] = normalize(b[k])
    return b

# Normalize the array within the range 0 and 1 for machine learning purposes
# Float not allowed, only integers allowed
def normalizeInt(a):
    m = min(a)
    M = max(a)
    i = 0
    while i < len(a):
        temp = (a[i]-m)/(M-m)
        if temp < 0.5:
            a[i] = 0
        else:
            a[i] = 1
        i += 1
    return a

def normalizeArrayInt(b):
    for k in range(len(b)):
        b[k] = normalizeInt(b[k])
    return b

A = normalizeArray(y)
plt.imshow(A,cmap=plt.cm.gray_r,interpolation="nearest")
plt.show()

B = normalizeArrayInt(y)
plt.imshow(B,cmap=plt.cm.gray_r,interpolation="nearest")
plt.show()