imkrish commited on
Commit
5beaba7
·
verified ·
1 Parent(s): 6437641

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -0
app.py CHANGED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import numpy as np
4
+ import tensorflow as tf
5
+ import pickle
6
+ import tkinter as tk
7
+ from tkinter import filedialog
8
+
9
+ # Set global parameters (update these as per your model's training settings)
10
+ IMAGE_WIDTH = 128
11
+ IMAGE_HEIGHT = 64
12
+ MAX_TEXT_LENGTH = 32
13
+
14
+ # Function to preprocess the image
15
+ def preprocess_image(image_path, image_width, image_height):
16
+ img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
17
+ if img is None:
18
+ print(f"Error reading image: {image_path}")
19
+ return None
20
+ img = cv2.resize(img, (image_width, image_height))
21
+ img = img / 255.0
22
+ img = img.T # Transpose if your model requires it
23
+ img = np.expand_dims(img, axis=-1)
24
+ img = np.expand_dims(img, axis=0)
25
+ return img
26
+
27
+ # Function to predict the word from the image using your model and tokenizer
28
+ def predict_word(model, image_path, tokenizer, max_text_length):
29
+ img = preprocess_image(image_path, IMAGE_WIDTH, IMAGE_HEIGHT)
30
+ if img is None:
31
+ return ""
32
+
33
+ # Get the model prediction
34
+ prediction = model.predict(img)
35
+ predicted_indices = np.argmax(prediction, axis=-1)[0]
36
+
37
+ # Create a reverse mapping from index to character
38
+ reverse_index = {index: char for char, index in tokenizer.word_index.items()}
39
+
40
+ # Convert prediction indices into a string (ignoring padding zeros)
41
+ predicted_word = ''.join([reverse_index.get(index, '') for index in predicted_indices if index != 0])
42
+ return predicted_word
43
+
44
+ # Load your trained Keras model
45
+ model = tf.keras.models.load_model("handwritten_text_recognition_model.keras")
46
+
47
+ # Load the tokenizer (make sure 'tokenizer.pickle' exists in your project directory)
48
+ with open("tokenizer.pickle", "rb") as handle:
49
+ tokenizer = pickle.load(handle)
50
+
51
+ # Create a simple Tkinter file dialog to select an image
52
+ root = tk.Tk()
53
+ root.withdraw() # Hide the main window
54
+
55
+ # Open file dialog for image selection
56
+ image_path = filedialog.askopenfilename(
57
+ title="Select an Image",
58
+ filetypes=[("Image Files", "*.png;*.jpg;*.jpeg")]
59
+ )
60
+
61
+ if image_path:
62
+ predicted_word = predict_word(model, image_path, tokenizer, MAX_TEXT_LENGTH)
63
+ print("Predicted word:", predicted_word)
64
+ else:
65
+ print("No image selected.")