Beispiel #1
0
def predict(weights_path, image_path):
    model = Net.build(32, 32, 3, weights_path)
    image = load_image(image_path)
    class_ = model.predict(image)
    output_indice = -1

    # get class index having maximum predicted score
    for i in range(36):
        if (i == 0):
            max = class_[0][i]
            output_indice = 0
        else:
            if (class_[0][i] > max):
                max = class_[0][i]
                output_indice = i

    # append 26 characters (A to Z) to list characters
    characters = []
    for i in range(65, 65 + 26):
        characters.append(chr(i))
    if (output_indice > 9):
        final_result = characters[(output_indice - 9) - 1]
        print("Predicted: ", final_result)

    else:
        print("No result can be fulfilled")
Beispiel #2
0
def predict_frames():
    """
    Loads pretrained CNN to predict on all frame images
    predictions: nparray with class prediction on all images
    filenames: nparray of all frame filenames
    """
    frames, filenames = get_data()
    model = Net.build(width=imageSize, height=imageSize, depth=3)
    model.compile(loss='categorical_crossentropy',
                  optimizer='adam',
                  metrics=['accuracy'])
    model.load_weights('trained_weights_2.h5')
    predicted_classes = model.predict(frames)
    predictions = np.argmax(predicted_classes, axis=1)

    #for i in range(len(predictions)):
    #print('Predicted class: {} for image: {} with confidence: {}'.format(map_characters[predictions[i]], filenames[i], np.amax(predicted_classes[i])*100))
    return predictions, filenames
Beispiel #3
0
def predict(weights_path, image_path):
    '''
    Function: loads a trained model and predicts the class of given image
    Input: weights_path (.h5 file, prefer adding absolute path)
           image_path (image to predict, prefer adding absolute path)
    Returns: none
    '''
    model = Net.build(32, 32, 3, weights_path)

    image = load_image(image_path, show=True)  # load image, rescale to 0 to 1
    class_ = model.predict(
        image)  # predict the output, returns 36 length array
    print("Detected: ", class_[0])  # print what is predicted
    output_indice = -1  # set it initially to -1

    # get class index having maximum predicted score
    for i in range(36):
        if (i == 0):
            max = class_[0][i]
            output_indice = 0
        else:
            if (class_[0][i] > max):
                max = class_[0][i]
                output_indice = i

    # append 26 characters (A to Z) to list characters
    characters = []
    for i in range(65, 65 + 26):
        characters.append(chr(i))
    # if output indice > 9 (means characters)
    if (output_indice > 9):
        final_result = characters[(output_indice - 9) - 1]
        print("Predicted: ", final_result)
        print("value: ", max)  # print predicted score
    # else it's a digit, print directly
    else:
        print("Predicted: ", output_indice)
        print("value: ", max)  # print it's predicted score
def predict(weights_path, image_path):
    '''
    Function: loads a trained model and predicts the class of given image
    Input: weights_path (.h5 file, prefer adding absolute path)
           image_path (image to predict, prefer adding absolute path)
    Returns: none
    '''
    model = Net.build(32, 32, 3, weights_path)
    
    image = load_image(image_path, show=True) # load image, rescale to 0 to 1
    class_ = model.predict(image) # predict the output, returns 36 length array
    print("Detected: ", class_[0]) # print what is predicted
    output_indice = -1 # set it initially to -1
    
    # get class index having maximum predicted score
    for i in range(36):
        if(i == 0):
            max = class_[0][i]
            output_indice = 0
        else:
            if(class_[0][i] > max):
                max = class_[0][i]
                output_indice = i
    
    # append 26 characters (A to Z) to list characters
    characters = []
    for i in range(65, 65+26):
        characters.append(chr(i))
    # if output indice > 9 (means characters)
    if(output_indice > 9):
        final_result = characters[(output_indice - 9) - 1]
        print("Predicted: ", final_result)
        print("value: ", max) # print predicted score
    # else it's a digit, print directly
    else:
        print("Predicted: ", output_indice)
        print("value: ", max) # print it's predicted score
Beispiel #5
0
# Dimensions of our images
img_width, img_height = 64, 64

# 3 channel image
no_of_channels = 3

# Training variables
epochs = 6
batch_size = 64

# Train data Directory
train_data_dir = 'data/train/'

# Load model from Net
model = Net.build(width=img_width, height=img_height, depth=no_of_channels)
print('--------building done--------')
model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
print('--------compiling done--------')


def preprocess_image(image):
    '''Function that will be implied on each input. The function
    will run after the image is resized and augmented.
    The function should take one argument: one image (Numpy tensor
    with rank 3), and should output a Numpy tensor with the same
    shape.'''
    sobely = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=5)
    return sobely
Beispiel #6
0
# Dimensions of our images
img_width, img_height = 32, 32

# 3 channel image
no_of_channels = 3

# train data Directory
train_data_dir = 'train/' 
# test data Directory
validation_data_dir = 'test/' 

epochs = 80
batch_size = 32

#initialize model
model = Net.build(width = img_width, height = img_height, depth = no_of_channels)
print('building done')
# Compile model
rms = optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=None, decay=0.0)
print('optimizing done')

model.compile(loss='categorical_crossentropy',
              optimizer=rms,
              metrics=['accuracy'])

print('compiling')

# this is the augmentation configuration used for training
# horizontal_flip = False, as we need to retain Characters
train_datagen = ImageDataGenerator(
    featurewise_center=True,
from keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
from keras import optimizers
from net import Net  # creating modelNameName

wdthIm, hghtIm = 32, 32  # set image size
channelNo = 3  # set image number
data_dir_train = 'test_together/'
data_dirc_validation = 'test_together/'
epochNo = 120
batchSize = 52

modelName = Net.build(width=wdthIm, height=hghtIm,
                      depth=channelNo)  #modelName name
print('building done!!')

Rms = optimizers.Rmsprop(lr=0.001, rho=0.9, epsilon=None,
                         decay=0.0)  #compiling model
print('optimizing done!!')
modelName.compile(loss='categorical_crossentropy',
                  optimizer=Rms,
                  metrics=['accuracy'])

print('compiling.....')

train_datagenerator = ImageDataGenerator(
    featurewise_centering=True,
    featurewise_std_normaliztn=True,
    shear_ranges=0.1,
    zoom_ranges=0.1,
    rotation_ranges=5,
                                                label,
                                                test_size=0.25,
                                                random_state=30)

classes = len(labels)
trainY = to_categorical(trainY, num_classes=classes)
testY = to_categorical(testY, num_classes=classes)

aug = ImageDataGenerator(rotation_range=30,
                         width_shift_range=0.1,
                         height_shift_range=0.1,
                         shear_range=0.2,
                         zoom_range=0.2,
                         horizontal_flip=True,
                         fill_mode="nearest")

print("[INFO] Compiling model...")
model = Net.build(width=28, height=28, depth=3, classes=classes)
opt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)
model.compile(loss="binary_crossentropy", optimizer=opt, metrics=["accuracy"])

print("[INFO] Training model...")
H = model.fit_generator(aug.flow(trainX, trainY, batch_size=BATCH_SIZE),
                        validation_data=(testX, testY),
                        steps_per_epoch=len(trainX) // BATCH_SIZE,
                        epochs=EPOCHS,
                        verbose=1)

model.save(args["model"])
print("[INFO] Model Saved...")