yahboom
HomeLearn
Solution
Blog
Online Store
About Us
EN/中文
Jetson AGX Thor📖
1.Get started
  • 01.Learning Route
  • 02.Getting Started Quickly
2.Jetson basic course
  • 01.Jetson board introduction
  • 02.Flashing a Pure Jetson System via SDK
  • 03.Flashing a Pure Jetson System via USB Drive
  • 04.Flashing the Jetson Bootloader using L4T
  • 05.Replacing the SSD
  • 06.Install Jetpack environment
  • 07.Backup SSD system
  • 08.Restore factory image system
  • 09.SSD expansion
  • 10.SSD Speed Test
3.Basic setting course
  • 01.Basic knowledge
  • 02.Network configuration
  • 03.SSH remote login
  • 04.VNC remote control
  • 05.Remote file transfer
  • 06.Jtop tool
  • 07.Exchange space expansion
  • 08.Use VSCode
  • 09.Use VMware
  • 10.Change screen resolution
  • 11.Virtual Desktop
  • 12.Set root user password
  • 13.Configure sudo passwordless operation
  • 14.Managing custom services
  • 15.View system version information
4.OpenCV basic course
  • 01.Image reading
  • 02.Image saving
  • 03.Image modification
  • 04.Image scaling
  • 05.Image cropping
  • 06.Image translation
  • 07.Image mirroring
  • 08.Image grayscale conversion
  • 09.Image binarization
  • 10.Image edge detection
  • 11.Add line segments
  • 12.Add rectangles
  • 13.Add circular shape
  • 14.Add ellipses
  • 15.Add polygons
  • 16.Add Text
5.Vision basic course
  • 01.USB camera preview
  • 02.Use Jupyter Lab
  • 03.Use JetCam
6.Vision advanced course
01.Environment construction
  • 01.TensorFlow
  • 02.PyTorch
  • 03.Torchvision
  • 04.Torchaudio
02.DeepStream development
  • 01.DeepStream environment
  • 02.Four types of detection(traffic)
03.YOLO26 development
  • 01.YOLO Environment Setup
  • 02.CLI Usage
  • 03.Object Detection
  • 04.Instance Segmentation
  • 05.Pose Estimation
  • 06.Image Classification
  • 07.Oriented Bounding Boxes Object Detection
  • 08.Model Conversion
  • 09.Dataset Annotation
  • 10.Model Training_Conversion
  • 11.Model Prediction
04.Mediapipe development
  • 01.Mediapipe environment
  • 02.Hand detection
  • 03.Face detection
  • 04.Face effects
  • 05.3D object recognition
  • 06.Virtual brush
  • 07.Gesture recognition
  • 08.Finger control
  • 09.Posture estimation
  • 10.Face mask
  • 11.Overall detection
  • 12.Green scene removal(Human)
05.QR code recognition
  • 01.Barcode Recognition
  • 02.QR Code Recognition
  • 03.Machine Code Recognition
  • 04.Handwritten Digit Recognition
7.Docker basic course
  • 01.Docker introduction
  • 02.Docker installation
  • 03.Docker command
  • 04.Docker usage
  • 05.Docker interaction
8.ROS2-jazzy
1.ROS2 basic course
  • 1.Introduction to ROS2
  • 2.ROS2 install Jazzy
  • 3.ROS2 development environment
  • 4.ROS2 workspace
  • 5.ROS2 function package
  • 6.ROS2 node
  • 7.ROS2 topic communication
  • 8.ROS2 service communication
  • 9.ROS2 action communication
  • 10.ROS2 custom interface message
  • 11.ROS2 parameter service case
  • 12.ROS2 meta-function package
  • 13.ROS2 distributed communication
  • 14.ROS2 DDS
  • 15.ROS2 time related API
  • 16.ROS2 common command tools
  • 17.ROS2 rviz2 use
  • 18.ROS2 rqt toolbox
  • 19.ROS2 Launch startup file configuration
  • 20.ROS2 recording and playback tool
  • 21.ROS2 URDF model
  • 22.ROS2 Gazebo simulation platform
  • 23.ROS2 TF2 coordinate transformation
2.ROS2 vision course
  • 01.Camera preview (USB)
  • 02.Camera calibration (USB)
  • 03.AR vision (USB)
9.Offline AI model course
Offline large model (Text Interaction)
  • 1.Al large model environment deployment
  • 2.Install large model dialogue platform
  • 3.Meta Al Llama3.2 model
  • 4.Alibaba Cloud Qwen3 model
  • 5.Microsoft Phi-4-mini model
  • 6.DeepSeek DeepSeek-R1 model
  • 7.Alibaba Cloud Qwen2.5v visual multimodal large model
  • 8.Google Gemma3 visual multimodal large model
  • 9.Lava visual multimodal large model
  • 10.MiniCPM-V visual multimodal large model
  • 11.Multimodal visual understand application
  • 12.Multimodal text image application
  • 13.Multimodal video analysis application
  • 14.Multi module visual position application
  • 15.Multimodal table scanning application
  • 16.Multimodal autonomous agent application
Offline large model (Voice Interaction)
  • 0.Voice interaction hardware connection (ReadMe)
  • 1.Offline speech to text (ASR)
  • 2.Offline text to speech (TTS)
  • 3.AI large model voice interaction
  • 4.Multimodal visual understand speech interaction
  • 5.Multimodal text and graphics application
  • 6.Multimodal video analysis application
  • 7.Multi module visual position application
  • 8.Multimodal table scanning application
  • 9.Multimodal autonomous proxy application
  • 10.AI large model offline voice assistant
10.Online AI model course
Online large model (Text Interaction)
  • 1.OpenRouter large model API aggregation platform
  • 2.Multimodal Video Analysis Applications
  • 3.Multimodal visual localization application
  • 4.Multimodal table scanning application
  • 5.Multimodal autonomous proxy application
Online large model (Voice Interaction)
  • 0.Voice interaction hardware connection (ReadMe)
  • 1.Online speech to text (ASR)
  • 2.Online text to speech (TTS)
  • 3.AI large model voice interaction
  • 4.Multimodal visual understand speech interaction
  • 5.Multi module visual position application
  • 6.Multimodal table scanning application
  • 7.Multimodal autonomous proxy application
  • 8.AI large model offline voice assistant
11.Generative AI Applications
12.OpenClaw Advanced Development
  • 00.OpenClaw Quick Start on Jetson Platform
  • 01.OpenClaw Installation
  • 02.OpenClaw Online Platform Deployment
  • 03.OpenClaw Local Model Deployment
  • 04.OpenClaw TUI Interaction
  • 05.OpenClaw WebChat Interaction
  • 06.OpenClaw Tools Introduction
  • 07.OpenClawGate Gateway User Manual
  • 08.OpenClaw Features Overview
  • 09.OpenClawClawHub Introduction (Skill Installation)
  • 10. OpenClaw Switching Models
  • 11.OpenClaw Application - File Management
  • 12.OpenClaw Application - Camera
  • 13.OpenClaw Application - Browser Control
  • 14.OpenClaw Application - Script Execution
  • 15.OpenClaw Application - AI Programming
  • 16.OpenClaw Application - Dedicated AI Assistant
  • 17.OpenClaw WhatsApp Plugin Application
  • 18.OpenClaw Voice Assistant
Download
  • Code
  • SystemFile
  • VM_File
  • Tools
  • Jetson boot files
Download ZIP

Welcome to Jetson AGX Thor repository

04.Handwritten Digit Recognition

Handwritten Digit Recognition

1. Introduction to KNN (K-Nearest Neighbors) for Handwritten Digit Recognition

1) KNN (K-Nearest Neighbor) is a supervised learning method. Its working mechanism is very simple, requiring no training set, and it is one of the simpler classic machine learning algorithms. It can handle regression and classification problems.

2) Methodology

In the feature space, if the majority of the k nearest neighbors (i.e., the closest neighbors in the feature space) of a sample belong to a certain class, then the sample also belongs to that class.

In official terms, the K-Nearest Neighbors algorithm is, given a training dataset, for a new input instance, finding the K nearest neighbors (the K neighbors mentioned above) in the training dataset. If the majority of these K neighbors belong to a certain class, the input instance is classified into that class.

3) Working Principle

There exists a set of sample data, also called the training sample set, and each data point in the sample set has a label, meaning we know the relationship between each data point in the sample set and its corresponding class. After inputting unlabeled data, each feature in the new data is compared with the corresponding features in the sample set, extracting the classification label of the most similar data (nearest neighbor) in the sample set. Generally, we only select the top K most similar data in the sample dataset; this is the origin of K in the K-nearest neighbor algorithm, and K is usually an integer no greater than 20. Finally, the classification of the new data is selected based on the most frequent occurrence among the K most similar data.

4) Advantages and Disadvantages of KNN

  • Advantages

Flexible usage, convenient for small sample prediction, high accuracy, insensitive to outliers, no data input assumptions

  • Disadvantages

Lacks a training phase, cannot handle multiple samples, high computational and space complexity

5) KNN Implementation Steps:

  • Calculate distance

Euclidean distance, i.e.

image-20220222145000137.png

  • Sort points according to increasing distance
  • Select the K points with the smallest distance (generally no more than 20)
  • Determine the frequency of occurrence of the class of the top K points, frequency = class / k
  • Return the class with the highest frequency among the top K points as the predicted classification for the test data

2. Introducing the KNN algorithm implementation using handwritten digit recognition as an example

1) Dataset

  • Training Set

The training set is pre-classified data. You can refer to ~/content_recognition/KNN/knn-digits/trainingDigits in the directory.

Note: The training set is already trained. If you want to train it yourself, you need to back up the original training set first, as it is quite large.

  • Test Set

The test set is used to test the algorithm. You can refer to ~/content_recognition/KNN/knn-digits/testDigits in the directory.

2) Creating handwritten digit images using Windows Paint

  • Open Paint and adjust the resolution to 32*32. Other resolutions are also possible, but it's best to fill the entire area with the drawing; otherwise, the error rate will be high.

image-20220222151155632.png

  • Hold down Ctrl and scroll the mouse wheel upwards to zoom in on the image to its maximum. Select the Paint Bucket tool and choose black to fill the entire image.

image-20220222151348607.png

  • Select the Pencil tool, choose white as the color, and select the maximum line width. As shown in the image below:

image-20220305122748713

After drawing, save it as a PNG image (using 8.png as an example), and copy it to the project directory using WinSCP.

3) Convert the image (.img) to text (.txt)

  • Code

Code location: ~/content_recognition/KNN/img2file.py

​x
from PIL import Image
​
import numpy as np
​
​
def img2txt(img_path, txt_name):
​
    im = Image.open(img_path).convert('1').resize((32, 32))  # type:Image.Image
​
    data = np.asarray(im)
​
    np.savetxt(txt_name, data, fmt='%d', delimiter='')
img2txt("8.png","./knn-digits/testDigits/8_1.txt")

img_path: Image filename

txt_name: The converted file will be saved in the ~/content_recognition/KNN/knn-digits/testDigits directory, named 8_1.txt

  • Run the program
xxxxxxxxxx
cd ~/content_recognition/KNN
python img2file.py

After the program runs, a file named 8_1.txt will be generated in the KNN directory. Double-clicking it will show something like this:

image-20220222161205064

You can see that the part containing the number 8 roughly encloses the number 8.

4) Run the KNN recognition algorithm program

Open the terminal and run the following command:

xxxxxxxxxx
cd ~/content_recognition/KNN
python knn.py
  • Code

Code location: ~/content_recognition/KNN/knn.py

xxxxxxxxxx
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 16 14:53:46 2017
​
@author: jiangkang
"""
​
import numpy
import operator
import os
import matplotlib.pyplot as plt
​
def img2vector(filename):
    returnVect = numpy.zeros((1, 1024))
    file = open(filename)
    for i in range(32):
        lineStr = file.readline()
        for j in range(32):
            returnVect[0, 32 * i + j] = int(lineStr[j])
    return returnVect
​
def classifier(inX, dataSet, labels, k):
    dataSetSize = dataSet.shape[0]
    diffMat = numpy.tile(inX, (dataSetSize, 1)) - dataSet
    sqDiffMat = diffMat ** 2
    sqDistances = sqDiffMat.sum(axis=1)
    distances = sqDistances ** 0.5
    sortedDistIndicies = distances.argsort()
    classCount = {}
    for i in range(k):
        voteIlabel = labels[sortedDistIndicies[i]]
        classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
    sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]
#Train first, then test for recognition. k represents the k-value in the algorithm - selecting the K most similar data points from the sample dataset. The k-value is generally an integer not greater than 20.  
def handWritingClassTest(k):
    hwLabels = []
    trainingFileList = os.listdir('knn-digits/trainingDigits') #Read training set data
    m = len(trainingFileList)
    trainingMat = numpy.zeros((m, 1024))
    for i in range(m):
        fileNameStr = trainingFileList[i]
        fileStr = fileNameStr.split('.')[0]
        classNumStr = int(fileStr.split('_')[0])
        hwLabels.append(classNumStr)
        trainingMat[i, :] = img2vector("knn-digits/trainingDigits/%s" % fileNameStr)
    testFileList = os.listdir('knn-digits/testDigits') #Read test set data
    errorCount = 0.0
    mTest = len(testFileList)
    for i in range(mTest):
        fileNameStr = testFileList[i]
        fileStr = fileNameStr.split('.')[0]
        classNumStr = int(fileStr.split('_')[0])
        vectorTest = img2vector("knn-digits/testDigits/%s" % fileNameStr)
        result = classifier(vectorTest, trainingMat, hwLabels, k)
        print("分类结果是:%d, 真实结果是:%d" % (result, classNumStr))
        if result != classNumStr:
            errorCount += 1.0
    '''fileStr = "2.txt"
    classNumStr = int(fileStr.split('.')[0])
    vectorTest = img2vector("./2.txt")
    result = classifier(vectorTest, trainingMat, hwLabels, 3)'''
    print("错误总数:%d" % errorCount)
    print("错误率:%f" % (errorCount / mTest))
    return errorCount
​
handWritingClassTest(1)
​
  • Screenshot of the running process

image-20220222162113689.png

As shown in the figure, the recognized number is 8, which is correct. If the recognition result is different from the actual result, please copy the converted txt document to knn-digits/trainingDigits/ and name it as follows: 8_801.txt, and then retrain and recognize it normally.

  • Program description

The text file converted from the image is named as follows, taking 8_1 as an example. knn.py will parse this file name in the program. The underscore is used as the boundary. The 8 at the beginning represents the actual number, and the part after can be customized. See the code.

xxxxxxxxxx
classNumStr = int(fileStr.split('_')[0])

Train first, then recognize.

Machine Code Recognition
Docker introduction

COMPANY

  • About us
  • Team Style
  • Blog

LEARNING & EXPLORATION

  • Tutorials
  • Edge AI hardware
  • Educational robots
  • Embedded intelligent hardware

WHERE TO BUY

  • Yahboom Online Store
  • Amazon
  • Alibaba
  • AliExpress
  • Mercado

TECHNOLOGY SUPPORT

  • Email: support@yahboom.com

BE A DISTRIBUTOR

  • Email: sales@yahboom.com
QR Code
QR Code

Copyright © 2017-2026 Yahboom. All Rights Reserved.

EN/中文