Can't use model.predict in digit recognition deep learning project

25 Views Asked by At

This is my code:

import keras
#COLOUR
import matplotlib.pyplot as plt
import numpy as np
from skimage import io
import cv2
from skimage import util
import os
import tensorflow as tf
from keras.utils import normalize
IMG_SIZE = 28
model = keras.models.load_model("bestmodel.h5",compile=True)
for filename in os.listdir('colour'):
    if filename.endswith(".png") or filename.endswith(".jpg") or filename.endswith(".jpeg"): 
        pass
    else:   
        continue
    name="colour/"
    name+=filename
    i=name
    img = cv2.imread(i)
    # plt.imshow(img) #ORIGINAL IMAGE
    img1 = cv2.imread(i,cv2.IMREAD_GRAYSCALE)
    average = img1.mean(axis=0).mean(axis=0)
#     print(average)
    # plt.imshow(img1) GRAYSCALED READ IMAGE
    thresh = average
    img_binary = cv2.threshold(img1, thresh, 255, cv2.THRESH_BINARY)[1]

    cv2.imwrite('test_colour/test_c.png',img_binary) 

    img2=cv2.imread('test_colour/test_c.png')
    # plt.imshow(img2) #BLACK AND WHITE
    # print(img2)
    unique_elements, counts_elements = np.unique(img2, return_counts=True)
#     print("Frequency of unique values of the said array:")
#     print(np.asarray((unique_elements, counts_elements)))
    d=dict(zip(unique_elements, counts_elements))
#     print(d)
    # print(d[0],d[255])

    if(0 in d and 255 in d):
        if(d[0]<d[255]):
            img2 = util.invert(img2)
    else:
        continue
    cv2.imwrite('test_colour/test_c.png',img2) 
   
    gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
    resized2 = cv2.resize(gray2, (28,28),interpolation = cv2.INTER_AREA)  
    newimg2 = tf.keras.utils.normalize(resized2, axis=1)
    newimg2 = np.array(newimg2).reshape(-1, IMG_SIZE, IMG_SIZE, 1)
    predictions2 = model.predict(newimg2)
#     plt.subplot(1,15,images.index(i)+1)
    t="test_colour/"
    t+=filename
    cv2.imwrite(t,img2) 
    plt.imshow(img2)
    print("PREDICTION: ",np.argmax(predictions2),"IMAGE NAME: ",i)
    
plt.imshow(resized2) #FINAL IMAGE

this is all the code and bestmodel.h5 is the model i trained and color is a folder in which i have images that need to be predicted

the error is

NameError                                 Traceback (most recent call last)
d:\PROJECT\good\app.ipynb Cell 1 line 7
     70     plt.imshow(img2)
     71     print("PREDICTION: ",np.argmax(predictions2),"IMAGE NAME: ",i)
---> 73 plt.imshow(resized2) #FINAL IMAGE

NameError: name 'resized2' is not defined

here i can't make my model to predict the number by using model.predict Please help me

This is what iam expecting. As you can see in the image it predict the number and also provides path of the image. I want to check my prediction instantaneously right in command prompt. There are nearly 20 images in my color folder which will be predicted by the model/

0

There are 0 best solutions below