yahboom
HomeLearn
Solution
Blog
Online Store
About Us
EN/中文
Transbot SE📖
01.Introduction to Transbot SE
  • 01. Introduction to Transbot SE
  • 02. Precautions for use and battery safety
  • 03. First Trial
02.First Trial
  • 2.1.APP control
  • 2.2.USB wireless handle control(Optional)
  • 2.3.Handle video control Transbot(Optional)
  • 2.4.Network configuration tutorial in hotspot mode
03.Hardware control course
  • 3.1About expansion board and update firmware
  • 3.2.Close self-starting process
  • 3.3.Install Transbot library
  • 3.4.Control buzzer and button
  • 3.5.Control PWM servo
  • 3.6.Control bus servo
  • 3.7.Control motor
  • 3.8.Control robot movement
04.Linux operating system
  • 1. Virtual machine installation and use
  • 2. Linux basics
  • 3. Remote control
  • 4. Multi-machine communication configuration
  • 5. Static IP and hotspot mode
  • 6. Web page real-time monitoring
  • 7. Expansion tutorial
  • 8. Write system images
05.Docker couse(For Pi5)
  • 1.Docker overview and docker installation
  • 2.Common commands for docker image containers
  • 3.Docker images deeply understand and publish images
  • 4.Docker hardware interaction and data processing
  • 5.Start the transbot se container
06.ROS basic course
  • 1.ROS introduction
  • 2.Project file structure
  • 3.Common commands and tools
  • 4.Publisher
  • 5.Subscribers
  • 6.Customize topic messages and use
  • 7.Client
  • 8.Server
  • 9.Custom service messages and usage
  • 10.TF release and monitoring
07.OpenCV courses
  • 1. Getting started with Open Source CV
  • 2. Open Source CV geometric transformation
  • 3. Open Source CV image processing and drawing text line segments
  • 4. Open Source CV image beautification
  • 5. Opencv application
  • 6. AR vision
  • 7. AR QR code
  • 8. ROS+Opencv foundation
  • 9. ROS+Opencv application
  • 10. MediaPipe development
08.ROS robot course
  • 1.PID algorithm
  • 2.Basic communication
  • 3.Keyboard control
  • 4.Handle control(Optional)
  • 5.Robot state estimation
  • 6.Data calibration
09.ROS simple camera course
  • 1.HD camera calibration
  • 2.HD camera color tracking
  • 3.HD camera color tracking (robotic arm)
  • 4.HD camera object tracking
  • 5. KCF target tracking
  • 6.HD camera face tracking
  • 7.HD camera robotic arm carrying
  • 8.HD camera Autopilot
10.ROS robotic arm control tutorial
  • 1.MoveIt configuration
  • 2.MoveIt control the real machine
  • 3.MoveIt moves randomly
  • 4.MoveIt kinematics design
  • 5.MoveIt cartesian path
  • 6.MoveIt avoiding
  • 7.MoveIt scene design
  • 8.MoveIt trajectory planning
  • 9.Mediapipe palm control car
  • 10.Mediapipe gesture control robotic arm
  • 11.Mediapipe gesture control car
  • 12.Mediapipe arm attitude control robotic arm
11.ROS multi-robot control(Optional)
  • 1. Multi-robot control(Optional)
  • 2. Multi-robot queue performance(Optional)
  • 3. Multi-robot robot arm dancing(Optional)
12.Deep learning courses
  • 1.KNN recognizes handwritten digits
  • 2.Basic use of TensorFlow
  • 3.Basic use of PyTorch(jetson)
  • 4.yolov5 model training(jetson)
  • 5.yolov5+tensorrt acceleration(jetson)
  • 6.yolov4-tiny
13.Installation Video
  • Part18
  • Part1-6
  • Part7-12
  • Part13.1-13.3.3
  • Part13.4.1-17
14.FAQnew
  • 1.Using your own Jetson board,Transbot-SE cannot start normally
Download
  • APP(iOS/Android)
  • System_File-Pi5
  • System_File-Pi4
  • System_File-Jetson
  • VM_File
  • Appendix
  • Code
  • InstructionManual
  • Jetson_Boot_USB.tar.gz
  • Hardware_Info
Download ZIP

Welcome to Transbot SE repository

1.KNN recognizes handwritten digits

1 KNN recognizes handwritten digits

1 KNN recognizes handwritten digits 1.1 KNN(K-nearest neighbor algorithm) to recognize handwritten digits 1.1.1 Introduction to KNN 1.1.2 Taking the recognition of handwritten digits as an example to introduce the implementation of the KNN algorithm

1.1 KNN(K-nearest neighbor algorithm) to recognize handwritten digits

1.1.1 Introduction to KNN

  1. KNN(K-Nearest Neighbor) is a supervised learning method. Its working mechanism is very simple, and it does not need to train a training set. It is one of the simpler classical machine learning algorithms. Can handle regression and classification problems.
  2. method ideas

In the feature space, if most of the k nearest(that is, the nearest neighbors in the feature space) samples near a sample belong to a certain category, the sample also belongs to this category.

In official words, the so-called K-nearest neighbor algorithm is to give a training data set, for a new input instance, find the K instances closest to the instance in the training data set(that is, the K neighbors mentioned above).), the majority of these K instances belong to a certain class, and the input instance is classified into this class.

  1. working principle

There is a sample data set, also known as a training sample set, and each data in the sample set has a label, that is, we know the relationship between each data in the sample set and the category to which it belongs. After inputting data without labels, compare each feature in the new data with the features corresponding to the data in the sample set, and extract the classification labels of the most similar data(nearest neighbors) in the sample set. Generally speaking, we only select the top K most similar data in the sample data set, which is the origin of K in the K nearest neighbor algorithm, usually K is an integer not greater than 20. Finally, the classification with the most occurrences in the K most similar data is selected as the classification of the new data.

  1. KNN advantages and disadvantages
  • advantage

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

  • shortcoming

    Lack of training phase, unable to cope with multiple samples, high computational complexity and high space complexity

  1. KNN implementation steps:
  • Calculate distance

    Euclidean distance, that is

    image-20220222145000137

  • Sort by increasing distance

  • Select the K points with the smallest distance(generally no more than 20)

  • Determine the frequency of occurrence of the category in which the first K points belong, frequency = a category/k

  • Returns the category with the highest frequency in the top K points as the predicted classification of the test data

1.1.2 Taking the recognition of handwritten digits as an example to introduce the implementation of the KNN algorithm

  1. data set
  • Training set

    The training set is already classified data, you can refer to the directory ~/KNN/knn-digits/trainingDigits

    Note: The training set has been trained. If the user wants to train by himself, he needs to back up the original training set first. The number of training sets is large.

  • test set

The test set is used to test the algorithm, you can refer to the directory ~/KNN/knn-digits/testDigits

  1. use the drawing function under windows to make handwritten digital pictures
  • Open the drawing software, adjust the resolution to 32*32, or other resolutions, but it is best to draw to fill the entire interval, otherwise the error rate is very high.

image-20220222151155632

  • Hold down ctrl and slide the mouse wheel up to enlarge the picture to the maximum. Pick the Paint Bucket Tool and choose a black color to fill the entire screen.

    image-20220222151348607

  • Pick the Pencil Tool, choose White for the Color, and the Maximum Width for the Line Thickness. As shown below:

image-20220305122748713

After drawing, save it as a png image(this example takes 8.png as an example), and copy it to the project directory through the WinSCP tool

  1. Convert the image(.img) to text(.txt)
  • code

Code location: ~/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 file name

txt_name: After conversion, save it in the ~/KNN/knn-digits/testDigits directory, the name is 8_1.txt

  • run the program

jetson motherboard/Raspberry Pi 4B

xxxxxxxxxx
cdKNN
python3 img2file.py

Raspberry Pi 5

Note: Open the Raspberry Pi 5 terminal directly without entering docker

xxxxxxxxxx
cdKNN
python3 img2file.py

After the program is run, a file named 8_1.txt will be generated in the KNN directory. Double-click it and you will see something like this:image-20220222161205064

It can be seen that the part with the number 8 is roughly surrounded by a number 8.

  1. run the KNN recognition algorithm program

jetson motherboard/Raspberry Pi 4B

xxxxxxxxxx
In the ~/KNN directory, open the terminal and run
python3knn.py

Raspberry Pi 5

Note: Open the Raspberry Pi 5 terminal directly without entering docker

xxxxxxxxxx
cdKNN
python3knn.py
  • code

Code location: ~/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 recognition, k represents the k value in the algorithm - select the top K most similar data in the sample data set, the k value is generally an integer not greater than 20 
 def handWritingClassTest(k): 
    hwLabels  = [] 
    trainingFileList = os.listdir('knn-digits/trainingDigits') 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') 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("The classification result is: %d, the real result is: %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("Total number of errors: %d"  %  errorCount) 
    print("Error rate: %f"  %(errorCount / mTest)) 
    return  errorCount 

handWritingClassTest(1) 

  • run screenshot

image-20220222162113689

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

  • Program Description

    The name of the text file converted from the picture, taking 8_1 as an example, knn.py will parse the file name in the program, the underscore is the limit, the front 8 represents the real number, and the latter part can be customized, see the code,

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

Train first, then identify.

Multi-robot robot arm dancing(Optional)
Basic use of TensorFlow

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/中文