CoolFace
Apppublic

Shingome/Image_Processing

sourceHugging Faceotherupdated 2y agoView on Hugging Face
0likes
predict.py96 linesDownload Raw Back to src
1import numpy as np2from PIL import Image, ImageDraw3 4 5def prepare_image(image: Image):6    # convert image7    width, height = image.size8    width = width // 8 * 89    height = height // 8 * 810    image = image.crop((0, 0, width, height))11    image = image.convert('L')12 13    image_array = []14 15    # image to arrays16    for x in range(width):17        for y in range(height):18            crop = image.crop((x, y, x + 8, y + 8))19            image_array.append(np.reshape(np.asarray(crop) / 255, (1, 64)))20 21    # save image_array22    image_array = np.asarray(image_array)23 24    return image_array25 26 27def draw_image(map, size):28    # size29    step = 1030    width, height = size31    new_width = width // 8 * 8 * step32    new_height = height // 8 * 8 * step33 34    # create canvas35    image = Image.new('RGB', (new_width, new_height), (255, 255, 255))36    draw = ImageDraw.Draw(image)37 38    iter = 039 40    # drawing41    for x in range(0, new_width, step):42        for y in range(0, new_height, step):43            if map[iter] == 1:44                xn, yn = x, y + 845            elif map[iter] == 2:46                xn, yn = x + 8, y47            elif map[iter] == 3:48                xn, yn = x + 8, y - 849            elif map[iter] == 4:50                xn, yn = x + 8, y + 851            else:52                iter += 153                continue54            draw.line(xy=[(x, y), (xn, yn)], fill='black')55            iter += 156 57    image = image.resize((width, height), Image.Resampling.LANCZOS)58 59    return image60 61 62def create_map(image_array):63    # Load synapses64    synapses = np.load('./final_synapses.npz')65    W1 = synapses['arr_0']66    b1 = synapses['arr_1']67    W2 = synapses['arr_2']68    b2 = synapses['arr_3']69    W3 = synapses['arr_4']70    b3 = synapses['arr_5']71 72    def predict(x):73        def relu(t):74            return np.maximum(t, 0)75 76        def softmax(t):77            out = np.exp(t)78            return out / np.sum(out)79 80        # Calculate81        t1 = x @ W1 + b182        h1 = relu(t1)83        t2 = h1 @ W2 + b284        h2 = relu(t2)85        t3 = h2 @ W3 + b386        z = softmax(t3)87        return z88 89    # Form map90    map = []91    for x in image_array:92        z = predict(x)93        y_pred = np.argmax(z)94        map.append(y_pred)95    return map96