!pip install imutils

import numpy as np
import pandas as pd
from keras.preprocessing.image import ImageDataGenerator
import os
import random
import cv2
import imutils
import random
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import LabelBinarizer
from keras.utils import np_utils
from keras.models import Sequential
from keras import optimizers
from sklearn.preprocessing import LabelBinarizer
from keras import backend as K
from keras.layers import Dense, Activation, Flatten, Dense,MaxPooling2D, Dropout
from keras.layers import Conv2D, MaxPooling2D, BatchNormalization

# Install required package
!pip install imutils

# Import necessary libraries

import numpy as np
import pandas as pd
from keras.preprocessing.image import ImageDataGenerator
import os
import random
import cv2
import imutils
import random
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import LabelBinarizer
from keras.utils import np_utils
from keras.models import Sequential
from keras import optimizers
from sklearn.preprocessing import LabelBinarizer
from keras import backend as K
from keras.layers import Dense, Activation, Flatten, Dense,MaxPooling2D, Dropout
from keras.layers import Conv2D, MaxPooling2D, BatchNormalization

# Set the directory path for training data
dir = '../input/handwritten-characters/Train/'

# Create an empty list to store training data
train_data = []

# Set the image size
img_size = 32

# Define non-character symbols
non_chars = ['#', '$', '&', '@']

# Iterate over each directory in the train directory
for i in os.listdir(dir):
    # Skip non-character symbols
    if i in non_chars:
        continue
    count = 0
    sub_directory = os.path.join(dir, i)
    # Iterate over each image in the sub-directory
    for j in os.listdir(sub_directory):
        count += 1
        # Limit the number of images to 4000 per character
        if count > 4000:
            break
        img = cv2.imread(os.path.join(sub_directory, j), 0)
        img = cv2.resize(img, (img_size, img_size))
        train_data.append([img, i])

# Print the length of the training data
print(len(train_data))

# Set the directory path for validation data
val_dir = '../input/handwritten-characters/Validation/'

# Create an empty list to store validation data
val_data = []

# Set the image size
img_size = 32

# Iterate over each directory in the validation directory
for i in os.listdir(val_dir):
    # Skip non-character symbols
    if i in non_chars:
        continue
    count = 0
    sub_directory = os.path.join(val_dir, i)
    # Iterate over each image in the sub-directory
    for j in os.listdir(sub_directory):
        count += 1
        # Limit the number of images to 1000 per character
        if count > 1000:
            break
        img = cv2.imread(os.path.join(sub_directory, j), 0)
        img = cv2.resize(img, (img_size, img_size))
        val_data.append([img, i])

# Print the length of the validation data
print(len(val_data))

# Shuffle the training data
random.shuffle(train_data)

# Shuffle the validation data
random.shuffle(val_data)

# Create empty lists to store training and validation features and labels
train_X = []
train_Y = []
val_X = []
val_Y = []

# Iterate over each feature and label in the training data
for features, label in train_data:
    train_X.append(features)
    train_Y.append(label)

# Iterate over each feature and label in the validation data
for features, label in val_data:
    val_X.append(features)
    val_Y.append(label)

# Create a label binarizer object
LB = LabelBinarizer()

# Transform the training labels using label binarizer
train_Y = LB.fit_transform(train_Y)

# Transform the validation labels using label binarizer
val_Y = LB.fit_transform(val_Y)

# Normalize the training features
train_X = np.array(train_X) / 255.0

# Reshape the training features to match the input shape of the model
train_X = train_X.reshape(-1, 32, 32, 1)

# Convert the training labels to numpy array
train_Y = np.array(train_Y)

# Normalize the validation features
val_X = np.array(val_X) / 255.0

# Reshape the validation features to match the input shape of the model
val_X = val_X.reshape(-1, 32, 32, 1)

# Convert the validation labels to numpy array
val_Y = np.array(val_Y)

# Print the shapes of training and validation data
print(train_X.shape, val_X.shape)
print(train_Y.shape, val_Y.shape)

# Create a sequential model
model = Sequential()

# Add convolutional layers to the model
model.add(Conv2D(32, (3, 3), padding='same', activation='relu', input_shape=(32, 32, 1)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

# Flatten the output from convolutional layers
model.add(Flatten())

# Add fully connected layers to the model
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(35, activation='softmax'))

# Print the summary of the model
model.summary()

# Compile the model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

# Train the model on the training data
history = model.fit(train_X, train_Y, epochs=50, batch_size=32, validation_data=(val_X, val_Y), verbose=1)

# Plot the training and validation accuracy
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Training Accuracy vs Validation Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Validation'], loc='upper left')
plt.show()

# Plot the training and validation loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Training Loss vs Validation Loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Validation'], loc='upper left')
plt.show()

# Function to sort contours
def sort_contours(cnts, method='left-to-right'):
    reverse = False
    i = 0
    if method == 'right-to-left' or method == 'bottom-to-top':
        reverse = True
    if method == 'top-to-bottom' or method == 'bottom-to-top':
        i = 1
    boundingBoxes = [cv2.boundingRect(c) for c in cnts]
    (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
    key=lambda b: b[1][i], reverse=reverse))
    # return the list of sorted contours and bounding boxes
    return (cnts, boundingBoxes)

# Function to extract letters from an image
def get_letters(img):
    letters = []
    image = cv2.imread(img)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    ret, thresh1 = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
    dilated = cv2.dilate(thresh1, None, iterations=2)

    cnts = cv2.findContours(dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = imutils.grab_contours(cnts)
    cnts = sort_contours(cnts, method='left-to-right')[0]
    # loop over the contours
    for c in cnts:
        if cv2.contourArea(c) > 10:
            (x, y, w, h) = cv2.boundingRect(c)
            cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
        roi = gray[y:y + h, x:x + w]
        thresh = cv2.threshold(roi, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
        thresh = cv2.resize(thresh, (32, 32), interpolation=cv2.INTER_CUBIC)
        thresh = thresh.astype('float32') / 255.0
        thresh = np.expand_dims(thresh, axis=-1)
        thresh = thresh.reshape(1, 32, 32, 1)
        ypred = model.predict(thresh)
        ypred = LB.inverse_transform(ypred)
        [x] = ypred
        letters.append(x)
    return letters, image

# Function to combine letters into a word
def get_word(letter):
    word = ''.join(letter)
    return word

# Example usage of the functions
letter, image = get_letters('../input/handwriting-recognition/train_v2/train/TRAIN_00003.jpg')
word = get_word(letter)
print(word)
plt.imshow(image)

letter, image = get_letters('../input/handwriting-recognition/train_v2/train/TRAIN_00023.jpg')
word = get_word(letter)
print(word)
plt.imshow(image)

letter, image = get_letters('../input/handwriting-recognition/train_v2/train/TRAIN_00030.jpg')
word = get_word(letter)
print(word)
plt.imshow(image)

letter, image = get_letters('../input/handwriting-recognition/validation_v2/validation/VALIDATION_0005.jpg')
word = get_word(letter)
print(word)
plt.imshow(image)

letter, image = get_letters('../input/handwriting-recognition/test_v2/test/TEST_0007.jpg')
word = get_word(letter)
print(word)
plt.imshow(image)
Handwritten Character Recognition using CNN and imutils

原文地址: https://www.cveoy.top/t/topic/pcHR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录