机器学习-基于KNN及其改进的汉字图像识别系统

news2024/10/7 8:28:13

一、简介和环境准备

knn一般指邻近算法。 邻近算法,或者说K最邻近(KNN,K-NearestNeighbor)分类算法是数据挖掘分类技术中最简单的方法之一。而lmknn是局部均值k最近邻分类算法。

本次实验环境需要用的是Google Colab和Google Drive(云盘),文件后缀是.ipynb可以直接用。首先登录谷歌云盘(网页),再打卡ipynb文件就可以跳转到谷歌colab了。再按以下点击顺序将colab和云盘链接。

from google.colab import drive
drive.mount('/content/drive')

 准备的数据是一些分类好的手写汉字图(实验来源在结尾)

引入库

from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from imutils import paths
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import glob
import argparse
import imutils
import cv2
import os
# import sys
# np.set_printoptions(threshold=sys.maxsize)

二、数据预处理和算法简介

2.1预处理

注意路径的修改。这一步处理所有图片数据,存到xy的train和test。

x_train = []
y_train = []
x_test = []
y_test = []

for i in os.listdir('./drive/MyDrive/Chinese-HCR-master/TA_dataset/train'):
    for filename in glob.glob('drive/MyDrive/Chinese-HCR-master/TA_dataset/train/'+str(i)+'/*.png'):
        im = cv2.imread(filename, 0)        
        im = cv2.resize(im, (128, 128)) # resize to 128 * 128 pixel size
        blur = cv2.GaussianBlur(im, (5,5), 0) # using Gaussian blur
        ret, th = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
        x_train.append(th)
        y_train.append(i) # append class
        
for i in os.listdir('./drive/MyDrive/Chinese-HCR-master/TA_dataset/test'):
    for filename in glob.glob('drive/MyDrive/Chinese-HCR-master/TA_dataset/test/'+str(i)+'/*.png'):
        im = cv2.imread(filename, 0)        
        im = cv2.resize(im, (128, 128)) # resize to 128 * 128 pixel size
        blur = cv2.GaussianBlur(im, (5,5), 0) # using Gaussian blur
        ret, th = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
        x_test.append(th)
        y_test.append(i) # append class
x_train = np.array(x_train) / 255
x_test = np.array(x_test) / 255
y_train = np.array(y_train)
# x_train = np.array(x_train)
# x_test = np.array(x_test)

可以打印看一下

plt.imshow(x_train[0])
plt.show()

plt.imshow(x_test[0], 'gray')
plt.show()

 2.2算法代码

1.KNN

这里不像上一章分析源码,只调用

from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
neigh = KNeighborsClassifier(n_neighbors=3)
xtrain = np.reshape(x_train, (x_train.shape[0], x_train.shape[1] * x_train.shape[1]))
xtest = np.reshape(x_test, (x_test.shape[0], x_test.shape[1] * x_test.shape[1]))
prediction = neigh.fit(xtrain, y_train).predict(xtrain)
prediction
print(accuracy_score(y_train,prediction))

0.7969348659003831

2.基于HOG特征提取的KNN

from skimage.feature import hog
features = np.array(xtrain, 'int64')
labels = y_train
list_hog_fd = []
for feature in features:
    fd = hog(
        feature.reshape((128, 128)), 
        orientations=8, 
        pixels_per_cell=(64, 64), 
        cells_per_block=(1, 1), )
    list_hog_fd.append(fd)
hog_features = np.array(list_hog_fd)
hog_features

array([[0.52801754, 0. , 0.52801754, ..., 0. , 0.5 , 0. ], [0.35309579, 0. , 0.54016151, ..., 0. , 0.5 , 0. ], [0.5 , 0. , 0.5 , ..., 0. , 0.5 , 0. ], ..., [0.5035908 , 0. , 0.59211517, ..., 0. , 0.5 , 0. ], [0.51920317, 0. , 0.51920317, ..., 0. , 0.5 , 0. ], [0.55221191, 0. , 0.55221191, ..., 0. , 0.5 , 0. ]])

(注:如果没运行1的knn 要先跑下面的)

neigh = KNeighborsClassifier(n_neighbors=3)
xtrain = np.reshape(x_train, (x_train.shape[0], x_train.shape[1] * x_train.shape[1]))
xtest = np.reshape(x_test, (x_test.shape[0], x_test.shape[1] * x_test.shape[1]))
prediction = neigh.fit(hog_features, labels).predict(hog_features)
prediction
print(accuracy_score(labels,prediction))

0.6360153256704981

3.带骨架的KNN

from skimage.morphology import skeletonize
from skimage import data
import matplotlib.pyplot as plt
from skimage.util import invert

# Invert the horse image
image = invert(x_train[0])

# perform skeletonization
skeleton = skeletonize(image)

# display results
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(8, 4),
                         sharex=True, sharey=True)

ax = axes.ravel()

ax[0].imshow(image, cmap=plt.cm.gray)
ax[0].axis('off')
ax[0].set_title('original', fontsize=20)

ax[1].imshow(skeleton, cmap=plt.cm.gray)
ax[1].axis('off')
ax[1].set_title('skeleton', fontsize=20)

fig.tight_layout()
plt.show()

from sklearn.neighbors import KNeighborsClassifier
neigh = KNeighborsClassifier(n_neighbors=3)
xtrain = np.reshape(x_train, (x_train.shape[0], x_train.shape[1] * x_train.shape[1]))
xtest = np.reshape(x_test, (x_test.shape[0], x_test.shape[1] * x_test.shape[1]))
from sklearn.metrics import accuracy_score
prediction = neigh.fit(xtrain, y_train).predict(xtrain)
prediction
print(accuracy_score(y_train,prediction))

0.7969348659003831

4.拓展--Otsu方法概述

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('drive/MyDrive/Chinese-HCR-master/TA_dataset/train/亮/37162.png',0)
img = cv.medianBlur(img,5)
ret,th1 = cv.threshold(img,127,255,cv.THRESH_BINARY)
th2 = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_MEAN_C,\
            cv.THRESH_BINARY,11,2)
th3 = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,\
            cv.THRESH_BINARY,11,2)
titles = ['Original Image', 'Global Thresholding (v = 127)',
            'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']
images = [img, th1, th2, th3]
for i in range(4):
    plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])
plt.show()

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('drive/MyDrive/Chinese-HCR-master/TA_dataset/train/亮/37162.png',0)
# global thresholding
ret1,th1 = cv.threshold(img,127,255,cv.THRESH_BINARY)
# Otsu's thresholding
ret2,th2 = cv.threshold(img,0,255,cv.THRESH_BINARY+cv.THRESH_OTSU)
# Otsu's thresholding after Gaussian filtering
blur = cv.GaussianBlur(img,(5,5),0)
ret3,th3 = cv.threshold(blur,0,255,cv.THRESH_BINARY+cv.THRESH_OTSU)
# plot all the images and their histograms
images = [img, 0, th1,
          img, 0, th2,
          blur, 0, th3]
titles = ['Original Noisy Image','Histogram','Global Thresholding (v=127)',
          'Original Noisy Image','Histogram',"Otsu's Thresholding",
          'Gaussian filtered Image','Histogram',"Otsu's Thresholding"]
for i in range(3):
    plt.subplot(3,3,i*3+1),plt.imshow(images[i*3],'gray')
    plt.title(titles[i*3]), plt.xticks([]), plt.yticks([])
    plt.subplot(3,3,i*3+2),plt.hist(images[i*3].ravel(),256)
    plt.title(titles[i*3+1]), plt.xticks([]), plt.yticks([])
    plt.subplot(3,3,i*3+3),plt.imshow(images[i*3+2],'gray')
    plt.title(titles[i*3+2]), plt.xticks([]), plt.yticks([])
plt.show()


来源:GitHub - NovitaGuok/Chinese-HCR: A Chinese Character Recognition system using KNN, LMPNN, and MVMCNN

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/365996.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

ASEMI高压MOS管60R380参数,60R380特征,60R380应用

编辑-Z ASEMI高压MOS管60R380参数: 型号:60R380 漏极-源极电压(VDS):600V 栅源电压(VGS):20V 漏极电流(ID):11A 功耗(PD&#x…

Python的PyQt框架的使用-资源文件夹的使用

Python的PyQt框架的使用-资源文件夹的使用一、前言二、Qt Designer加载资源文件三、资源文件的转换一、前言 个人主页: ζ小菜鸡大家好我是ζ小菜鸡,小伙伴们,让我们一起来学习Python的PyQt框架的使用。如果文章对你有帮助、欢迎关注、点赞、收藏(一键三…

win10怎么取消开机密码?电脑小白也可以轻松掌握的3种方法

为了保护隐私,我们大多喜欢给自己的电脑“上锁”,即设置开机密码。有时候,我们想要取消电脑的开机密码,却不知有什么方法可以帮到我们。win10怎么取消开机密码?方法有很多。 比如:通过运行来进入用户账户设…

Golang学习Day1

😋 大家好,我是YAy_17,是一枚爱好网安的小白。本人水平有限,欢迎各位大佬指点,欢迎关注 😁,一起学习 💗 ,一起进步 ⭐ 。⭐ 此后如竟没有炬火,我便是唯一的光…

GEE学习笔记 五十一:Fusion Table将在2019年12月3日关闭

刚刚看到的一则消息,Google运行了9年之久的Fusion Table将在2019年12月3日关闭相关服务,同时也就是未来Google Earth Engine(GEE)上将不会存在Fusion Table这一数据,GEE官方也不再建议用户使用Fusion Table数据。 目前…

anaconda:安装cuda和对应版本的cudnn

复现别人论文的时候经常遇到不同的cuda版本,可以使用anaconda创建虚拟环境,并在不同的虚拟环境中配置对应的cuda版本 1、安装anaconda及虚拟环境使用 Anaconda多个python版本(python2.7 & python3.8) 2、安装cuda和对应版本…

【机器学习】噪声数据的理解

文章目录一、噪声数据1.1 分箱1.2 回归1.3 聚类1.4 其他二、数据清理作为一个过程2.1 偏差检测2.1.1 使用“元数据”:关于数据的数据2.1.2 编码格式:存在使用不一致、数据表示不一致2.1.3 字段过载2.1.4 唯一性规则2.1.5 连续性规则2.1.6 空值规则2.2 数…

爆赞!首次公布阿里Java成长路线,Github访问量突破80万

作为程序员,进大厂是大多数人的梦想,进大厂的好处也如下图一样: 有面儿,不易失业。牛人多,培训多,成长更快。钱多。有较为完善的晋升规则。站在巨人肩膀人,眼界开阔更何况程序员不同于其他行业…

zabbix4.0安装部署

目录 1.1、添加 Zabbix 软件仓库 1.2、安装 Server/proxy/前端 1.3、创建数据库 1.4、导入数据 1.5、为 Zabbix server/proxy 配置数据库 1.6、 启动 Zabbix server 进程 1.7、zabbix前端配置 SELinux 配置 1.8、安装 Agent 1.9、启动zabbix 2.0、访问zabbix 1.1、添加…

【图像处理OpenCV(C++版)】——4.6 限制对比度的自适应直方图均衡化

前言: 😊😊😊欢迎来到本博客😊😊😊 🌟🌟🌟 本专栏主要结合OpenCV和C来实现一些基本的图像处理算法并详细解释各参数含义,适用于平时学习、工作快…

使用FORCE训练的脉冲神经网络中的监督学习(Matlab代码实现)

目录 💥1 概述 📚2 运行结果 🎉3 参考文献 👨‍💻4 Matlab代码 💥1 概述 1.1 脉冲神经网络简介 脉冲神经网络 (SNN) 属于第三代神经网络模型,实现了更高级的生物神经模拟水平。除了神经元和…

3.知识图谱概念和相关技术简介[知识抽取、知识融合、知识推理方法简述],典型应用案例介绍国内落地产品介绍。一份完整的入门指南,带你快速掌握KG知识,芜湖起飞!

1. 知识图谱(KG)的概念 知识图谱(KG)得益于Web的发展(更多的是数据层面),有着来源于KR、NLP、Web、AI多个方面的基因。知识图谱是2012年后的提法,基础还是语义网和本体论。 知识图谱的本质包含: 知识表示——Knowledge Representation基于知识表示的知识库——Knowledge…

OpenGL入门demo

开发环境visual studio 2022 preview版本,x64版本安装OpenGL首先OpenGL是windows系统里面自带的,我们可以不用去下载最新版。直接在此基础上配置OpenGL的三个扩展库glew,glfw,flut就可以了。下载OpenGL的开发依赖类库:…

【java】Spring Cloud --Spring Cloud Alibaba 微服务解决方案

文章目录1、Spring Cloud Alibaba 是什么先说说 Spring CloudSpring Cloud Alibaba和Spring Cloud 的区别和联系Spring Cloud Alibaba2、Spring Cloud Alibaba 包含组件阿里开源组件阿里商业化组件集成 Spring Cloud 组件3、Spring Cloud Alibaba 功能服务注册与发现支持多协议…

python-剑指 Offer 42. 连续子数组的最大和【动态规划经典题解】

一.题目 剑指 Offer 42. 连续子数组的最大和 描述:输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。 要求时间复杂度为O(n)。 示例1: 输入: nums [-2,1,-3,4,-1,2,1,-5,4] 输出: 6 解释: 连续子数组 [4,-1,2…

html初识

HTML认知 文章目录HTML认知语法规范注释标签组成和关系标签的关系标签学习排版系列标签**标题标签****段落标签**换行标签水平线标签文本格式化标签媒体标签图片标签src 目标图片的路径alt 替换文本title 图片的标题width 宽度 / height 高度路径绝对路径相对路径(常…

feature分支开发到一半时切换到bugfix分支,如何暂存数据

1、解决思路在工作过程中,当你正在当前feature分支上进行功能的开发,突然来了一个bug,要创建一个bugfix修复分支进行修复。但是当前feature分支你只开发了一半,显然你去提当前的半成品是不合适的,我们如何处理此类问题…

面试题-----JDBC单例模式(懒汉式和饿汉式)

1.单例概念 作为一种常见的设计模式,单例模式的设计概念是"两个私有,一个公有",即私有属性/成员变量和私有构造,以及公有方法,常用于在整个程序中仅调用一次的代码。 2.具体操作 从单例模式的描述来看,单例模式并不能用于多次频繁调用的设计中,而更适用…

【Linux】进程状态|优先级|进程切换|环境变量

文章目录1. 运行队列和运行状态2. 进程状态3. 两种特殊的进程僵尸进程孤儿进程4. 进程优先级5. 进程切换进程特性进程切换6. 环境变量的基本概念7. PATH环境变量8. 设置和获取环境变量9. 命令行参数1. 运行队列和运行状态 💕 运行队列: 进程是如何在CP…

如何在Net6.0里配置多版本支持并支持注释说明的Swagger

一、前言现在已经进入了微服务的开发时代了,在这个时代,如果有人问你什么是微服务,你说不知道,就有点太丢人了,别人会有异样的眼光看你,俗话说:唾液淹死人。没办法,我们只能去学习新…