JGuizard
7/31/2019 - 11:53 AM

Image Scaling and Falttening

from PIL import Image
import numpy as np

def scale_and_flatten(img_arr, size):

    new_image = np.zeros(size[0]*size[1])

    h_img, w_img = img_arr.shape

    img_arr = img_arr.reshape(h_img*w_img)

    h_new, w_new = size
    h_scale = int(h_img/h_new)
    w_scale = int(w_img/w_new)

    offset = int((w_img-h_img)/2)

    for h_index in range(h_new):
        for w_index in range(w_new):
            new_image[h_index*w_new+w_index]=img_arr[h_index*w_img*h_scale+w_index*w_scale+offset]

    return new_image.astype(np.uint8)



if(__name__ = "__main__"):

    img = Image.open("potato.jpg")
    data = np.asarray(img)
    data = data[:,:,1].copy()
    scaled_data = img_scale(data, (150,150))
    scaled_data = scaled_data.reshape(150,150)
    img = Image.fromarray(scaled_data, "L")
    img.save("potato_scaled.png")