Search code examples
pythonmachine-learningflaskkerasglcm

I always got the same result, How to remove variable session in flask


I'm building an application for GLCM and RGB extraction and also make prediction. But somehow if I use different data I always get results on the previous data or first data. But not for RGB data, RGB data always manages to get results according to the uploaded data. Unless I stop the server and restart it then it should work.

here is my code in app.py

from flask import Flask, render_template, request
from keras.models import load_model
from io import BytesIO
import keras.utils as image
import numpy as np
from PIL import Image
import math
import pandas as pd
import csv
import requests
from io import BytesIO
import numpy as np
import keras.utils as image
import cv2 as cv
from data import Data
from glcm import Glcm
from sklearn.preprocessing import StandardScaler
import os

app = Flask(__name__)

model = load_model('klasifikasi_ayam_potong_berformalin3.h5', compile=False)

matriks = [
    [0,1],
    [1,0],
]

matriksIterasi = [
    [0,0,0,0],
    [0,0,0,0],
    [0,0,0,0],
    [0,0,0,0],
]

feature = []

def countFeatures(data, glcm):
    asm = glcm.asmMethod(data)
    energy = glcm.energy(asm)
    feature.append(energy)
    idm = glcm.idmMethod(data)
    feature.append(idm)
    cont = glcm.contrasMethod(data)
    feature.append(cont)
    corel = glcm.correlation(data)
    feature.append(corel)

def processImg(imgPat):

    imageObject  = Image.open(imgPat)
    cropped     = imageObject.crop((0,0,250,250))
    citra = np.array(cropped)
    citra = citra.transpose(2,0,1).reshape(3,-1)
    matriksIterasi = [[0 for i in range(256)] for j in range(256)]

    glcm = Glcm()
    data0 = glcm.forOder0(citra, matriksIterasi)
    countFeatures(data0, glcm)
    data45 = glcm.forOder45(citra, matriksIterasi)
    countFeatures(data45, glcm)
    data90 = glcm.forOder90(citra, matriksIterasi)
    countFeatures(data90, glcm)
    data135 = glcm.forOder135(citra, matriksIterasi)
    countFeatures(data135, glcm)

    for i in range(len(data0)-1):
        for j in range(len(data0[i])-1):
            data0[i][j]=(data0[i][j]+data45[i][j]+data90[i][j]+data135[i][j])/4
    
    countFeatures(data0, glcm)

    R = []
    G = []
    B = []

    cvImage = cv.imread(imgPat, cv.COLOR_RGB2BGR)
    rows, cols, _ = cvImage.shape

    color_B = 0
    color_G = 0
    color_R = 0
    color_N = 0 
    for i in range(rows):
        for j in range(cols):
            k = cvImage[i,j]
            if k[0] > k[1] and k[0] > k[2]:
                color_B = color_B + 1
                continue
            if k[1] > k[0] and k[1] > k[2]:
                color_G = color_G + 1
                continue
            if k[2] > k[0] and k[2] > k[1]:
                color_R = color_R + 1
                continue
            color_N = color_N + 1

        pix_total = rows * cols

    G.append(color_G/pix_total)
    B.append(color_B/pix_total)
    R.append(color_R/pix_total)
    print("    ")
    print(imgPat, '\n')
    df = pd.DataFrame({'Red': R, 'Green': G, 'Blue': B, 'energy0':feature[0], 'contras0':feature[1], 'homogenity0':feature[2], 'correlation0':feature[3], 'energy45':feature[4], 'contras45':feature[5], 'homogenity45':feature[6], 'correlation45':feature[7], 'energy90':feature[8], 'contras90':feature[9], 'homogenity90':feature[10], 'correlation90':feature[11], 'energy135':feature[12], 'contras135':feature[13], 'homogenity135':feature[14], 'correlation135':feature[15], 'energy_mean':feature[16], 'contras_mean':feature[17], 'homogenity_mean':feature[18], 'correlation_mean':feature[19]})
    print(df)

    sc = StandardScaler()
    xtesx = sc.fit_transform(df)
    prediction = model.predict(xtesx)
    data_pred = []
    pred = ''
    for i in prediction:
        if i > 0.5:
            data_pred.append(1)
            pred = 'Good'
        else:
             data_pred.append(0)
             pred = 'Bad'

    return pred

@app.route("/", methods=['GET', 'POST'])
def main():
    return render_template("index.html")

@app.route("/about")
def about_page():
    return render_template("about.html")

@app.route("/contact")
def contact_page():
    return render_template("contact.html")

@app.route("/submit", methods = ['POST'])

def get_output():
    if request.method == 'POST':
       
       img = request.files['my_image']
       img_path = "static/" + img.filename  
       img.save(img_path)
       
       pred = processImg(img_path)
       
    return render_template("index.html", prediction = pred, img_path = img_path)

if __name__ =='__main__':
    app.run(debug = True)

you could see the same results after Red, Green, Blue which is on energy0, contras0 and so on..

results could be found here

How do I make it not necessary to restart the server and the GLCM data gets according to the uploaded data?


Solution

  • I have managed to fix this problem, and based on the comments from @Frayal, I found a solution. That is, I only need to reset the feature[] list with the clear() function.