Home > Article > Backend Development > How to Implement Simple Digit Recognition in OpenCV-Python using the letter_recognition.data Dataset?
The letter_recognition.data file is a dataset that contains 20,000 samples of handwritten letters, with each letter represented by 16 features. To build a similar file from your own dataset, you can follow these steps:
results.reval() is the output array returned by the find_nearest() function of OpenCV's KNearest class. It contains the predicted labels for the given samples.
To write a simple digit recognition tool using the letter_recognition.data file, you can follow these steps:
Training:
Testing:
Below is an example code that demonstrates the training and testing process:
import numpy as np import cv2 # Load training data samples = np.loadtxt('letter_recognition.data', np.float32, delimiter=',', converters={0: lambda ch: ord(ch) - ord('A')}) responses = samples[:, 0] samples = samples[:, 1:] # Create KNearest classifier model = cv2.KNearest() # Train the classifier model.train(samples, responses) # Load test image test_image = cv2.imread('test_image.png') # Preprocess the image gray = cv2.cvtColor(test_image, cv2.COLOR_BGR2GRAY) thresh = cv2.adaptiveThreshold(gray, 255, 1, 1, 11, 2) # Extract digits contours, hierarchy = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) digits = [] for cnt in contours: if cv2.contourArea(cnt) > 50: [x, y, w, h] = cv2.boundingRect(cnt) roi = thresh[y:y + h, x:x + w] roismall = cv2.resize(roi, (10, 10)) digits.append(roismall) # Predict labels for digits results = model.find_nearest(np.array(digits), 10) labels = [chr(ch + ord('A')) for ch in results[0]] # Display recognized digits on the image for i, label in enumerate(labels): cv2.putText(test_image, str(label), (digits[i][0], digits[i][1]), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0)) cv2.imshow('Recognized Digits', test_image) cv2.waitKey(0)
By following these steps and leveraging the KNearest classifier in OpenCV, you can create a basic digit recognition tool that can be further improved upon for more complex digit recognition tasks.
The above is the detailed content of How to Implement Simple Digit Recognition in OpenCV-Python using the letter_recognition.data Dataset?. For more information, please follow other related articles on the PHP Chinese website!