<jupyter_start><jupyter_text>Plate Number **Classification**<jupyter_code>import os, cv2, itertools # cv2 -- OpenCV
from google.colab import drive
drive.mount('/gdrive')
%cd /gdrive
#Import packages
import numpy as np
import pandas as pd
import random
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
%matplotlib inline
#Image dirctory

plate_number_dir = '/gdrive/My Drive/hngi6/plate_number/' #'./plate_numbers/'
negative_image_dir = '/gdrive/My Drive/hngi6/negative_image/' #'./negative_images/'
#creating a list of paths for all the images

plate_number_paths = [os.path.join(plate_number_dir, i) for i in os.listdir(plate_number_dir)]
negative_image_paths = [os.path.join(negative_image_dir, i) for i in os.listdir(negative_image_dir)]
# A fuction to read the images in greyscale and resize them

rows = 64
cols = 64
def read_image(file_path):
    img = cv2.imread(file_path, cv2.IMREAD_GRAYSCALE)
    resized_img = cv2.resize(img, (rows, cols), interpolation=cv2.INTER_CUBIC)
    return resized_img

# A function to prepare the image

def prep_data(images):
    m = len(images)
    n_x = rows*cols
    X = np.ndarray((n_x, m), dtype=np.uint8)
    y = np.zeros((1, m))
    print("X.shape is {}".format(X.shape))
    print("y.shape is {}".format(y.shape))
    for i, image_file in enumerate(images):
        image = read_image(image_file)
        X[:, i] = np.squeeze(image.reshape((n_x, 1)))
        
        if 'plate_number' in image_file.lower():
            y[0, i] = 1
            
        elif 'negative_image' in image_file.lower():
            y[0, i] = 0
            
        if i%100 == 0:
            print('Proceed {} of {}'.format(i, m))
            
    return X, y
# Calling prep_data function and using the train_test_split for train and test data

X_image, y_image = prep_data(plate_number_paths + negative_image_paths)

X_img_train, X_img_test, y_img_train, y_img_test = train_test_split(X_image.T, y_image.T, test_size=0.2, random_state=0, shuffle=True)

print('X_img_train.shape is {}'.format(X_img_train.shape))
print('X_img_test.shape is {}'.format(X_img_test.shape))
print('y_img_train.shape is {}'.format(y_img_train.shape))
print('y_img_test.shape is {}'.format(y_img_test.shape))
# function for displaying image give an index: idx

classes = {0: 'Negative_Image', 1: 'Plate_Number'}

def show_images(X, y, idx):
    image = X[idx]
    image = image.reshape((rows, cols))
    plt.figure(figsize=(4,2))
    plt.imshow(image)
    plt.title(classes[y[idx, 0]])
    plt.show()
    
for i in range(4):
    show_images(X_img_train, y_img_train, i)
# Build Models
# Logistic Regression Model

from sklearn.linear_model import LogisticRegressionCV
clf = LogisticRegressionCV()
clf.fit(X_img_train, y_img_train)
# function to visualize predictions and score for linear regression

def show_img_pred(X_test, y_test, idx, model):
    image = X_test[idx].reshape(1, -1)
    image_class = classes[model.predict(image).item()]
    image = image.reshape((rows, cols))
    plt.figure(figsize=(4, 2))
    plt.imshow(image)
    plt.title("Test {} : I think this is {}".format(idx, image_class))
    plt.show()
    print("Model accuracy: {:.2f}%".format(model.score(X_test, y_test)*100))

for i in np.random.randint(0, len(X_img_test), 10):
    show_img_pred(X_img_test, y_img_test, i, clf)
#preprocessing for keras model
from tensorflow import keras

num_classes = 2
def prep_image(X, y):
    out_y = keras.utils.to_categorical(y, num_classes)
    num_images = X.shape[0]
    out_x = X.reshape(num_images, rows, cols, 1)
    out_x = out_x/255
    return out_x, out_y
X_img_keras, y_img_keras = prep_image(X_image.T, y_image.T)

# Keras Model

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Conv2D


model = Sequential()
model.add(Conv2D(10, kernel_size=(3, 3), activation='relu', input_shape=(rows, cols, 1)))
model.add(Conv2D(10, kernel_size=(3, 3), activation='relu'))
model.add(Flatten())
model.add(Dense(50, activation = 'relu'))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss=keras.losses.categorical_crossentropy, optimizer='adam', metrics=['accuracy'])
model.fit(X_img_keras, y_img_keras, batch_size=50, epochs=2, validation_split=0.2)<jupyter_output>Train on 80 samples, validate on 20 samples
Epoch 1/2
80/80 [==============================] - 1s 8ms/sample - loss: 1.3997 - acc: 0.6250 - val_loss: 3.8888 - val_acc: 0.0000e+00
Epoch 2/2
80/80 [==============================] - 0s 4ms/sample - loss: 1.1817 - acc: 0.5250 - val_loss: 0.4274 - val_acc: 1.0000
{'fraction_non_alphanumeric': 0.14310607710738402, 'fraction_numerical': 0.028316270964931386, 'mean_word_length': 4.358226371061844, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '202537', 'license': 'MIT', 'n_tokens_mistral': 1782, 'n_tokens_neox': 1687, 'n_words': 392, 'path': 'Hngi6_ML_Plate_Number_Classification.ipynb', 'repo_name': 'Euchigere/Plate-Number-Classification', 'size': '4591'}