1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
#include <iostream> #include <opencv2/opencv.hpp> #include <opencv2/ml.hpp> using namespace std; using namespace cv; using namespace cv::ml; int main() { // Load the pre-trained KNN model Ptr<KNearest> knn = KNearest::create(); knn->read("knn_model.xml"); // The model file should be pre-trained and saved // Load the handwritten digit image Mat img = imread("handwritten_digit.png", IMREAD_GRAYSCALE); if (img.empty()) { cerr << "Error loading image!" << endl; return -1; } // Preprocess the image Mat resized_img, flattened_img; resize(img, resized_img, Size(28, 28)); // Resize image to match training size resized_img.convertTo(resized_img, CV_32F); // Convert to float for KNN flattened_img = resized_img.reshape(1, 1); // Flatten to 1D vector // Predict the digit Mat result; knn->findNearest(flattened_img, 1, result); // Output the result cout << "Predicted digit: " << result.at<float>(0, 0) << endl; return 0; } |
Explanation:
- Dependencies:
- OpenCV is used for image processing and machine learning functions. You need to have OpenCV installed and properly linked with your project.
Advertisement - Load Pre-trained Model:
Ptr<KNearest> knn = KNearest::create();
creates a KNN object.knn->read("knn_model.xml");
loads a pre-trained KNN model from an XML file. You need to have this model pre-trained and saved.
- Load and Preprocess Image:
imread("handwritten_digit.png", IMREAD_GRAYSCALE);
loads the handwritten digit image in grayscale mode.resize(img, resized_img, Size(28, 28));
resizes the image to 28×28 pixels to match the training size.resized_img.convertTo(resized_img, CV_32F);
converts the image to a floating-point format suitable for KNN.flattened_img = resized_img.reshape(1, 1);
flattens the 2D image to a 1D vector.
Advertisement - Predict the Digit:
knn->findNearest(flattened_img, 1, result);
performs the KNN classification and stores the result.result.at<float>(0, 0)
contains the predicted digit.
- Output the Result:
cout << "Predicted digit: " << result.at<float>(0, 0) << endl;
prints the predicted digit.
Requirements:
- Pre-trained Model: You need a pre-trained KNN model to recognize handwritten digits. You can train this model using a dataset like MNIST and save it as
knn_model.xml
. - Handwritten Digit Image: Ensure you have an image file named
handwritten_digit.png
Advertisement
Possible Enhancements:
- Improved Accuracy: Use more sophisticated algorithms or deep learning models for better accuracy.
- Real-time Recognition: Implement real-time recognition using a camera and dynamic preprocessing.
- GUI Integration: Create a graphical user interface to allow users to draw digits and see predictions interactively.