Here's an updated version of the code that includes the preprocessing, segmentation, and prediction steps for a given image. I assume you have a grayscale image of handwritten text that you want to process, segment, and generate predictions for.
First, let's add the required libraries for image processing and segmentation:
import cv2
from typing import List, Tuple
Next, add a function to preprocess the image. This will resize, threshold, and pad the image, so it's ready to be fed into the model. For any input image, change this method according to the expected input shape of your models.
def preprocess_image(img: np.ndarray, img_size: Tuple[int, int] = (32, 32)) -> np.ndarray:
# Resize image if necessary
h, w = img.shape
if img_size != (h, w):
img = cv2.resize(img, (img_size[1], img_size[0]))
# Thresholding the image to create a binary image
_, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# Padding the image with a constant border
pad_thresh = round(max(img_size) * 0.1)
img = cv2.copyMakeBorder(img, pad_thresh, pad_thresh, pad_thresh, pad_thresh, cv2.BORDER_CONSTANT, value=255)
return img
Now, let's create a function for segmenting the preprocessed image into individual characters. We'll assume that the text in the image is a single line (change this method according to the images you have). This function returns a list of the segmented character images.
def segment_characters(img: np.ndarray) -> List[np.ndarray]:
contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
characters = []
for c in contours:
x, y, w, h = cv2.boundingRect(c)
character = img[y : y + h, x : x + w]
characters.append(character)
return characters
Finally, generate predictions for the segmented character images. The following function takes a preprocessed and segmented list of character images and the trained model as input and returns the predicted characters' labels.
def predict_characters(character_imgs: List[np.ndarray], model: tf.keras.Model, label_encoder: LabelEncoder) -> List[str]:
processed_characters = []
for character_img in character_imgs:
character_img = preprocess_image(character_img)
character_img = character_img.reshape(1, character_img.shape[0], character_img.shape[1], 1)
processed_characters.append(character_img)
stacked_imgs = np.vstack(processed_characters)
predictions = model.predict(stacked_imgs)
predicted_labels = np.argmax(predictions, axis=1)
predicted_chars = label_encoder.inverse_transform(predicted_labels)
return predicted_chars
Now you can preprocess, segment and generate predictions for your grayscale input image using the above functions as follows:
input_image = cv2.imread('path_to_your_input_image', cv2.IMREAD_GRAYSCALE)
# Preprocess the input image
preprocessed_image = preprocess_image(input_image)
# Segment the preprocessed image into individual characters
character_images = segment_characters(preprocessed_image)
# Predict characters using CNN or RNN model
predicted_chars_cnn = predict_characters(character_images, cnn_model, label_encoder)
predicted_chars_rnn = predict_characters(character_images, rnn_model, label_encoder)
# Print predictions
print("Predicted characters using CNN model:", " ".join(predicted_chars_cnn))
print("Predicted characters using RNN model:", " ".join(predicted_chars_rnn))
Please note that this code is a basic template for processing and segmenting input images and generating predictions for handwritten text recognition. You may need to adjust and fine-tune the code according to your dataset's specifics and any additional requirements. Image segmentation accuracy highly depends on your input images, and you may need to improve the segmentation function to work better for various cases.